<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 <iostream>
#include <cstdio>

#include "Compiler.hpp"

#include "Target.hpp"

#include "Utils.hpp"
#include "DebugStopWatch.hpp"
#include "Options.hpp"

#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "SemanticalException.hpp"
#include "AssemblyFileWriter.hpp"

#include "parser/SpiritParser.hpp"
#include "ast/SourceFile.hpp"

//Annotators
#include "DefaultValues.hpp"
#include "ContextAnnotator.hpp"
#include "FunctionsAnnotator.hpp"
#include "VariablesAnnotator.hpp"

//Checkers
#include "StringChecker.hpp"
#include "TypeChecker.hpp"

//Visitors
#include "DependenciesResolver.hpp"
#include "OptimizationEngine.hpp"
#include "TransformerEngine.hpp"
#include "WarningsEngine.hpp"
#include "DebugVisitor.hpp"

//Three Address Code
#include "tac/Program.hpp"
#include "tac/Compiler.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/TemporaryAllocator.hpp"
#include "tac/LivenessAnalyzer.hpp"
#include "tac/Optimizer.hpp"
#include "tac/Printer.hpp"

//Code generation
#include "asm/IntelX86CodeGenerator.hpp"

#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif

#define TIMER_START(name) StopWatch name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}

using namespace eddic;

void exec(const std::string& command);

int Compiler::compile(const std::string& file) {
    std::cout << "Compile " << file << std::endl;

    if(TargetDetermined && Target64){
        std::cout << "Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly." << std::endl;
    }

    StopWatch timer;

    int code = compileOnly(file);

    std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;

    return code;
}

int Compiler::compileOnly(const std::string& file) {
    std::string output = options["output"].as<std::string>();

    int code = 0;
    try {
        TIMER_START(parsing)

        parser::SpiritParser parser;

        //The program to build
        ast::SourceFile program;

        //Parse the file into the program
        bool parsing = parser.parse(file, program);

        TIMER_END(parsing)

        if(parsing){
            //Symbol tables
            FunctionTable functionTable;
            StringPool pool;

            //Read dependencies
            includeDependencies(program, parser);

            //Apply some cleaning transformations
            clean(program);

            //Annotate the AST with more informations
            defineDefaultValues(program);

            //Fill the string pool
            checkStrings(program, pool);

            //Add some more informations to the AST
            defineContexts(program);
            defineVariables(program);
            defineFunctions(program, functionTable);

            //Transform the AST
            transform(program);

            //Static analysis
            checkTypes(program);

            //Check for warnings
            checkForWarnings(program, functionTable);

            //Optimize the AST
            optimize(program, functionTable, pool);

            tac::Program tacProgram;

            //Generate Three-Address-Code language
            tac::Compiler compiler;
            compiler.compile(program, pool, tacProgram);

            //Separate into basic blocks
            tac::BasicBlockExtractor extractor;
            extractor.extract(tacProgram);

            //Allocate storage for the temporaries that need to be stored
            tac::TemporaryAllocator allocator;
            allocator.allocate(tacProgram);

            tac::Optimizer optimizer;
            optimizer.optimize(tacProgram);

            //Compute liveness of variables
            tac::LivenessAnalyzer liveness;
            liveness.compute(tacProgram);

            //Generate assembly from TAC
            AssemblyFileWriter writer("output.asm");
            as::IntelX86CodeGenerator generator(writer);
            generator.generate(tacProgram, pool);
            writer.write();

            //If it's necessary, assemble and link the assembly
            if(!options.count("assembly")){
                if(options.count("debug")){
                    exec("as -g --32 -o output.o output.asm");
                    exec("ld -m elf_i386 output.o -o " + output);
                } else {
                    exec("as --32 -o output.o output.asm");
                    exec("ld -S -m elf_i386 output.o -o " + output);
                }

                //Remove temporary files
                if(!options.count("keep")){
                    remove("output.asm");
                }

                remove("output.o");
            }
        }
    } catch (const SemanticalException& e) {
        std::cout << e.what() << std::endl;
        code = 1;
    }

    return code;
}

void eddic::defineDefaultValues(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate with default values");
    DefaultValues values;
    values.fill(program);
}

void eddic::defineContexts(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate contexts");
    ContextAnnotator annotator;
    annotator.annotate(program);
}

void eddic::defineVariables(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate variables");
    VariablesAnnotator annotator;
    annotator.annotate(program);
}

void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){
    DebugStopWatch<debug> timer("Annotate functions");
    FunctionsAnnotator annotator;
    annotator.annotate(program, functionTable);
}

void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){
    DebugStopWatch<debug> timer("Strings checking");
    StringChecker checker;
    checker.check(program, pool);
}

void eddic::checkTypes(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Types checking");
    TypeChecker checker;
    checker.check(program);
}

void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){
    DebugStopWatch<debug> timer("Check for warnings");
    WarningsEngine engine;
    engine.check(program, table);
}

void eddic::clean(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Cleaning");
    TransformerEngine engine;
    engine.clean(program);
}

void eddic::transform(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Transformation");
    TransformerEngine engine;
    engine.transform(program);
}

void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){
    DebugStopWatch<debug> timer("Optimization");
    OptimizationEngine engine;
    engine.optimize(program, functionTable, pool);
}

void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){
    DebugStopWatch<debug> timer("Resolve dependencies");
    DependenciesResolver resolver(parser);
    resolver.resolve(sourceFile);
}

void exec(const std::string& command) {
    DebugStopWatch<debug> timer("Exec " + command);

    if(debug){
        std::cout << "eddic : exec command : " << command << std::endl;
    }

    std::string result = execCommand(command);

    if(result.size() > 0){
        std::cout << result << std::endl;
    }
}

void eddic::warn(const std::string& warning){
    std::cout << "warning: " << warning << std::endl;
}
<commit_msg>Use nasm instead of GNU As<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// 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 <iostream>
#include <cstdio>

#include "Compiler.hpp"

#include "Target.hpp"

#include "Utils.hpp"
#include "DebugStopWatch.hpp"
#include "Options.hpp"

#include "StringPool.hpp"
#include "FunctionTable.hpp"
#include "SemanticalException.hpp"
#include "AssemblyFileWriter.hpp"

#include "parser/SpiritParser.hpp"
#include "ast/SourceFile.hpp"

//Annotators
#include "DefaultValues.hpp"
#include "ContextAnnotator.hpp"
#include "FunctionsAnnotator.hpp"
#include "VariablesAnnotator.hpp"

//Checkers
#include "StringChecker.hpp"
#include "TypeChecker.hpp"

//Visitors
#include "DependenciesResolver.hpp"
#include "OptimizationEngine.hpp"
#include "TransformerEngine.hpp"
#include "WarningsEngine.hpp"
#include "DebugVisitor.hpp"

//Three Address Code
#include "tac/Program.hpp"
#include "tac/Compiler.hpp"
#include "tac/BasicBlockExtractor.hpp"
#include "tac/TemporaryAllocator.hpp"
#include "tac/LivenessAnalyzer.hpp"
#include "tac/Optimizer.hpp"
#include "tac/Printer.hpp"

//Code generation
#include "asm/IntelX86CodeGenerator.hpp"

#ifdef DEBUG
static const bool debug = true;
#else
static const bool debug = false;
#endif

#define TIMER_START(name) StopWatch name_timer;
#define TIMER_END(name) if(debug){std::cout << #name << " took " << name_timer.elapsed() << "s" << std::endl;}

using namespace eddic;

void exec(const std::string& command);

int Compiler::compile(const std::string& file) {
    std::cout << "Compile " << file << std::endl;

    if(TargetDetermined && Target64){
        std::cout << "Warning : Looks like you're running a 64 bit system. This compiler only outputs 32 bits assembly." << std::endl;
    }

    StopWatch timer;

    int code = compileOnly(file);

    std::cout << "Compilation took " << timer.elapsed() << "s" << std::endl;

    return code;
}

int Compiler::compileOnly(const std::string& file) {
    std::string output = options["output"].as<std::string>();

    int code = 0;
    try {
        TIMER_START(parsing)

        parser::SpiritParser parser;

        //The program to build
        ast::SourceFile program;

        //Parse the file into the program
        bool parsing = parser.parse(file, program);

        TIMER_END(parsing)

        if(parsing){
            //Symbol tables
            FunctionTable functionTable;
            StringPool pool;

            //Read dependencies
            includeDependencies(program, parser);

            //Apply some cleaning transformations
            clean(program);

            //Annotate the AST with more informations
            defineDefaultValues(program);

            //Fill the string pool
            checkStrings(program, pool);

            //Add some more informations to the AST
            defineContexts(program);
            defineVariables(program);
            defineFunctions(program, functionTable);

            //Transform the AST
            transform(program);

            //Static analysis
            checkTypes(program);

            //Check for warnings
            checkForWarnings(program, functionTable);

            //Optimize the AST
            optimize(program, functionTable, pool);

            tac::Program tacProgram;

            //Generate Three-Address-Code language
            tac::Compiler compiler;
            compiler.compile(program, pool, tacProgram);

            //Separate into basic blocks
            tac::BasicBlockExtractor extractor;
            extractor.extract(tacProgram);

            //Allocate storage for the temporaries that need to be stored
            tac::TemporaryAllocator allocator;
            allocator.allocate(tacProgram);

            tac::Optimizer optimizer;
            optimizer.optimize(tacProgram);

            //Compute liveness of variables
            tac::LivenessAnalyzer liveness;
            liveness.compute(tacProgram);

            //Generate assembly from TAC
            AssemblyFileWriter writer("output.asm");
            as::IntelX86CodeGenerator generator(writer);
            generator.generate(tacProgram, pool);
            writer.write();

            //If it's necessary, assemble and link the assembly
            if(!options.count("assembly")){
                if(options.count("debug")){
                    exec("nasm -g -f elf32 -o output.o output.asm");
                    exec("ld -m elf_i386 output.o -o " + output);
                } else {
                    exec("nasm -f elf32 -o output.o output.asm");
                    exec("ld -S -m elf_i386 output.o -o " + output);
                }

                //Remove temporary files
                if(!options.count("keep")){
                    remove("output.asm");
                }

                remove("output.o");
            }
        }
    } catch (const SemanticalException& e) {
        std::cout << e.what() << std::endl;
        code = 1;
    }

    return code;
}

void eddic::defineDefaultValues(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate with default values");
    DefaultValues values;
    values.fill(program);
}

void eddic::defineContexts(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate contexts");
    ContextAnnotator annotator;
    annotator.annotate(program);
}

void eddic::defineVariables(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Annotate variables");
    VariablesAnnotator annotator;
    annotator.annotate(program);
}

void eddic::defineFunctions(ast::SourceFile& program, FunctionTable& functionTable){
    DebugStopWatch<debug> timer("Annotate functions");
    FunctionsAnnotator annotator;
    annotator.annotate(program, functionTable);
}

void eddic::checkStrings(ast::SourceFile& program, StringPool& pool){
    DebugStopWatch<debug> timer("Strings checking");
    StringChecker checker;
    checker.check(program, pool);
}

void eddic::checkTypes(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Types checking");
    TypeChecker checker;
    checker.check(program);
}

void eddic::checkForWarnings(ast::SourceFile& program, FunctionTable& table){
    DebugStopWatch<debug> timer("Check for warnings");
    WarningsEngine engine;
    engine.check(program, table);
}

void eddic::clean(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Cleaning");
    TransformerEngine engine;
    engine.clean(program);
}

void eddic::transform(ast::SourceFile& program){
    DebugStopWatch<debug> timer("Transformation");
    TransformerEngine engine;
    engine.transform(program);
}

void eddic::optimize(ast::SourceFile& program, FunctionTable& functionTable, StringPool& pool){
    DebugStopWatch<debug> timer("Optimization");
    OptimizationEngine engine;
    engine.optimize(program, functionTable, pool);
}

void eddic::includeDependencies(ast::SourceFile& sourceFile, parser::SpiritParser& parser){
    DebugStopWatch<debug> timer("Resolve dependencies");
    DependenciesResolver resolver(parser);
    resolver.resolve(sourceFile);
}

void exec(const std::string& command) {
    DebugStopWatch<debug> timer("Exec " + command);

    if(debug){
        std::cout << "eddic : exec command : " << command << std::endl;
    }

    std::string result = execCommand(command);

    if(result.size() > 0){
        std::cout << result << std::endl;
    }
}

void eddic::warn(const std::string& warning){
    std::cout << "warning: " << warning << std::endl;
}
<|endoftext|>


<commit_before>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       DNObject.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/

#include  <limal/ca-mgm/DNObject.hpp>
#include  <limal/ca-mgm/CAConfig.hpp>
#include  <limal/ValueRegExCheck.hpp>
#include  <limal/Exception.hpp>
#include  <blocxx/Format.hpp>
#include  <blocxx/Map.hpp>

#include  "DNObject_Priv.hpp"
#include  "Utils.hpp"

namespace LIMAL_NAMESPACE
{
namespace CA_MGM_NAMESPACE
{

using namespace limal;
using namespace blocxx;

RDNObject::RDNObject()
    : type(String()), value(String()), prompt(String()),
      min(0), max(0)
{
}

RDNObject::RDNObject(const RDNObject& rdn)
    : type(rdn.type),
      value(rdn.value),
      prompt(rdn.prompt),
      min(rdn.min),
      max(rdn.max)
{}

RDNObject::~RDNObject()
{}

RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
    if(this == &rdn) return *this;

    type   = rdn.type;
    value  = rdn.value;
    prompt = rdn.prompt;
    min    = rdn.min;
    max    = rdn.max;

    return *this;
}

void
RDNObject::setRDNValue(const String& value)
{
    this->value = value;
}

blocxx::String
RDNObject::getType() const
{
    return type;
}

blocxx::String
RDNObject::getValue() const
{
    return value;
}

blocxx::String
RDNObject::getOpenSSLValue() const
{
    if(value.empty()) return String();

    Map<String, String> opensslKeys;
    opensslKeys["countryName"] = "C";
    opensslKeys["stateOrProvinceName"] = "ST";
    opensslKeys["localityName"] = "L";
    opensslKeys["organizationName"] = "O";
    opensslKeys["organizationalUnitName"] = "OU";
    opensslKeys["commonName"] = "CN";
    opensslKeys["emailAddress"] = "emailAddress";
    //opensslKeys[""] = "";

    String ret;
    Map<String, String>::const_iterator it = opensslKeys.find(type);

    if( it != opensslKeys.end()) {

        ret += (*it).second + "=";

    } else {

        LOGIT_ERROR("Invalid type:" << type);
        BLOCXX_THROW(limal::ValueException, Format("Invalid type:%1", type).c_str());

    }

    PerlRegEx regex("([\\\\/])");
    String v = regex.replace(value, "\\\\\\1", true);

    ret += v;

    return ret;
}

bool
RDNObject::valid() const
{
    if(type.empty()) {
        LOGIT_DEBUG("type is empty");
        return false;
    }

    if(min != 0 && value.UTF8Length() < min) {
        LOGIT_DEBUG("value(" << value << ") is too small. Value has to be a minimal length of " << min);
        return false;
    }

    if(max != 0 && value.UTF8Length() > max) {
        LOGIT_DEBUG("value(" << value << ") is too long. Value has to be a maximal length of " << max);
        return false;
    }

    return true;
}

blocxx::StringArray
RDNObject::verify() const
{
    StringArray result;

    if(type.empty()) {
        result.append("type is empty");
    }

    if(min != 0 && value.UTF8Length() < min) {
        result.append("Value(" + value +
                      ") is too small. Value has to be a minimal length of " + String(min));
    }

    if(max != 0 && value.UTF8Length() > max) {
        result.append("Value(" + value +
                      ") is too long. Value has to be a maximal length of " + String(max));
    }

    LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);

    return result;
}

blocxx::StringArray
RDNObject::dump() const
{
    StringArray result;
    result.append("RDNObject::dump()");

    result.append(type + "=" + value);
    result.append("Prompt:" + prompt);
    result.append("Min:" + String(min));
    result.append("Max:" + String(max));
    return result;
}

bool
operator==(const RDNObject &l, const RDNObject &r)
{
    if(l.getType()  == r.getType() &&
       l.getValue() == r.getValue())
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool
operator<(const RDNObject &l, const RDNObject &r)
{
    if(l.getType()  < r.getType())
    {
        return true;
    }
    else if(l.getType()  == r.getType())
    {
        if(l.getValue() < r.getValue())
        {
            return true;
        }
        else
        {
            return false;
        }
    } else{
        return false;
    }
}

// ######################################################################

DNObject::DNObject()
    : dn(blocxx::List<RDNObject>())
{
    dn.push_back(RDNObject_Priv("countryName", ""));
    dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
    dn.push_back(RDNObject_Priv("localityName", ""));
    dn.push_back(RDNObject_Priv("organizationName", ""));
    dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
    dn.push_back(RDNObject_Priv("commonName", ""));
    dn.push_back(RDNObject_Priv("emailAddress", ""));
}

DNObject::DNObject(CAConfig* caConfig, Type type)
    : dn(blocxx::List<RDNObject>())
{
    if(type == E_Client_Cert || type == E_Server_Cert ||
       type == E_CA_Cert     || type == E_CRL           )
    {
        LOGIT_ERROR("wrong type" << type);
        BLOCXX_THROW(limal::ValueException, Format("wrong type: %1", type).c_str());
    }

    bool p = caConfig->exists(type2Section(type, false), "distinguished_name");
    if(!p) {
        LOGIT_ERROR("missing section 'distinguished_name' in config file");
        BLOCXX_THROW(limal::SyntaxException,
                     "missing section 'distinguished_name' in config file");
    }
    String dnSect = caConfig->getValue(type2Section(type, false),
                                       "distinguished_name");

    StringList dnKeys = caConfig->getKeylist(dnSect);

    if(dnKeys.empty()) {
        LOGIT_ERROR("Can not parse Section " << dnSect);
        BLOCXX_THROW(limal::SyntaxException,
                     Format("Can not parse Section %1", dnSect).c_str());
    }
    StringList::const_iterator it = dnKeys.begin();

    String fieldName;
    String prompt;
    String defaultValue;
    String min("0");
    String max("0");

    Array<Map<String, String> > configDN;

    for(; it != dnKeys.end(); ++it) {

        if((*it).endsWith("_default", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                defaultValue = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else if((*it).endsWith("_min", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                min = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else if((*it).endsWith("_max", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                max = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else {
            // A new fieldName
            //
            // commit values
            if(!fieldName.empty()) {

                dn.push_back(RDNObject_Priv(fieldName, defaultValue,
                                            prompt, min.toUInt32(), max.toUInt32()));
            }

            // reset
            prompt       = String();
            defaultValue = String();
            min          = String("0");
            max          = String("0");

            fieldName    = *it;
            prompt       = caConfig->getValue(dnSect, *it);

        }

    }
    // commit the last values
    if(!fieldName.empty()) {

        dn.push_back(RDNObject_Priv(fieldName, defaultValue,
                                    prompt, min.toUInt32(), max.toUInt32()));
    }
}

DNObject::DNObject(const blocxx::List<RDNObject> &dn)
    : dn(dn)
{
    StringArray r = this->verify();
    if(!r.empty()) {
        BLOCXX_THROW(limal::ValueException, r[0].c_str());
    }
}

DNObject::DNObject(const DNObject& dn)
    : dn(dn.dn)
{}

DNObject::~DNObject()
{}

DNObject&
DNObject::operator=(const DNObject& dn)
{
    if(this == &dn) return *this;

    this->dn = dn.dn;

    return *this;
}

void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
    StringArray r = checkRDNList(dn);
    if(!r.empty()) {
        LOGIT_ERROR(r[0]);
        BLOCXX_THROW(limal::ValueException, r[0].c_str());
    }
    this->dn = dn;
}

blocxx::List<RDNObject>
DNObject::getDN() const
{
    return dn;
}

blocxx::String
DNObject::getOpenSSLString() const
{
    String ret;

    blocxx::List<RDNObject>::const_iterator it = dn.begin();
    for(; it != dn.end(); ++it) {
        if(! (*it).getOpenSSLValue().empty()) {

            ret += "/" + (*it).getOpenSSLValue();

        }
    }

    return ret;
}

bool
DNObject::valid() const
{
    if(dn.empty()) {
        LOGIT_DEBUG("empty DN");
        return false;
    }
    StringArray r = checkRDNList(dn);
    if(!r.empty()) {
        LOGIT_DEBUG(r[0]);
        return false;
    }
    return true;
}

blocxx::StringArray
DNObject::verify() const
{
    StringArray result;

    if(dn.empty()) {
        result.append("empty DN");
    }
    result.appendArray(checkRDNList(dn));

    LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);

    return result;
}

blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
    StringArray result;

    blocxx::List<RDNObject>::const_iterator it = list.begin();
    for(; it != list.end(); ++it) {
        result.appendArray((*it).verify());
    }
    return result;
}

blocxx::StringArray
DNObject::dump() const
{
    StringArray result;
    result.append("DNObject::dump()");

    blocxx::List< RDNObject >::const_iterator it = dn.begin();
    for(; it != dn.end(); ++it) {
        result.appendArray((*it).dump());
    }

    return result;
}

}
}
<commit_msg>remove unused var<commit_after>/*---------------------------------------------------------------------\
|                                                                      |
|                     _     _   _   _     __     _                     |
|                    | |   | | | \_/ |   /  \   | |                    |
|                    | |   | | | |_| |  / /\ \  | |                    |
|                    | |__ | | | | | | / ____ \ | |__                  |
|                    |____||_| |_| |_|/ /    \ \|____|                 |
|                                                                      |
|                             ca-mgm library                           |
|                                                                      |
|                                         (C) SUSE Linux Products GmbH |
\----------------------------------------------------------------------/

  File:       DNObject.cpp

  Author:     <Michael Calmer>     <mc@suse.de>
  Maintainer: <Michael Calmer>     <mc@suse.de>

  Purpose:

/-*/

#include  <limal/ca-mgm/DNObject.hpp>
#include  <limal/ca-mgm/CAConfig.hpp>
#include  <limal/ValueRegExCheck.hpp>
#include  <limal/Exception.hpp>
#include  <blocxx/Format.hpp>
#include  <blocxx/Map.hpp>

#include  "DNObject_Priv.hpp"
#include  "Utils.hpp"

namespace LIMAL_NAMESPACE
{
namespace CA_MGM_NAMESPACE
{

using namespace limal;
using namespace blocxx;

RDNObject::RDNObject()
    : type(String()), value(String()), prompt(String()),
      min(0), max(0)
{
}

RDNObject::RDNObject(const RDNObject& rdn)
    : type(rdn.type),
      value(rdn.value),
      prompt(rdn.prompt),
      min(rdn.min),
      max(rdn.max)
{}

RDNObject::~RDNObject()
{}

RDNObject&
RDNObject::operator=(const RDNObject& rdn)
{
    if(this == &rdn) return *this;

    type   = rdn.type;
    value  = rdn.value;
    prompt = rdn.prompt;
    min    = rdn.min;
    max    = rdn.max;

    return *this;
}

void
RDNObject::setRDNValue(const String& value)
{
    this->value = value;
}

blocxx::String
RDNObject::getType() const
{
    return type;
}

blocxx::String
RDNObject::getValue() const
{
    return value;
}

blocxx::String
RDNObject::getOpenSSLValue() const
{
    if(value.empty()) return String();

    Map<String, String> opensslKeys;
    opensslKeys["countryName"] = "C";
    opensslKeys["stateOrProvinceName"] = "ST";
    opensslKeys["localityName"] = "L";
    opensslKeys["organizationName"] = "O";
    opensslKeys["organizationalUnitName"] = "OU";
    opensslKeys["commonName"] = "CN";
    opensslKeys["emailAddress"] = "emailAddress";
    //opensslKeys[""] = "";

    String ret;
    Map<String, String>::const_iterator it = opensslKeys.find(type);

    if( it != opensslKeys.end()) {

        ret += (*it).second + "=";

    } else {

        LOGIT_ERROR("Invalid type:" << type);
        BLOCXX_THROW(limal::ValueException, Format("Invalid type:%1", type).c_str());

    }

    PerlRegEx regex("([\\\\/])");
    String v = regex.replace(value, "\\\\\\1", true);

    ret += v;

    return ret;
}

bool
RDNObject::valid() const
{
    if(type.empty()) {
        LOGIT_DEBUG("type is empty");
        return false;
    }

    if(min != 0 && value.UTF8Length() < min) {
        LOGIT_DEBUG("value(" << value << ") is too small. Value has to be a minimal length of " << min);
        return false;
    }

    if(max != 0 && value.UTF8Length() > max) {
        LOGIT_DEBUG("value(" << value << ") is too long. Value has to be a maximal length of " << max);
        return false;
    }

    return true;
}

blocxx::StringArray
RDNObject::verify() const
{
    StringArray result;

    if(type.empty()) {
        result.append("type is empty");
    }

    if(min != 0 && value.UTF8Length() < min) {
        result.append("Value(" + value +
                      ") is too small. Value has to be a minimal length of " + String(min));
    }

    if(max != 0 && value.UTF8Length() > max) {
        result.append("Value(" + value +
                      ") is too long. Value has to be a maximal length of " + String(max));
    }

    LOGIT_DEBUG_STRINGARRAY("RDNObject::verify()", result);

    return result;
}

blocxx::StringArray
RDNObject::dump() const
{
    StringArray result;
    result.append("RDNObject::dump()");

    result.append(type + "=" + value);
    result.append("Prompt:" + prompt);
    result.append("Min:" + String(min));
    result.append("Max:" + String(max));
    return result;
}

bool
operator==(const RDNObject &l, const RDNObject &r)
{
    if(l.getType()  == r.getType() &&
       l.getValue() == r.getValue())
    {
        return true;
    }
    else
    {
        return false;
    }
}

bool
operator<(const RDNObject &l, const RDNObject &r)
{
    if(l.getType()  < r.getType())
    {
        return true;
    }
    else if(l.getType()  == r.getType())
    {
        if(l.getValue() < r.getValue())
        {
            return true;
        }
        else
        {
            return false;
        }
    } else{
        return false;
    }
}

// ######################################################################

DNObject::DNObject()
    : dn(blocxx::List<RDNObject>())
{
    dn.push_back(RDNObject_Priv("countryName", ""));
    dn.push_back(RDNObject_Priv("stateOrProvinceName", ""));
    dn.push_back(RDNObject_Priv("localityName", ""));
    dn.push_back(RDNObject_Priv("organizationName", ""));
    dn.push_back(RDNObject_Priv("organizationalUnitName", ""));
    dn.push_back(RDNObject_Priv("commonName", ""));
    dn.push_back(RDNObject_Priv("emailAddress", ""));
}

DNObject::DNObject(CAConfig* caConfig, Type type)
    : dn(blocxx::List<RDNObject>())
{
    if(type == E_Client_Cert || type == E_Server_Cert ||
       type == E_CA_Cert     || type == E_CRL           )
    {
        LOGIT_ERROR("wrong type" << type);
        BLOCXX_THROW(limal::ValueException, Format("wrong type: %1", type).c_str());
    }

    bool p = caConfig->exists(type2Section(type, false), "distinguished_name");
    if(!p) {
        LOGIT_ERROR("missing section 'distinguished_name' in config file");
        BLOCXX_THROW(limal::SyntaxException,
                     "missing section 'distinguished_name' in config file");
    }
    String dnSect = caConfig->getValue(type2Section(type, false),
                                       "distinguished_name");

    StringList dnKeys = caConfig->getKeylist(dnSect);

    if(dnKeys.empty()) {
        LOGIT_ERROR("Can not parse Section " << dnSect);
        BLOCXX_THROW(limal::SyntaxException,
                     Format("Can not parse Section %1", dnSect).c_str());
    }
    StringList::const_iterator it = dnKeys.begin();

    String fieldName;
    String prompt;
    String defaultValue;
    String min("0");
    String max("0");

    for(; it != dnKeys.end(); ++it) {

        if((*it).endsWith("_default", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                defaultValue = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else if((*it).endsWith("_min", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                min = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else if((*it).endsWith("_max", String::E_CASE_INSENSITIVE)) {

            if((*it).startsWith(fieldName, String::E_CASE_INSENSITIVE)) {

                max = caConfig->getValue(dnSect, *it);

            } else {
                LOGIT_INFO("Wrong order of section '" << dnSect <<
                           "'. FieldName is '" << fieldName <<
                           "' but parsed Key is '" << *it <<
                           "'. Ignoring value.");
                continue;
            }

        } else {
            // A new fieldName
            //
            // commit values
            if(!fieldName.empty()) {

                dn.push_back(RDNObject_Priv(fieldName, defaultValue,
                                            prompt, min.toUInt32(), max.toUInt32()));
            }

            // reset
            prompt       = String();
            defaultValue = String();
            min          = String("0");
            max          = String("0");

            fieldName    = *it;
            prompt       = caConfig->getValue(dnSect, *it);

        }

    }
    // commit the last values
    if(!fieldName.empty()) {

        dn.push_back(RDNObject_Priv(fieldName, defaultValue,
                                    prompt, min.toUInt32(), max.toUInt32()));
    }
}

DNObject::DNObject(const blocxx::List<RDNObject> &dn)
    : dn(dn)
{
    StringArray r = this->verify();
    if(!r.empty()) {
        BLOCXX_THROW(limal::ValueException, r[0].c_str());
    }
}

DNObject::DNObject(const DNObject& dn)
    : dn(dn.dn)
{}

DNObject::~DNObject()
{}

DNObject&
DNObject::operator=(const DNObject& dn)
{
    if(this == &dn) return *this;

    this->dn = dn.dn;

    return *this;
}

void
DNObject::setDN(const blocxx::List<RDNObject> &dn)
{
    StringArray r = checkRDNList(dn);
    if(!r.empty()) {
        LOGIT_ERROR(r[0]);
        BLOCXX_THROW(limal::ValueException, r[0].c_str());
    }
    this->dn = dn;
}

blocxx::List<RDNObject>
DNObject::getDN() const
{
    return dn;
}

blocxx::String
DNObject::getOpenSSLString() const
{
    String ret;

    blocxx::List<RDNObject>::const_iterator it = dn.begin();
    for(; it != dn.end(); ++it) {
        if(! (*it).getOpenSSLValue().empty()) {

            ret += "/" + (*it).getOpenSSLValue();

        }
    }

    return ret;
}

bool
DNObject::valid() const
{
    if(dn.empty()) {
        LOGIT_DEBUG("empty DN");
        return false;
    }
    StringArray r = checkRDNList(dn);
    if(!r.empty()) {
        LOGIT_DEBUG(r[0]);
        return false;
    }
    return true;
}

blocxx::StringArray
DNObject::verify() const
{
    StringArray result;

    if(dn.empty()) {
        result.append("empty DN");
    }
    result.appendArray(checkRDNList(dn));

    LOGIT_DEBUG_STRINGARRAY("DNObject::verify()", result);

    return result;
}

blocxx::StringArray
DNObject::checkRDNList(const blocxx::List<RDNObject>& list) const
{
    StringArray result;

    blocxx::List<RDNObject>::const_iterator it = list.begin();
    for(; it != list.end(); ++it) {
        result.appendArray((*it).verify());
    }
    return result;
}

blocxx::StringArray
DNObject::dump() const
{
    StringArray result;
    result.append("DNObject::dump()");

    blocxx::List< RDNObject >::const_iterator it = dn.begin();
    for(; it != dn.end(); ++it) {
        result.appendArray((*it).dump());
    }

    return result;
}

}
}
<|endoftext|>


<commit_before>#include "protocol.h"

Protocol::Protocol() : floodThrottle(true), nextID(0) {}

void Protocol::connectServer() {
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "protocol-client-connect-" + serverName, "Connecting to " + serverName + " ...");
	Config* config = Config::getHandle();
	std::unordered_map<std::string, std::string> configBlock = config->getSingleBlockOnConditions("server", std::unordered_map<std::string, std::string> { { "name", serverName } });
	serverAddress = configBlock["address"];
	serverPort = configBlock["port"];
	serverBindAddr = configBlock["bind"];
	floodThrottle = Config::makeBool(configBlock["floodthrottle"]);
	if (serverAddress.empty() || serverPort.empty()) {
		logger->log(LOG_ERROR, "protocol-client-connect-" + serverName, "Cannot connect to " + serverName + " because the configuration is incomplete or invalid.");
		throw ServerBadConfiguration ();
	}
	std::list<std::unordered_map<std::string, std::string>> clientConfigs = config->getBlocksOnConditions("client", std::unordered_map<std::string, std::string> { { "server", serverName } });
	for (auto clientConf : clientConfigs) {
		std::string nick (clientConf["nick"]);
		std::string ident (clientConf["ident"]);
		std::string gecos (clientConf["gecos"]);
		std::string password (clientConf["password"]);
		std::string socket (clientConf["socket"]);
		if (nick.empty() || ident.empty() || gecos.empty() || socket.empty()) {
			logger->log(LOG_ERROR, "protocol-client-connect-" + serverName, "An improperly configured client was encountered.  Client not added.");
			continue;
		}
		std::string id (clientConf["id"]);
		if (id.empty()) {
			while (users.find(id) != users.end())
				id = getNextID();
		}
		std::shared_ptr<Client> newClient (new Client (std::move(id), std::move(nick), std::move(ident), std::move(gecos), std::move(password), std::move(socket), this));
		clients.insert(std::pair<std::string, std::shared_ptr<Client>> (id, newClient));
		users.insert(std::pair<std::string, std::shared_ptr<User>> (id, static_cast<std::shared_ptr<User>>(newClient)));
	}
}

bool Protocol::connected() {
	bool connectedClientsExist = false;
	std::list<std::string> removeClients;
	for (auto client : clients) {
		if (client.second->checkConnection())
			connectedClientsExist = true;
		else if (client.second->wantsToReconnect())
			client.second->doReconnect();
		else
			removeClients.push_back(client.first);
	}
	for (auto clientID : removeClients) {
		clients.erase(clientID);
		auto clientUser = users.find(clientID);
		if (clientUser != users.end())
			users.erase(clientUser);
	}
	return connectedClientsExist;
}

bool Protocol::shouldUnload() {
	return clients.empty();
}

void Protocol::disconnect(const std::string& reason) {
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEFAULT, "protocol-client-connection-" + serverName, "Disconnecting all clients");
	for (auto client : clients)
		client.second->disconnect(reason);
}

void Protocol::onRehash() {

}

void Protocol::sendMsg(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendNotice(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::setMode(const std::string& client, const std::string& target, const std::list<std::tuple<bool, std::string, std::string>>& modes, const std::map<std::string, std::string>& tags) {

}

void Protocol::joinChan(const std::string& client, const std::string& channel, const std::map<std::string, std::string>& tags) {

}

void Protocol::joinChan(const std::string& client, const std::string& channel, const std::string& key, const std::map<std::string, std::string>& tags) {

}

void Protocol::partChan(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::kickUser(const std::string& client, const std::string& channel, const std::string& user, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::setTopic(const std::string& client, const std::string& channel, const std::string& topic, const std::map<std::string, std::string>& tags) {

}

void Protocol::inviteUser(const std::string& client, const std::string& channel, const std::string& user, const std::map<std::string, std::string>& tags) {

}

void Protocol::knock(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::changeNick(const std::string& client, const std::string& newNick, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendPing(const std::string& client, const std::string& data, const std::map<std::string, std::string>& tags) {

}

void Protocol::setAway(const std::string& client, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::setUnaway(const std::string& client, const std::map<std::string, std::string>& tags) {

}

void Protocol::oper(const std::string& client, const std::string& username, const std::string& password, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendWallops(const std::string& client, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendOtherData(const std::string& client, const IRCMessage* line) {

}

std::string Protocol::addClient(const std::string& nick, const std::string& ident, const std::string& gecos) {

}

void Protocol::removeClient(const std::string& client) {

}

std::set<std::string> Protocol::serverCapabilities() {

}

std::set<char> Protocol::chanTypes() {

}

std::list<std::pair<ModeType, std::string>> Protocol::allChanModes() {

}

ModeType Protocol::chanModeType(const std::string& mode) {

}

char Protocol::prefixSymbol(const std::string& mode) {

}

std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, const std::string& status1) {

}

std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, char status1) {

}

std::pair<std::string, char> Protocol::compareStatus(char status0, char status1) {

}

std::string Protocol::chanTopic(const std::string& channel) {

}

std::string Protocol::chanTopicSetter(const std::string& channel) {

}

time_t Protocol::chanTopicTimestamp(const std::string& channel) {

}

time_t Protocol::chanTimestamp(const std::string& channel) {

}

std::list<std::string> Protocol::chanUsers(const std::string& channel) {

}

bool Protocol::userInChan(const std::string& channel, const std::string& user) {

}

std::pair<std::string, char> Protocol::userStatus(const std::string& channel, const std::string& user) {

}

bool Protocol::userHasStatus(const std::string& channel, const std::string& user, const std::string& status) {

}

bool Protocol::userHasStatus(const std::string& channel, const std::string& user, char status) {

}

bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, const std::string& status) {

}

bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, char status) {

}

std::map<std::string, std::string> Protocol::chanModes(const std::string& channel) {

}

bool Protocol::chanHasMode(const std::string& channel, const std::string& mode) {

}

std::string Protocol::chanModeParam(const std::string& channel, const std::string& mode) {

}

std::list<std::string> Protocol::chanListModeList(const std::string& channel, const std::string& mode) {

}

std::list<std::string> Protocol::clientList() {

}

std::string Protocol::userNick(const std::string& user) {

}

std::string Protocol::userIdent(const std::string& user) {

}

std::string Protocol::userHost(const std::string& user) {

}

std::string Protocol::userGecos(const std::string& user) {

}

std::string Protocol::idFromNick(const std::string& nick) {

}

std::list<std::pair<ModeType, std::string>> Protocol::allUserModes() {

}

ModeType Protocol::userModeType(const std::string& mode) {

}

std::map<std::string, std::string> Protocol::userModes(const std::string& user) {

}

bool Protocol::userHasMode(const std::string& user, const std::string& mode) {

}

std::string Protocol::userModeParam(const std::string& user, const std::string& mode) {

}

std::list<std::string> Protocol::userListModeList(const std::string& user, const std::string& listMode) {

}

std::set<std::string> Protocol::userChans(const std::string& user) {

}

std::string Protocol::servName() {
	return serverName;
}

std::shared_ptr<Socket> Protocol::obtainSocket(const std::string& sockType) {
	return assignSocket(sockType);
}

void Protocol::connectSocket(const std::shared_ptr<Socket> sock) {
	sock->connectServer(serverAddress, serverPort, serverBindAddr);
}

bool Protocol::floodThrottleInEffect() {
	return floodThrottle;
}

void Protocol::processIncoming(const std::string& client, const IRCMessage* message) {
	MutexLocker mutexLock (&processMutex);
	// TODO: the rest of this
}

std::string Protocol::getNextID() {
	std::ostringstream currID;
	currID << nextID;
	nextID++;
	return currID.str();
}<commit_msg>Toggle flood throttle on rehash<commit_after>#include "protocol.h"

Protocol::Protocol() : floodThrottle(true), nextID(0) {}

void Protocol::connectServer() {
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEBUG, "protocol-client-connect-" + serverName, "Connecting to " + serverName + " ...");
	Config* config = Config::getHandle();
	std::unordered_map<std::string, std::string> configBlock = config->getSingleBlockOnConditions("server", std::unordered_map<std::string, std::string> { { "name", serverName } });
	serverAddress = configBlock["address"];
	serverPort = configBlock["port"];
	serverBindAddr = configBlock["bind"];
	floodThrottle = Config::makeBool(configBlock["floodthrottle"]);
	if (serverAddress.empty() || serverPort.empty()) {
		logger->log(LOG_ERROR, "protocol-client-connect-" + serverName, "Cannot connect to " + serverName + " because the configuration is incomplete or invalid.");
		throw ServerBadConfiguration ();
	}
	std::list<std::unordered_map<std::string, std::string>> clientConfigs = config->getBlocksOnConditions("client", std::unordered_map<std::string, std::string> { { "server", serverName } });
	for (auto clientConf : clientConfigs) {
		std::string nick (clientConf["nick"]);
		std::string ident (clientConf["ident"]);
		std::string gecos (clientConf["gecos"]);
		std::string password (clientConf["password"]);
		std::string socket (clientConf["socket"]);
		if (nick.empty() || ident.empty() || gecos.empty() || socket.empty()) {
			logger->log(LOG_ERROR, "protocol-client-connect-" + serverName, "An improperly configured client was encountered.  Client not added.");
			continue;
		}
		std::string id (clientConf["id"]);
		if (id.empty()) {
			while (users.find(id) != users.end())
				id = getNextID();
		}
		std::shared_ptr<Client> newClient (new Client (std::move(id), std::move(nick), std::move(ident), std::move(gecos), std::move(password), std::move(socket), this));
		clients.insert(std::pair<std::string, std::shared_ptr<Client>> (id, newClient));
		users.insert(std::pair<std::string, std::shared_ptr<User>> (id, static_cast<std::shared_ptr<User>>(newClient)));
	}
}

bool Protocol::connected() {
	bool connectedClientsExist = false;
	std::list<std::string> removeClients;
	for (auto client : clients) {
		if (client.second->checkConnection())
			connectedClientsExist = true;
		else if (client.second->wantsToReconnect())
			client.second->doReconnect();
		else
			removeClients.push_back(client.first);
	}
	for (auto clientID : removeClients) {
		clients.erase(clientID);
		auto clientUser = users.find(clientID);
		if (clientUser != users.end())
			users.erase(clientUser);
	}
	return connectedClientsExist;
}

bool Protocol::shouldUnload() {
	return clients.empty();
}

void Protocol::disconnect(const std::string& reason) {
	LogManager* logger = LogManager::getHandle();
	logger->log(LOG_DEFAULT, "protocol-client-connection-" + serverName, "Disconnecting all clients");
	for (auto client : clients)
		client.second->disconnect(reason);
}

void Protocol::onRehash() {
	Config* config = Config::getHandle();
	std::unordered_map<std::string, std::string> configBlock = config->getSingleBlockOnConditions("server", std::unordered_map<std::string, std::string> { { "name", serverName } });
	bool newFloodThrottle = Config::makeBool(configBlock["floodthrottle"]);
	if (newFloodThrottle != floodThrottle) {
		floodThrottle = newFloodThrottle;
		if (floodThrottle) {
			for (auto client : clients)
				client.second->startFloodThrottle();
		} else {
			for (auto client : clients)
				client.second->endFloodThrottle();
		}
	}
}

void Protocol::sendMsg(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendNotice(const std::string& client, const std::string& target, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::setMode(const std::string& client, const std::string& target, const std::list<std::tuple<bool, std::string, std::string>>& modes, const std::map<std::string, std::string>& tags) {

}

void Protocol::joinChan(const std::string& client, const std::string& channel, const std::map<std::string, std::string>& tags) {

}

void Protocol::joinChan(const std::string& client, const std::string& channel, const std::string& key, const std::map<std::string, std::string>& tags) {

}

void Protocol::partChan(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::kickUser(const std::string& client, const std::string& channel, const std::string& user, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::setTopic(const std::string& client, const std::string& channel, const std::string& topic, const std::map<std::string, std::string>& tags) {

}

void Protocol::inviteUser(const std::string& client, const std::string& channel, const std::string& user, const std::map<std::string, std::string>& tags) {

}

void Protocol::knock(const std::string& client, const std::string& channel, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::changeNick(const std::string& client, const std::string& newNick, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendPing(const std::string& client, const std::string& data, const std::map<std::string, std::string>& tags) {

}

void Protocol::setAway(const std::string& client, const std::string& reason, const std::map<std::string, std::string>& tags) {

}

void Protocol::setUnaway(const std::string& client, const std::map<std::string, std::string>& tags) {

}

void Protocol::oper(const std::string& client, const std::string& username, const std::string& password, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendWallops(const std::string& client, const std::string& message, const std::map<std::string, std::string>& tags) {

}

void Protocol::sendOtherData(const std::string& client, const IRCMessage* line) {

}

std::string Protocol::addClient(const std::string& nick, const std::string& ident, const std::string& gecos) {

}

void Protocol::removeClient(const std::string& client) {

}

std::set<std::string> Protocol::serverCapabilities() {

}

std::set<char> Protocol::chanTypes() {

}

std::list<std::pair<ModeType, std::string>> Protocol::allChanModes() {

}

ModeType Protocol::chanModeType(const std::string& mode) {

}

char Protocol::prefixSymbol(const std::string& mode) {

}

std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, const std::string& status1) {

}

std::pair<std::string, char> Protocol::compareStatus(const std::string& status0, char status1) {

}

std::pair<std::string, char> Protocol::compareStatus(char status0, char status1) {

}

std::string Protocol::chanTopic(const std::string& channel) {

}

std::string Protocol::chanTopicSetter(const std::string& channel) {

}

time_t Protocol::chanTopicTimestamp(const std::string& channel) {

}

time_t Protocol::chanTimestamp(const std::string& channel) {

}

std::list<std::string> Protocol::chanUsers(const std::string& channel) {

}

bool Protocol::userInChan(const std::string& channel, const std::string& user) {

}

std::pair<std::string, char> Protocol::userStatus(const std::string& channel, const std::string& user) {

}

bool Protocol::userHasStatus(const std::string& channel, const std::string& user, const std::string& status) {

}

bool Protocol::userHasStatus(const std::string& channel, const std::string& user, char status) {

}

bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, const std::string& status) {

}

bool Protocol::userHasStatusOrGreater(const std::string& channel, const std::string& user, char status) {

}

std::map<std::string, std::string> Protocol::chanModes(const std::string& channel) {

}

bool Protocol::chanHasMode(const std::string& channel, const std::string& mode) {

}

std::string Protocol::chanModeParam(const std::string& channel, const std::string& mode) {

}

std::list<std::string> Protocol::chanListModeList(const std::string& channel, const std::string& mode) {

}

std::list<std::string> Protocol::clientList() {

}

std::string Protocol::userNick(const std::string& user) {

}

std::string Protocol::userIdent(const std::string& user) {

}

std::string Protocol::userHost(const std::string& user) {

}

std::string Protocol::userGecos(const std::string& user) {

}

std::string Protocol::idFromNick(const std::string& nick) {

}

std::list<std::pair<ModeType, std::string>> Protocol::allUserModes() {

}

ModeType Protocol::userModeType(const std::string& mode) {

}

std::map<std::string, std::string> Protocol::userModes(const std::string& user) {

}

bool Protocol::userHasMode(const std::string& user, const std::string& mode) {

}

std::string Protocol::userModeParam(const std::string& user, const std::string& mode) {

}

std::list<std::string> Protocol::userListModeList(const std::string& user, const std::string& listMode) {

}

std::set<std::string> Protocol::userChans(const std::string& user) {

}

std::string Protocol::servName() {
	return serverName;
}

std::shared_ptr<Socket> Protocol::obtainSocket(const std::string& sockType) {
	return assignSocket(sockType);
}

void Protocol::connectSocket(const std::shared_ptr<Socket> sock) {
	sock->connectServer(serverAddress, serverPort, serverBindAddr);
}

bool Protocol::floodThrottleInEffect() {
	return floodThrottle;
}

void Protocol::processIncoming(const std::string& client, const IRCMessage* message) {
	MutexLocker mutexLock (&processMutex);
	// TODO: the rest of this
}

std::string Protocol::getNextID() {
	std::ostringstream currID;
	currID << nextID;
	nextID++;
	return currID.str();
}<|endoftext|>


<commit_before>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <test/fuzz/fuzz.h>
#include <util/memory.h>

void initialize()
{
    static const ECCVerifyHandle verify_handle;
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string descriptor(buffer.begin(), buffer.end());
    FlatSigningProvider signing_provider;
    std::string error;
    for (const bool require_checksum : {true, false}) {
        Parse(descriptor, signing_provider, error, require_checksum);
    }
}
<commit_msg>fuzz: Extend descriptor fuzz test<commit_after>// Copyright (c) 2009-2019 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include <chainparams.h>
#include <pubkey.h>
#include <script/descriptor.h>
#include <test/fuzz/fuzz.h>
#include <util/memory.h>

void initialize()
{
    static const ECCVerifyHandle verify_handle;
    SelectParams(CBaseChainParams::REGTEST);
}

void test_one_input(const std::vector<uint8_t>& buffer)
{
    const std::string descriptor(buffer.begin(), buffer.end());
    FlatSigningProvider signing_provider;
    std::string error;
    for (const bool require_checksum : {true, false}) {
        const auto desc = Parse(descriptor, signing_provider, error, require_checksum);
        if (desc) {
            (void)desc->ToString();
            (void)desc->IsRange();
            (void)desc->IsSolvable();
        }
    }
}
<|endoftext|>


<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "policy/fees.h"
#include "txmempool.h"
#include "uint256.h"
#include "util.h"

#include "test/test_pivx.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(policyestimator_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
{
    CTxMemPool mpool(CFeeRate(1000));
    TestMemPoolEntryHelper entry;
    CAmount basefee(2000);
    double basepri = 1e6;
    CAmount deltaFee(100);
    double deltaPri=5e5;
    std::vector<CAmount> feeV[2];
    std::vector<double> priV[2];

    // Populate vectors of increasing fees or priorities
    for (int j = 0; j < 10; j++) {
        //V[0] is for fee transactions
        feeV[0].push_back(basefee * (j+1));
        priV[0].push_back(0);
        //V[1] is for priority transactions
        feeV[1].push_back(CAmount(0));
        priV[1].push_back(basepri * pow(10, j+1));
    }

    // Store the hashes of transactions that have been
    // added to the mempool by their associate fee/pri
    // txHashes[j] is populated with transactions either of
    // fee = basefee * (j+1)  OR  pri = 10^6 * 10^(j+1)
    std::vector<uint256> txHashes[10];

    // Create a transaction template
    CScript garbage;
    for (unsigned int i = 0; i < 128; i++)
        garbage.push_back('X');
    CMutableTransaction tx;
    std::list<CTransaction> dummyConflicted;
    tx.vin.resize(1);
    tx.vin[0].scriptSig = garbage;
    tx.vout.resize(1);
    tx.vout[0].nValue=0LL;
    CFeeRate baseRate(basefee, ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));

    // Create a fake block
    std::vector<CTransaction> block;
    int blocknum = 0;

    // Loop through 200 blocks
    // At a decay .998 and 4 fee transactions per block
    // This makes the tx count about 1.33 per bucket, above the 1 threshold
    while (blocknum < 200) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k; // make transaction unique
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                txHashes[j].push_back(hash);
            }
        }
        //Create blocks where higher fee/pri txs are included more often
        for (int h = 0; h <= blocknum%10; h++) {
            // 10/10 blocks add highest fee/pri transactions
            // 9/10 blocks add 2nd highest and so on until ...
            // 1/10 blocks add lowest fee/pri transactions
            while (txHashes[9-h].size()) {
                CTransaction btx;
                if (mpool.lookup(txHashes[9-h].back(), btx))
                    block.push_back(btx);
                txHashes[9-h].pop_back();
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
        block.clear();
        if (blocknum == 30) {
            // At this point we should need to combine 5 buckets to get enough data points
            // So estimateFee(1,2,3) should fail and estimateFee(4) should return somewhere around
            // 8*baserate.  estimateFee(4) %'s are 100,100,100,100,90 = average 98%
            BOOST_CHECK(mpool.estimateFee(1) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(2) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(3) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() < 8*baseRate.GetFeePerK() + deltaFee);
            BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() > 8*baseRate.GetFeePerK() - deltaFee);
            int answerFound;
            BOOST_CHECK(mpool.estimateSmartFee(1, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(3, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(4, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(8, &answerFound) == mpool.estimateFee(8) && answerFound == 8);
        }
    }

    std::vector<CAmount> origFeeEst;
    std::vector<double> origPriEst;
    // Highest feerate is 10*baseRate and gets in all blocks,
    // second highest feerate is 9*baseRate and gets in 9/10 blocks = 90%,
    // third highest feerate is 8*base rate, and gets in 8/10 blocks = 80%,
    // so estimateFee(1) should return 10*baseRate.
    // Second highest feerate has 100% chance of being included by 2 blocks,
    // so estimateFee(2) should return 9*baseRate etc...
    for (int i = 1; i < 10;i++) {
        origFeeEst.push_back(mpool.estimateFee(i).GetFeePerK());
        origPriEst.push_back(mpool.estimatePriority(i));
        if (i > 1) { // Fee estimates should be monotonically decreasing
            BOOST_CHECK(origFeeEst[i-1] <= origFeeEst[i-2]);
            BOOST_CHECK(origPriEst[i-1] <= origPriEst[i-2]);
        }
        int mult = 11-i;
        BOOST_CHECK(origFeeEst[i-1] < mult*baseRate.GetFeePerK() + deltaFee);
        BOOST_CHECK(origFeeEst[i-1] > mult*baseRate.GetFeePerK() - deltaFee);
        //BOOST_CHECK(origPriEst[i-1] < pow(10,mult) * basepri + deltaPri);
        BOOST_CHECK(origPriEst[i-1] > pow(10,mult) * basepri - deltaPri);
    }

    // Mine 50 more blocks with no transactions happening, estimates shouldn't change
    // We haven't decayed the moving average enough so we still have enough data points in every bucket
    while (blocknum < 250)
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);

    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] + deltaFee);
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] + deltaPri);
        BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
    }

    // Mine 15 more blocks with lots of transactions happening and not getting mined
    // Estimates should go up
    while (blocknum < 265) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k;
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                txHashes[j].push_back(hash);
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
    }

    int answerFound;
    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i) == CFeeRate(0) || mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimateSmartFee(i, &answerFound).GetFeePerK() > origFeeEst[answerFound-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) == -1 || mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
        BOOST_CHECK(mpool.estimateSmartPriority(i, &answerFound) > origPriEst[answerFound-1] - deltaPri);
    }

    // Mine all those transactions
    // Estimates should still not be below original
    for (int j = 0; j < 10; j++) {
        while(txHashes[j].size()) {
            CTransaction btx;
            if (mpool.lookup(txHashes[j].back(), btx))
                block.push_back(btx);
            txHashes[j].pop_back();
        }
    }
    mpool.removeForBlock(block, 265, dummyConflicted);
    block.clear();
    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
    }

    // Mine 200 more blocks where everything is mined every block
    // Estimates should be below original estimates
    while (blocknum < 465) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k;
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                CTransaction btx;
                if (mpool.lookup(hash, btx))
                    block.push_back(btx);
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
        block.clear();
    }
    for (int i = 1; i < 10; i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] - deltaPri);
    }

    // Test that if the mempool is limited, estimateSmartFee won't return a value below the mempool min fee
    // and that estimateSmartPriority returns essentially an infinite value
    mpool.addUnchecked(tx.GetHash(),  entry.Fee(feeV[0][5]).Time(GetTime()).Priority(priV[1][5]).Height(blocknum).FromTx(tx, &mpool));
    // evict that transaction which should set a mempool min fee of minRelayTxFee + feeV[0][5]
    mpool.TrimToSize(1);
    BOOST_CHECK(mpool.GetMinFee(1).GetFeePerK() > feeV[0][5]);
    for (int i = 1; i < 10; i++) {
        BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.estimateFee(i).GetFeePerK());
        BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.GetMinFee(1).GetFeePerK());
        BOOST_CHECK(mpool.estimateSmartPriority(i) == INF_PRIORITY);
    }
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>[Trivial] Temporarily comment-out priority check in policyestimator test<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "policy/fees.h"
#include "txmempool.h"
#include "uint256.h"
#include "util.h"

#include "test/test_pivx.h"

#include <boost/test/unit_test.hpp>

BOOST_FIXTURE_TEST_SUITE(policyestimator_tests, BasicTestingSetup)

BOOST_AUTO_TEST_CASE(BlockPolicyEstimates)
{
    CTxMemPool mpool(CFeeRate(1000));
    TestMemPoolEntryHelper entry;
    CAmount basefee(2000);
    double basepri = 1e6;
    CAmount deltaFee(100);
    double deltaPri=5e5;
    std::vector<CAmount> feeV[2];
    std::vector<double> priV[2];

    // Populate vectors of increasing fees or priorities
    for (int j = 0; j < 10; j++) {
        //V[0] is for fee transactions
        feeV[0].push_back(basefee * (j+1));
        priV[0].push_back(0);
        //V[1] is for priority transactions
        feeV[1].push_back(CAmount(0));
        priV[1].push_back(basepri * pow(10, j+1));
    }

    // Store the hashes of transactions that have been
    // added to the mempool by their associate fee/pri
    // txHashes[j] is populated with transactions either of
    // fee = basefee * (j+1)  OR  pri = 10^6 * 10^(j+1)
    std::vector<uint256> txHashes[10];

    // Create a transaction template
    CScript garbage;
    for (unsigned int i = 0; i < 128; i++)
        garbage.push_back('X');
    CMutableTransaction tx;
    std::list<CTransaction> dummyConflicted;
    tx.vin.resize(1);
    tx.vin[0].scriptSig = garbage;
    tx.vout.resize(1);
    tx.vout[0].nValue=0LL;
    CFeeRate baseRate(basefee, ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION));

    // Create a fake block
    std::vector<CTransaction> block;
    int blocknum = 0;

    // Loop through 200 blocks
    // At a decay .998 and 4 fee transactions per block
    // This makes the tx count about 1.33 per bucket, above the 1 threshold
    while (blocknum < 200) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k; // make transaction unique
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                txHashes[j].push_back(hash);
            }
        }
        //Create blocks where higher fee/pri txs are included more often
        for (int h = 0; h <= blocknum%10; h++) {
            // 10/10 blocks add highest fee/pri transactions
            // 9/10 blocks add 2nd highest and so on until ...
            // 1/10 blocks add lowest fee/pri transactions
            while (txHashes[9-h].size()) {
                CTransaction btx;
                if (mpool.lookup(txHashes[9-h].back(), btx))
                    block.push_back(btx);
                txHashes[9-h].pop_back();
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
        block.clear();
        if (blocknum == 30) {
            // At this point we should need to combine 5 buckets to get enough data points
            // So estimateFee(1,2,3) should fail and estimateFee(4) should return somewhere around
            // 8*baserate.  estimateFee(4) %'s are 100,100,100,100,90 = average 98%
            BOOST_CHECK(mpool.estimateFee(1) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(2) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(3) == CFeeRate(0));
            BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() < 8*baseRate.GetFeePerK() + deltaFee);
            BOOST_CHECK(mpool.estimateFee(4).GetFeePerK() > 8*baseRate.GetFeePerK() - deltaFee);
            int answerFound;
            BOOST_CHECK(mpool.estimateSmartFee(1, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(3, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(4, &answerFound) == mpool.estimateFee(4) && answerFound == 4);
            BOOST_CHECK(mpool.estimateSmartFee(8, &answerFound) == mpool.estimateFee(8) && answerFound == 8);
        }
    }

    std::vector<CAmount> origFeeEst;
    std::vector<double> origPriEst;
    // Highest feerate is 10*baseRate and gets in all blocks,
    // second highest feerate is 9*baseRate and gets in 9/10 blocks = 90%,
    // third highest feerate is 8*base rate, and gets in 8/10 blocks = 80%,
    // so estimateFee(1) should return 10*baseRate.
    // Second highest feerate has 100% chance of being included by 2 blocks,
    // so estimateFee(2) should return 9*baseRate etc...
    for (int i = 1; i < 10;i++) {
        origFeeEst.push_back(mpool.estimateFee(i).GetFeePerK());
        origPriEst.push_back(mpool.estimatePriority(i));
        if (i > 1) { // Fee estimates should be monotonically decreasing
            BOOST_CHECK(origFeeEst[i-1] <= origFeeEst[i-2]);
            BOOST_CHECK(origPriEst[i-1] <= origPriEst[i-2]);
        }
        int mult = 11-i;
        BOOST_CHECK(origFeeEst[i-1] < mult*baseRate.GetFeePerK() + deltaFee);
        BOOST_CHECK(origFeeEst[i-1] > mult*baseRate.GetFeePerK() - deltaFee);
        //BOOST_CHECK(origPriEst[i-1] < pow(10,mult) * basepri + deltaPri);
        BOOST_CHECK(origPriEst[i-1] > pow(10,mult) * basepri - deltaPri);
    }

    // Mine 50 more blocks with no transactions happening, estimates shouldn't change
    // We haven't decayed the moving average enough so we still have enough data points in every bucket
    while (blocknum < 250)
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);

    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] + deltaFee);
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] + deltaPri);
        BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
    }

    // Mine 15 more blocks with lots of transactions happening and not getting mined
    // Estimates should go up
    while (blocknum < 265) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k;
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                txHashes[j].push_back(hash);
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
    }

    int answerFound;
    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i) == CFeeRate(0) || mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimateSmartFee(i, &answerFound).GetFeePerK() > origFeeEst[answerFound-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) == -1 || mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
        BOOST_CHECK(mpool.estimateSmartPriority(i, &answerFound) > origPriEst[answerFound-1] - deltaPri);
    }

    // Mine all those transactions
    // Estimates should still not be below original
    for (int j = 0; j < 10; j++) {
        while(txHashes[j].size()) {
            CTransaction btx;
            if (mpool.lookup(txHashes[j].back(), btx))
                block.push_back(btx);
            txHashes[j].pop_back();
        }
    }
    mpool.removeForBlock(block, 265, dummyConflicted);
    block.clear();
    for (int i = 1; i < 10;i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() > origFeeEst[i-1] - deltaFee);
        BOOST_CHECK(mpool.estimatePriority(i) > origPriEst[i-1] - deltaPri);
    }

    // Mine 200 more blocks where everything is mined every block
    // Estimates should be below original estimates
    while (blocknum < 465) {
        for (int j = 0; j < 10; j++) { // For each fee/pri multiple
            for (int k = 0; k < 5; k++) { // add 4 fee txs for every priority tx
                tx.vin[0].prevout.n = 10000*blocknum+100*j+k;
                uint256 hash = tx.GetHash();
                mpool.addUnchecked(hash, entry.Fee(feeV[k/4][j]).Time(GetTime()).Priority(priV[k/4][j]).Height(blocknum).FromTx(tx, &mpool));
                CTransaction btx;
                if (mpool.lookup(hash, btx))
                    block.push_back(btx);
            }
        }
        mpool.removeForBlock(block, ++blocknum, dummyConflicted);
        block.clear();
    }
    for (int i = 1; i < 10; i++) {
        BOOST_CHECK(mpool.estimateFee(i).GetFeePerK() < origFeeEst[i-1] - deltaFee);
        /* This check is currently failing. Let's just comment it for now, as it is going
         * to be removed soon (https://github.com/PIVX-Project/PIVX/pull/1788)
         *
        BOOST_CHECK(mpool.estimatePriority(i) < origPriEst[i-1] - deltaPri);
         */
    }

    // Test that if the mempool is limited, estimateSmartFee won't return a value below the mempool min fee
    // and that estimateSmartPriority returns essentially an infinite value
    mpool.addUnchecked(tx.GetHash(),  entry.Fee(feeV[0][5]).Time(GetTime()).Priority(priV[1][5]).Height(blocknum).FromTx(tx, &mpool));
    // evict that transaction which should set a mempool min fee of minRelayTxFee + feeV[0][5]
    mpool.TrimToSize(1);
    BOOST_CHECK(mpool.GetMinFee(1).GetFeePerK() > feeV[0][5]);
    for (int i = 1; i < 10; i++) {
        BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.estimateFee(i).GetFeePerK());
        BOOST_CHECK(mpool.estimateSmartFee(i).GetFeePerK() >= mpool.GetMinFee(1).GetFeePerK());
        BOOST_CHECK(mpool.estimateSmartPriority(i) == INF_PRIORITY);
    }
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>