/*****************************************************************************
 *
 * Copyright (c) 2018-19, Josef Treus
 * Westfälische Wilhelms-Universität Münster, AG Embedded Systems
 * All rights reserved.
 *
 * This file is part of SysCSec
 *
 * SysCSec is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your
 * option) any later version.
 *
 * SysCSec is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with SysCSec.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 *  Please report any problems or bugs to: sysc.sec@uni-muenster.de
 *
 ****************************************************************************/

#ifndef CCA_ATTACKER_CPP
#define CCA_ATTACKER_CPP

#include "rsa.cpp"
#include "systemc.h"
#include "Utils.cpp"
#include "RessourceHandler.cpp"
#include "math.h"
#include <map>


/* The attacker performs a CCA attack on a subject that uses RSA encryption
 * Param: sc_module_name name : name of the attacker
 *        int msgCount : number of messages that should be used in each step
*/
SC_MODULE(CCA_Attacker)
{ 
    sc_fifo_in<bigint> in;
    sc_fifo_out<bigint> out;
    sc_in<bool> cipherProceeded_in; 

    bigint publicKeySubjectE;
    bigint publicKeySubjectN;
    
    int msgCount;

    /* Is executed as soon as the module receives the public key from the subject.
     * Subsequently, a CCA attack is started.
     * Param: -
     * Return: -
     */
    void cca(){
        wait(in->data_written_event());
        // read Public key 
        this->publicKeySubjectE = in->read();
        this->publicKeySubjectN = in->read();

        //Generate msgCount power traces
        int bitsThatAreZero = Utils::unsignificantBitCount(publicKeySubjectN.to_int(),NBITS);
        int keyLength = NBITS-bitsThatAreZero; 
        char randVal[NBITS-bitsThatAreZero-1];
        
        // send msgCount number of messages to the subject
       
        for(int k = 0; k < msgCount; k++){
             rand_bitstr(randVal,keyLength-1); 
        bigint randValAsBigint =  randVal;
           
            out->write(randValAsBigint);
            wait();
        }
        
        
        // size (n) and number (m) of vectors
        int n = RessourceHandler::getInstance()->powerTraces.size();
       
        /**
        for(int l = 0; l < n; l++){
            m = (m < RessourceHandler::getInstance()->powerTraces[l].rbegin()->first)? RessourceHandler::getInstance()->powerTraces[l].rbegin()->first: m;

        }  
        m *= 2;
        **/
        // compute vectors
        int cols[n][keyLength*2] = {0};
         map<int, map<int,int>> peaks;
        for(int i = 0; i < n; i++){
            peaks = RessourceHandler::getInstance()->getPeaksOfTrace(true, 3, 30, 10, RessourceHandler::getInstance()->powerTraces[i]);
            if(peaks.size() != keyLength*2){
                cout << "peaks.size() " << peaks.size() << endl;
                cout << "Error" << endl;
                cout << "keyLength " << keyLength << endl;
            }
            for(int j = 0; j < keyLength*2; j++){
                cols[i][j] = 0;
                for(int k = 0; k < peaks[j].size(); k++){
                    cols[i][j] += peaks[j][k];
                }
            }
            
        }
        //compute Matrix C 
        map<int,map<int,int>> C;
        int u[n];
        int v[n];
        for(int i = 0; i< keyLength*2; i++){
           
            for(int j = 0; j< keyLength*2; j++){
                for(int k = 0; k < n; k++){
                    u[k] = cols[k][i];
                    v[k] = cols[k][j];
                }
                //calculate Pearson Correlation Coefficient 
                 C[i][j] = pearsonCoeff(u,v,n)*1000;
                 cout << C[i][j] << " ";
            }
            cout << endl;
        }
        int temp = 0;
        cout << "Total of each col: ";
        for(int i = 0; i< keyLength*2; i++){
           temp = 0;
            for(int j = 0; j< keyLength*2; j++){
                temp += C[i][j];
            }
            cout << temp << " ";
        }
        RessourceHandler::getInstance()->corrStrength = C;
        sc_stop();
    }

     /* Calculate Pearson Coefficient from two vectors
     * Param: int x, int y : vectors / test data
     *        int n : length of both vectors
     * Return: long double : Pearson Coefficient
     */
    
     long double pearsonCoeff(int* x,int* y, int n){
        double xMean = Utils::mean(x,n);
        double yMean = Utils::mean(y,n);
        double xStdDev = Utils::standardDeviation(x,n);
        double yStdDev = Utils::standardDeviation(y,n);
     
        //calculate covariance
        long double cov = 0;
        for(int i = 0; i < n; i++){
            cov += (x[i] - xMean)*(y[i] - yMean);
        }
        cov /= n;
        long double denominator = xStdDev*yStdDev;
        if(denominator != (double)0){
            return cov/denominator;
        }else{
            return 0;
        }
        
     }

    SC_HAS_PROCESS(CCA_Attacker);
	CCA_Attacker(sc_module_name name, int msgCount): sc_module(name), cipherProceeded_in("cPi"), in("in"), out("out"){
        this->msgCount = msgCount;
        SC_THREAD(cca); 
        sensitive << cipherProceeded_in.pos() << cipherProceeded_in.neg();
    }
};
#endif
