Esempio n. 1
0
        public bool GenerateTransaction(string sender, string receiver, IncentiveAssigned incentive, out string transactionID)
        {
            Transaction tx;

            transactionID = null;

            try
            {
                transactionID = Guid.NewGuid().ToString();
                lock (transactions)
                {
                    while (transactions.ContainsKey(transactionID))
                    {
                        transactionID = Guid.NewGuid().ToString();
                    }
                    tx = new Transaction(transactionID, sender, receiver, incentive);
                    transactions.Add(transactionID, tx);
                }

                return(true);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Esempio n. 2
0
        public override bool CheckUserBalance(string sender, IncentiveAssigned incentiveAssigned)
        {
            int balance;

            try
            {
                var respMultibal = this.MultichainClient.GetMultiBalancesAsync(sender, incentiveAssigned.IncentiveName);
                //respMultibal.Result.AssertOk();

                foreach (AssetBalanceResponse asset in respMultibal.Result.Result.Assets)
                {
                    if (asset.Name.Equals(incentiveAssigned.IncentiveName))
                    {
                        balance = (int)asset.Qty;

                        if (!this.Incentive.CheckSufficientCredits(balance, incentiveAssigned.IncentiveQty))
                        {
                            log.DebugFormat("Insufficient Funds. User Balance: [{0}] for Incentive:  [{1}]", asset.Qty, incentiveAssigned.IncentiveQty);
                            return(false);
                        }
                        return(true);
                    }
                }
                throw new Exception("Incentive not Found");
            }
            catch (Exception ex)
            {
                log.Error(ex.InnerException.Message);
                return(false);
            }
        }
Esempio n. 3
0
        public override bool RewardUser(string receiver, IncentiveAssigned incentiveAssigned, out object reward, out string transactionId)
        {
            Watch.Start();
            reward        = null;
            transactionId = null;
            bool hasFunds = false;

            try
            {
                //obtain the reward for completing the task
                incentiveAssigned = Incentive.CompleteTaskIncentive();

                //create the transaction and store it into the TransactionStorage
                if (!RegisterTransaction(this.ManagerAddress, receiver, incentiveAssigned, out transactionId, out hasFunds))
                {
                    return(false);
                }
                reward = new Dictionary <string, string>()
                {
                    { "quantity", incentiveAssigned.IncentiveQty.ToString() },
                    { "incentive", incentiveAssigned.IncentiveName }
                };
                Watch.Stop();
                Log.DebugFormat("Execution Time on IncentiveEngineNode Centralized: [{0}] milliseconds to Reward User", Watch.ElapsedMilliseconds);
                Watch.Reset();
                return(true);
            }
            catch (Exception ex)
            {
                log.ErrorFormat(ex.Message);
                return(false);
            }
        }
Esempio n. 4
0
 public Transaction(string ptxID, string pSender, string pReceiver, IncentiveAssigned pIncentive)
 {
     this.txID      = ptxID;
     this.sender    = pSender;
     this.receiver  = pReceiver;
     this.incentive = pIncentive;
     this.timestamp = Library.GetUnixTimestamp(DateTime.Now);
 }
Esempio n. 5
0
        private bool IssueMoreIncentives(IncentiveAssigned incentiveAssigned)
        {
            if (!this.TxNode.IssueMoreIncentives(ManagerAddress, incentiveAssigned))
            {
                return(false);
            }

            return(true);
        }
Esempio n. 6
0
        public void UserTesting()
        {
            IncentiveAssigned incentive = new IncentiveAssigned("BRONZE_BADGE", 2000);
            string            transactionId;
            string            userId = "1FwQkWSxzFMz8utyhZzwF2K5QqtZ59uQuGbAb8";
            bool hasfunds;

            //FIXME: remove
            this.Repository.RegisterUser(userId, this.Incentive);
            IssueMoreIncentives(incentive);
            RegisterTransaction(this.ManagerAddress, userId, incentive, out transactionId, out hasfunds);
        }
Esempio n. 7
0
 public bool IssueMoreIncentives(string managerAddress, IncentiveAssigned incentiveAssigned)
 {
     try
     {
         this.Wallets[managerAddress].Balance[incentiveAssigned.IncentiveName] += incentiveAssigned.IncentiveQty;
         return(true);
     }
     catch (Exception ex)
     {
         log.ErrorFormat(ex.Message);
         return(false);
     }
 }
Esempio n. 8
0
 private bool IssueMoreIncentives(IncentiveAssigned incentiveAsseigned)
 {
     try
     {
         log.DebugFormat("Going to issue more [{0}] from asset [{1}]", incentiveAsseigned.IncentiveQty, incentiveAsseigned.IncentiveName);
         var response = this.MultichainClient.IssueMoreAsync(ManagerAddress, incentiveAsseigned.IncentiveName, incentiveAsseigned.IncentiveQty);
         response.Result.AssertOk();
         return(true);
     }
     catch (Exception ex)
     {
         log.Error(ex.InnerException.Message);
         return(false);
     }
 }
Esempio n. 9
0
        public void ProcessTaskReports(CSTask task)
        {
            Dictionary <string, int> answersMap         = new Dictionary <string, int>();
            List <double>            listOfAnswersIndex = new List <double>();
            Dictionary <int, int>    answersIncentive   = null;
            List <InteractiveReport> listResports       = new List <InteractiveReport>();
            InteractiveReport        intReport          = null;
            IncentiveAssigned        incentive          = null;
            int    index      = 1;
            object taskReward = null;
            string txId       = null;

            //creates association between answer Index and answerId
            //this will allow to sort the answers to calculate the z-score modified
            foreach (TaskAnswer answer in task.InteractiveTask.Answers)
            {
                answersMap.Add(answer.AnswerId, index);
                index++;
            }

            foreach (string reportID in task.ReportsID.Values.ToList())
            {
                //get report from repository
                intReport = RepositoryRemote.GetInteractiveReportsByID(reportID);
                //add the first report result
                if (answersMap.ContainsKey(intReport.Result.AnswerId))
                {
                    listOfAnswersIndex.Add(answersMap[intReport.Result.AnswerId]);
                }
                listResports.Add(intReport);
            }
            if (listOfAnswersIndex.Count == 0)
            {
                Log.Debug("No Answers to Process");
                return;
            }
            //get for each answer its reward value
            answersIncentive = DataQualityProcess(listOfAnswersIndex);
            incentive        = this.IncentiveScheme.Incentive.CompleteTaskIncentive();
            foreach (InteractiveReport report in listResports)
            {
                index = answersMap[report.Result.AnswerId];
                incentive.IncentiveQty = answersIncentive[index];

                this.IncentiveScheme.RewardUser(report.UserID, incentive, out taskReward, out txId);
                this.RepositoryRemote.SaveReportReward(task.TaskID, report.ReportID, (Dictionary <string, string>)taskReward, txId);
            }
        }
Esempio n. 10
0
        public override bool RewardUser(string receiver, IncentiveAssigned incentiveAssigned, out object reward, out string transactionId)
        {
            Watch.Start();
            List <string> userNodes;

            reward        = null;
            transactionId = null;
            bool hasFunds;

            try
            {
                userNodes = this.Repository.GetUserMultichainNodes(receiver);

                if (userNodes != null)
                {
                    //increase the incentive based on the number of nodes contributing to the blockchain
                    if (userNodes.Count != 0)
                    {
                        incentiveAssigned.IncentiveQty *= userNodes.Count;
                    }
                }
                else
                {
                    return(false);
                }
                //transfer the incentive to the user
                if (!RegisterTransaction(ManagerAddress, receiver, incentiveAssigned, out transactionId, out hasFunds))
                {
                    return(false);
                }
                reward = new Dictionary <string, string>()
                {
                    { "quantity", incentiveAssigned.IncentiveQty.ToString() },
                    { "incentive", incentiveAssigned.IncentiveName }
                };
                Watch.Stop();
                Log.DebugFormat("Execution Time on IncentiveEngineNode Decentralized: [{0}] milliseconds to Reward User", Watch.ElapsedMilliseconds);
                Watch.Reset();
                return(true);
            }
            catch (Exception)
            {
                throw;
            }
        }
Esempio n. 11
0
        public bool CreateTransaction(string sender, string receiver, IncentiveAssigned incentiveAssgined, out string transactionID)
        {
            watch.Start();
            Wallet senderWallet;
            Wallet receiverWallet;

            transactionID = null;

            try
            {
                if (!GetUserWallet(sender, out senderWallet))
                {
                    log.DebugFormat("Invalid UserId: [{0}]", sender);
                    return(false);
                }
                if (!GetUserWallet(receiver, out receiverWallet))
                {
                    log.DebugFormat("Invalid UserId: [{0}]", receiver);
                    return(false);
                }
                //calc sender balance
                senderWallet.Balance[incentiveAssgined.IncentiveName] -= incentiveAssgined.IncentiveQty;
                //calc receiver balance
                receiverWallet.Balance[incentiveAssgined.IncentiveName] += incentiveAssgined.IncentiveQty;
                //generate transaction
                if (!TxStorage.GenerateTransaction(sender, receiver, incentiveAssgined, out transactionID))
                {
                    Log.Error("ERROR. Cannot Generate Transaction!");
                    return(false);
                }
                senderWallet.AssociateTransaction(transactionID);
                receiverWallet.AssociateTransaction(transactionID);
                watch.Stop();
                Log.DebugFormat("Execution Time: [{0}] in milliseconds to register transaction", watch.ElapsedMilliseconds);
                watch.Reset();
                return(true);
            }
            catch (Exception ex)
            {
                Log.ErrorFormat(ex.Message);
                return(false);
            }
        }
Esempio n. 12
0
        public bool CalcTaskCost(CSTaskDTO taskSpec, string userID, out IncentiveAssigned incentiveAssigned)
        {
            incentiveAssigned = null;

            try
            {
                Console.WriteLine("[INFO - INCENTIVE ENGINE] - Calc Task Cost for User: "******"[INFO - INCENTIVE ENGINE] - Incentive Value: " + incentiveAssigned.IncentiveQty
                                  + " " + incentiveAssigned.IncentiveName);
                return(true);
            }
            catch (Exception ex)
            {
                Log.Error(ex.Message);
                return(false);
            }
        }
Esempio n. 13
0
        public override bool CheckUserBalance(string userId, IncentiveAssigned incentiveAssigned)
        {
            Dictionary <string, int> incentivesBalance;
            int balance;


            Log.DebugFormat("Going to check the balance for UserId: [{0}]", userId);
            Watch.Stop();
            incentivesBalance = GetUserBalance(userId);
            Watch.Start();
            balance = incentivesBalance[incentiveAssigned.IncentiveName];

            Log.DebugFormat("Balance: [{0}] for Incentive: [{1}]", balance, incentiveAssigned.IncentiveName);
            if (!Incentive.CheckSufficientCredits(balance, incentiveAssigned.IncentiveQty))
            {
                log.Debug("Insufficient Funds.");
                return(false);
            }
            return(true);
        }
Esempio n. 14
0
        /// <summary>
        /// Calculate the cost for a crowd-sensing task.
        /// </summary>
        /// <param name="response"></param>
        /// <returns></returns>
        public bool CalcCostCSTask(out APIResponseDTO response)
        {
            IncentiveAssigned       incentiveValue = null;
            CalcTaskCostRequestDTO  csTask;
            CalcTaskCostResponseDTO calcCostDTO = new CalcTaskCostResponseDTO();

            response = new APIResponseDTO();

            try
            {
                if (!GetCSTaskToPay(out csTask))
                {
                    response.SetErrorResponse("Invalid Request please try again!", APIResponseDTO.RESULT_TYPE.ERROR);
                    return(false);
                }
                Global.Log.DebugFormat("Client ID: {0}", csTask.UserID);

                if (!serverMgr.RemoteIncentiveEngine.CalcTaskCost(csTask.Task, csTask.UserID, out incentiveValue) ||
                    incentiveValue == null)
                {
                    response.SetErrorResponse("Cannot calculate the task cost. Please try again!", APIResponseDTO.RESULT_TYPE.ERROR);
                    return(false);
                }
                calcCostDTO.IncentiveToPay = incentiveValue;
                response.SetResponse(calcCostDTO, APIResponseDTO.RESULT_TYPE.SUCCESS);
                Global.Log.DebugFormat("User ID: [{0}] has to Pay [{1}]", csTask.UserID, incentiveValue.ToString());
                return(true);
            }
            catch (Exception ex)
            {
                Global.Log.Error(ex.Message);
                response.SetResponse(new Dictionary <string, string>()
                {
                    { "errorMessage", "Cannot calculate the task cost. Please try again!" }
                }
                                     , APIResponseDTO.RESULT_TYPE.ERROR);
                return(false);
            }
        }
Esempio n. 15
0
        public override bool RegisterTransaction(string sender, string recipient, IncentiveAssigned incentiveAssigned, out string transactionId, out bool hasFunds)
        {
            transactionId = null;

            hasFunds = false;

            try
            {
                //check if the user can make the transaction
                if (!CheckUserBalance(sender, incentiveAssigned))
                {
                    //check if the Manager has  the necessary incentives to distribute among the users
                    if (sender.Equals(this.ManagerAddress))
                    {
                        log.Debug("Manager does not have the necessary incentive quantity. Going to issue more incentives!");
                        IssueMoreIncentives(incentiveAssigned);
                    }
                    else
                    {
                        hasFunds = false;
                        return(true);
                    }
                }
                hasFunds = true;
                log.DebugFormat("Going to transfer [{0}] from incentive [{1}]", incentiveAssigned.IncentiveQty, incentiveAssigned.IncentiveName);
                var response = this.MultichainClient.SendAssetFromAsync(sender, recipient, incentiveAssigned.IncentiveName, incentiveAssigned.IncentiveQty);
                response.Result.AssertOk();
                transactionId = response.Result.Result;
                log.DebugFormat("Transaction Id: [{0}]", transactionId);
                return(true);
            }
            catch (Exception ex)
            {
                log.Error(ex.InnerException.Message);
                return(false);
            }
        }
Esempio n. 16
0
        public override bool RegisterTransaction(string sender, string receiver, IncentiveAssigned incentiveAssigned, out string transactionId, out bool hasFunds)
        {
            transactionId = null;
            hasFunds      = false;

            //check if the user can make the transaction
            if (!CheckUserBalance(sender, incentiveAssigned))
            {
                //check if the Manager has  the necessary incentives to distribute among the users
                if (sender.Equals(this.ManagerAddress))
                {
                    log.Debug("Manager does not have the necessary incentive quantity. Going to issue more incentives!");
                    IssueMoreIncentives(incentiveAssigned);
                }
                else
                {
                    hasFunds = false;
                    return(true);
                }
            }
            hasFunds = true;
            log.DebugFormat("Going to create transaction for transfer [{0}] of incentive [{1}] from [{2}] to [{3}]", incentiveAssigned.IncentiveQty
                            , incentiveAssigned.IncentiveName
                            , sender
                            , receiver);
            Watch.Stop();
            //in the centralized version the transactions are stored in the TransactionNode
            //create the transaction
            if (!this.TxNode.CreateTransaction(sender, receiver, incentiveAssigned, out transactionId))
            {
                Log.Error("Cannot Create transaction!");
                return(false);
            }
            Log.DebugFormat("Transaction Create with Sucess!. ID: [{0}]", transactionId);
            return(true);
        }
Esempio n. 17
0
 public abstract bool CheckUserBalance(string userId, IncentiveAssigned incentiveAssigned);
Esempio n. 18
0
 public abstract bool RegisterTransaction(string sender, string recipient, IncentiveAssigned incentiveAssigned, out string transactionId, out bool hasFunds);
Esempio n. 19
0
 public abstract bool RewardUser(string receiver, IncentiveAssigned incentiveAssigned, out object reward, out string transactionId);
Esempio n. 20
0
        private Dictionary <int, int> DataQualityProcess(List <double> answersSortByIndex)
        {
            List <double>         medDevValues   = new List <double>();
            List <double>         modZscoreVals  = new List <double>();
            List <double>         answersWeight  = new List <double>();
            Dictionary <int, int> rewardByAnswer = new Dictionary <int, int>();
            IncentiveAssigned     incentive      = null;
            double medianVal      = 0;
            double finalMedianDev = 0;
            double auxZscoreVal   = 0;
            double maxAbsValue    = 0;
            double rewardvalue    = 0;


            //calculate the median value
            medianVal = Library.GetMedian(answersSortByIndex);
            medDevValues.Add(Math.Abs(1 - medianVal));
            medDevValues.Add(Math.Abs(2 - medianVal));
            medDevValues.Add(Math.Abs(3 - medianVal));
            medDevValues.Add(Math.Abs(4 - medianVal));
            //calculate median deviation final
            finalMedianDev = Library.GetMedian(medDevValues);

            //answer1
            auxZscoreVal = 0.6745 * (1 - medianVal) / finalMedianDev;
            modZscoreVals.Add(auxZscoreVal);
            //answer2
            auxZscoreVal = 0.6745 * (2 - medianVal) / finalMedianDev;
            modZscoreVals.Add(auxZscoreVal);
            //answer3
            auxZscoreVal = 0.6745 * (3 - medianVal) / finalMedianDev;
            modZscoreVals.Add(auxZscoreVal);
            //answer4
            auxZscoreVal = 0.6745 * (4 - medianVal) / finalMedianDev;
            modZscoreVals.Add(auxZscoreVal);

            //getMaxvalue
            maxAbsValue = Math.Abs(modZscoreVals.Max());

            //get answer1 weight, reuse zscoreval variable
            auxZscoreVal = Math.Abs(modZscoreVals[0] / maxAbsValue);
            answersWeight.Add(auxZscoreVal);
            //get answer2 weight, reuse zscoreval variable
            auxZscoreVal = Math.Abs(modZscoreVals[1] / maxAbsValue);
            answersWeight.Add(auxZscoreVal);
            //get answer3 weight, reuse zscoreval variable
            auxZscoreVal = Math.Abs(modZscoreVals[2] / maxAbsValue);
            answersWeight.Add(auxZscoreVal);
            //get answer4 weight, reuse zscoreval variable
            auxZscoreVal = Math.Abs(modZscoreVals[3] / maxAbsValue);
            answersWeight.Add(auxZscoreVal);

            //get the incentive for completing tasks
            incentive = this.IncentiveScheme.Incentive.CompleteTaskIncentive();
            //reward for the 1 answer
            rewardvalue = incentive.IncentiveQty - (incentive.IncentiveQty / 2 * answersWeight[0]);
            rewardvalue = Math.Round(rewardvalue, 0);
            rewardByAnswer.Add(1, (int)rewardvalue);
            //reward for the 2 answer
            rewardvalue = incentive.IncentiveQty - (incentive.IncentiveQty / 2 * answersWeight[1]);
            rewardvalue = Math.Round(rewardvalue, 0);
            rewardByAnswer.Add(2, (int)rewardvalue);
            //reward for the 3 answer
            rewardvalue = incentive.IncentiveQty - (incentive.IncentiveQty / 2 * answersWeight[2]);
            rewardvalue = Math.Round(rewardvalue, 0);
            rewardByAnswer.Add(3, (int)rewardvalue);
            //reward for the 4 answer
            rewardvalue = incentive.IncentiveQty - (incentive.IncentiveQty / 2 * answersWeight[3]);
            rewardvalue = Math.Round(rewardvalue, 0);
            rewardByAnswer.Add(4, (int)rewardvalue);

            return(rewardByAnswer);
        }