Exemplo n.º 1
0
double Security::yearlyRate() {
    QMap<QDate, double>::const_iterator it_begin = quotations.begin();
    QMap<QDate, double>::const_iterator it_end = quotations.end();
    if(it_end == it_begin) return 0.0;
    it_end--;
    QDate date1 = it_begin.key(), date2 = QDate::currentDate();
    double q1 = it_begin.value(), q2 = it_end.value();
    int days = date1.daysTo(date2);
    if(it_end.key() != date2 && q1 != q2) {
        int days2 = it_end.key().daysTo(date2);
        q2 *= pow(q2 / q1, days2 / (days - days2));
    }
    Income *trans = dividends.first();
    while(trans) {
        double s = shares(trans->date());
        if(s > 0.0) q2 += trans->income() / s;
        trans = dividends.next();
    }
    double shares_change = 0.0;
    ReinvestedDividend *rediv = reinvestedDividends.first();
    while(rediv) {
        double s = shares(rediv->date);
        if(s > 0.0) shares_change += rediv->shares / (s - rediv->shares);
        rediv = reinvestedDividends.next();
    }
    if(date1 == date2) return 0.0;
    double change = q2 / q1 + shares_change;
    return pow(change, 1 / yearsBetweenDates(date1, date2)) - 1;
}
Exemplo n.º 2
0
double Security::yearlyRate(const QDate &date1, const QDate &date2) {
    if(date1 > date2) return yearlyRate(date2, date1);
    if(date1 == date2) return 0.0;
    QMap<QDate, double>::const_iterator it_begin = quotations.begin();
    if(it_begin == quotations.end()) return 0.0;
    QDate curdate = QDate::currentDate();
    if(date1 >= curdate) {
        return pow(1 + (profit(date1, date2, true, true) / value(date1, true, true)), 1 / (yearsBetweenDates(date1, date2))) - 1;
    }
    if(date2 > curdate) {
        double rate1 = yearlyRate(date1, curdate);
        double rate2 = yearlyRate(curdate, date2);
        int days1 = date1.daysTo(curdate);
        int days2 = curdate.daysTo(date2);
        return ((rate1 * days1) + (rate2 * days2)) / (days1 + days2);
    }
    if(date2 < it_begin.key()) {
        return 0.0;
    }
    if(date1 < it_begin.key()) {
        return yearlyRate(it_begin.key(), date2);
    }
    QDate date1_q, date2_q;
    double q1 = getQuotation(date1, &date1_q);
    double q2 = getQuotation(date2, &date2_q);
    int days = date1.daysTo(date2);
    if(q1 != q2) {
        double q1_bak = q1;
        if(date1 != date1_q) {
            double rate = q1 / q2;
            int days1 = date1_q.daysTo(date1);
            q1 *= pow(rate, days1 / (days - days1));
        }
        if(date2 != date2_q) {
            double rate = q2 / q1_bak;
            int days2 = date2_q.daysTo(date2);
            q2 *= pow(rate, days2 / (days - days2));
        }
    }
    Income *trans = dividends.first();
    while(trans && trans->date() <= date2) {
        if(trans->date() >= date1) {
            double s = shares(trans->date());
            if(s > 0.0) q2 += trans->income() / s;
        }
        trans = dividends.next();
    }
    double shares_change = 0.0;
    ReinvestedDividend *rediv = reinvestedDividends.first();
    while(rediv && rediv->date <= date2) {
        if(rediv->date >= date1) {
            double s = shares(rediv->date);
            if(s > 0.0) shares_change += rediv->shares / (s - rediv->shares);
        }
        rediv = reinvestedDividends.next();
    }
    double change = q2 / q1 + shares_change;
    return pow(change, 1 / yearsBetweenDates(date1, date2)) - 1;
}
Exemplo n.º 3
0
Arquivo: tss.cpp Projeto: louiz/botan
std::vector<RTSS_Share>
RTSS_Share::split(byte M, byte N,
                  const byte S[], u16bit S_len,
                  const byte identifier[16],
                  RandomNumberGenerator& rng)
   {
   if(M == 0 || N == 0 || M > N)
      throw Encoding_Error("RTSS_Share::split: M == 0 or N == 0 or M > N");

   SHA_256 hash; // always use SHA-256 when generating shares

   std::vector<RTSS_Share> shares(N);

   // Create RTSS header in each share
   for(byte i = 0; i != N; ++i)
      {
      shares[i].m_contents += std::make_pair(identifier, 16);
      shares[i].m_contents += rtss_hash_id(hash.name());
      shares[i].m_contents += M;
      shares[i].m_contents += get_byte(0, S_len);
      shares[i].m_contents += get_byte(1, S_len);
      }

   // Choose sequential values for X starting from 1
   for(byte i = 0; i != N; ++i)
      shares[i].m_contents.push_back(i+1);

   // secret = S || H(S)
   secure_vector<byte> secret(S, S + S_len);
   secret += hash.process(S, S_len);

   for(size_t i = 0; i != secret.size(); ++i)
      {
      std::vector<byte> coefficients(M-1);
      rng.randomize(coefficients.data(), coefficients.size());

      for(byte j = 0; j != N; ++j)
         {
         const byte X = j + 1;

         byte sum = secret[i];
         byte X_i = X;

         for(size_t k = 0; k != coefficients.size(); ++k)
            {
            sum ^= gfp_mul(X_i, coefficients[k]);
            X_i  = gfp_mul(X_i, X);
            }

         shares[j].m_contents.push_back(sum);
         }
      }

   return shares;
   }
vm_placement_problem_result<TraitsT> make_vm_placement_problem_result(ProblemDescrT problem_descr, ProblemResultT problem_res)
{
	typedef TraitsT traits_type;
	typedef vm_placement_problem_result<traits_type> result_type;
	typedef typename result_type::real_type real_type;
	typedef typename result_type::resource_share_container resource_share_container;
	typedef typename result_type::physical_machine_identifier_type physical_machine_identifier_type;
	typedef typename result_type::virtual_machine_identifier_type virtual_machine_identifier_type;

	result_type res;

	res.cost(problem_res.cost());

	typename ProblemResultT::smallint_matrix_type placement_flags(problem_res.virtual_machine_placement());
	typename ProblemResultT::real_matrix_type placement_shares(problem_res.virtual_machine_shares());

	::std::size_t npm(::boost::numeric::ublasx::num_rows(placement_flags));
	::std::size_t nvm(::boost::numeric::ublasx::num_columns(placement_flags));

	for (::std::size_t i = 0; i < npm; ++i)
	{
		physical_machine_identifier_type pm_id(problem_descr.pm_ids[i]);

		real_type share_sum(0); // Normalization factor
		for (::std::size_t k = 0; k < 2; ++k)
		{
			for (::std::size_t j = 0; j < nvm; ++j)
			{
				if (placement_flags(i,j))
				{
					if (k == 0)
					{
						share_sum += placement_shares(i,j);
					}
					else
					{
						virtual_machine_identifier_type vm_id(problem_descr.vm_ids[j]);
						real_type share(placement_shares(i,j));
						if (share_sum > 1)
						{
							share /= share_sum;
						}
						//FIXME: CPU resource category is hard-coded.
						resource_share_container shares(1, ::std::make_pair(cpu_resource_category, share));
						res.placement()[::std::make_pair(pm_id, vm_id)] = shares;
					}
				}
			}
		}
	}

	return res;
}
void CGUIDialogAudioSubtitleSettings::OnSettingAction(const CSetting *setting)
{
  if (setting == NULL)
    return;

  CGUIDialogSettingsManualBase::OnSettingAction(setting);
  
  const std::string &settingId = setting->GetId();
  if (settingId == SETTING_AUDIO_DSP)
  {
    g_windowManager.ActivateWindow(WINDOW_DIALOG_AUDIO_DSP_OSD_SETTINGS);
  }
  else if (settingId == SETTING_SUBTITLE_BROWSER)
  {
    std::string strPath;
    if (URIUtils::IsInRAR(g_application.CurrentFileItem().GetPath()) || URIUtils::IsInZIP(g_application.CurrentFileItem().GetPath()))
      strPath = CURL(g_application.CurrentFileItem().GetPath()).GetHostName();
    else
      strPath = g_application.CurrentFileItem().GetPath();

    std::string strMask = ".utf|.utf8|.utf-8|.sub|.srt|.smi|.rt|.txt|.ssa|.aqt|.jss|.ass|.idx|.rar|.zip";
    if (g_application.GetCurrentPlayer() == "VideoPlayer")
      strMask = ".srt|.rar|.zip|.ifo|.smi|.sub|.idx|.ass|.ssa|.txt";
    VECSOURCES shares(*CMediaSourceSettings::GetInstance().GetSources("video"));
    if (CMediaSettings::GetInstance().GetAdditionalSubtitleDirectoryChecked() != -1 && !CServiceBroker::GetSettings().GetString(CSettings::SETTING_SUBTITLES_CUSTOMPATH).empty())
    {
      CMediaSource share;
      std::vector<std::string> paths;
      paths.push_back(URIUtils::GetDirectory(strPath));
      paths.push_back(CServiceBroker::GetSettings().GetString(CSettings::SETTING_SUBTITLES_CUSTOMPATH));
      share.FromNameAndPaths("video",g_localizeStrings.Get(21367),paths);
      shares.push_back(share);
      strPath = share.strPath;
      URIUtils::AddSlashAtEnd(strPath);
    }
    if (CGUIDialogFileBrowser::ShowAndGetFile(shares, strMask, g_localizeStrings.Get(293), strPath, false, true)) // "subtitles"
    {
      if (URIUtils::HasExtension(strPath, ".sub"))
      {
        if (XFILE::CFile::Exists(URIUtils::ReplaceExtension(strPath, ".idx")))
          strPath = URIUtils::ReplaceExtension(strPath, ".idx");
      }
      
      g_application.m_pPlayer->AddSubtitle(strPath);
      Close();
    }
  }
  else if (settingId == SETTING_AUDIO_MAKE_DEFAULT)
    Save();
}
Exemplo n.º 6
0
double Security::yearlyRate(const QDate &date) {
    QMap<QDate, double>::const_iterator it_begin = quotations.begin();
    if(it_begin == quotations.end()) return 0.0;
    QDate date1 = it_begin.key();
    QDate date2 = date;
    if(date1 >= date2) return 0.0;
    QDate curdate = QDate::currentDate();
    if(date2 > curdate) {
        double rate1 = yearlyRate();
        double rate2 = yearlyRate(curdate, date2);
        int days1 = date1.daysTo(curdate);
        int days2 = curdate.daysTo(date2);
        return ((rate1 * days1) + (rate2 * days2)) / (days1 + days2);
    }
    QDate date2_q;
    double q1 = it_begin.value(), q2 = getQuotation(date2, &date2_q);
    int days = date1.daysTo(date2);
    if(date2 != date2_q && q1 != q2) {
        int days2 = date2_q.daysTo(date2);
        q2 *= pow(q2 / q1, days2 / (days - days2));
    }
    Income *trans = dividends.first();
    while(trans && trans->date() <= date2) {
        double s = shares(trans->date());
        if(s > 0.0) q2 += trans->income() / s;
        trans = dividends.next();
    }
    double shares_change = 0.0;
    ReinvestedDividend *rediv = reinvestedDividends.first();
    while(rediv && rediv->date <= date2) {
        double s = shares(rediv->date);
        if(s > 0.0) shares_change += rediv->shares / (s - rediv->shares);
        rediv = reinvestedDividends.next();
    }
    double change = q2 / q1 + shares_change;
    return pow(change, 1 / yearsBetweenDates(date1, date2)) - 1;
}
Exemplo n.º 7
0
std::string CGUIDialogSubtitleSettings::BrowseForSubtitle()
{
  std::string extras;
  for (const auto& vfsAddon : CServiceBroker::GetVFSAddonCache().GetAddonInstances())
  {
    if (vfsAddon->ID() == "vfs.rar" || vfsAddon->ID() == "vfs.libarchive")
      extras += '|' + vfsAddon->GetExtensions();
  }

  std::string strPath;
  if (URIUtils::IsInRAR(g_application.CurrentFileItem().GetPath()) || URIUtils::IsInZIP(g_application.CurrentFileItem().GetPath()))
    strPath = CURL(g_application.CurrentFileItem().GetPath()).GetHostName();
  else
    strPath = g_application.CurrentFileItem().GetPath();

  std::string strMask = ".utf|.utf8|.utf-8|.sub|.srt|.smi|.rt|.txt|.ssa|.aqt|.jss|.ass|.idx|.zip";

  if (g_application.GetCurrentPlayer() == "VideoPlayer")
    strMask = ".srt|.zip|.ifo|.smi|.sub|.idx|.ass|.ssa|.txt";

  strMask += extras;

  VECSOURCES shares(*CMediaSourceSettings::GetInstance().GetSources("video"));
  if (CMediaSettings::GetInstance().GetAdditionalSubtitleDirectoryChecked() != -1 && !CServiceBroker::GetSettingsComponent()->GetSettings()->GetString(CSettings::SETTING_SUBTITLES_CUSTOMPATH).empty())
  {
    CMediaSource share;
    std::vector<std::string> paths;
    paths.push_back(URIUtils::GetDirectory(strPath));
    paths.push_back(CServiceBroker::GetSettingsComponent()->GetSettings()->GetString(CSettings::SETTING_SUBTITLES_CUSTOMPATH));
    share.FromNameAndPaths("video",g_localizeStrings.Get(21367),paths);
    shares.push_back(share);
    strPath = share.strPath;
    URIUtils::AddSlashAtEnd(strPath);
  }

  if (CGUIDialogFileBrowser::ShowAndGetFile(shares, strMask, g_localizeStrings.Get(293), strPath, false, true)) // "subtitles"
  {
    if (URIUtils::HasExtension(strPath, ".sub"))
    {
      if (XFILE::CFile::Exists(URIUtils::ReplaceExtension(strPath, ".idx")))
        strPath = URIUtils::ReplaceExtension(strPath, ".idx");
    }

    return strPath;
  }

  return "";
}
Exemplo n.º 8
0
void calculateLocalShares()
{
	QuickDC::Preferences config("~/.quickdc/quickdc.conf");
	QuickDC::Hash::Manager hash;
	QuickDC::Share::Manager shares(&config, &hash);
	
	shares.initialize();
	QDBG("calculateLocalShares()");
	
	while (hash.isBusy())
	{
		hash.process();
	}
	
	shares.createFileLists(false);
	
	printf("Shared: %s bytes, %d files\n", quickdc_ulltoa(shares.getSharedSize()), shares.getFiles());
}
    virtual_machines_placement<traits_type> do_placement(data_center_type const& dc)
    {
        DCS_DEBUG_TRACE("BEGIN Initial Placement");//XXX
        ::std::cerr << "[optimal_initial_placement] BEGIN Initial Placement" << ::std::endl;//XXX
        typedef typename traits_type::physical_machine_identifier_type physical_machine_identifier_type;
        typedef typename traits_type::virtual_machine_identifier_type virtual_machine_identifier_type;
        typedef ::std::map<virtual_machine_identifier_type,real_type> virtual_machine_utilization_map;
        typedef typename optimal_solver_type::physical_virtual_machine_map physical_virtual_machine_map;
        typedef typename physical_virtual_machine_map::const_iterator physical_virtual_machine_iterator;
        typedef typename optimal_solver_type::resource_share_container resource_share_container;
        typedef typename data_center_type::physical_machine_type physical_machine_type;
        typedef typename data_center_type::physical_machine_pointer physical_machine_pointer;
        typedef typename data_center_type::virtual_machine_type virtual_machine_type;
        typedef typename data_center_type::virtual_machine_pointer virtual_machine_pointer;
        typedef typename data_center_type::application_type application_type;
        typedef typename application_type::reference_physical_resource_type ref_resource_type;
        typedef typename application_type::reference_physical_resource_container ref_resource_container;
        typedef typename ref_resource_container::const_iterator ref_resource_iterator;


        virtual_machine_utilization_map vm_util_map;

        // Retrieve application performance info
        {
            typedef ::std::vector<virtual_machine_pointer> virtual_machine_container;
            typedef typename virtual_machine_container::const_iterator virtual_machine_iterator;

            virtual_machine_container vms(dc.active_virtual_machines());
            virtual_machine_iterator vm_end_it(vms.end());
            for (virtual_machine_iterator vm_it = vms.begin(); vm_it != vm_end_it; ++vm_it)
            {
                virtual_machine_pointer ptr_vm(*vm_it);

                // paranoid-check: null
                DCS_DEBUG_ASSERT( ptr_vm );

                ref_resource_container rress(ptr_vm->guest_system().application().reference_resources());
                ref_resource_iterator rress_end_it(rress.end());
                for (ref_resource_iterator rress_it = rress.begin(); rress_it != rress_end_it; ++rress_it)
                {
                    ref_resource_type res(*rress_it);

                    //TODO: CPU resource category not yet handle in app simulation model and optimization problem
                    DCS_ASSERT(
                        res.category() == cpu_resource_category,
                        DCS_EXCEPTION_THROW(
                            ::std::runtime_error,
                            "Resource categories other than CPU are not yet implemented."
                        )
                    );

                    vm_util_map[ptr_vm->id()] = ptr_vm->guest_system().application().performance_model().tier_measure(
                                                    ptr_vm->guest_system().id(),
                                                    ::dcs::des::cloud::utilization_performance_measure
                                                );
                    ::std::cerr << "[optimal_initial_placement] VM: " << *ptr_vm << " - U: " << vm_util_map.at(ptr_vm->id()) << ::std::endl;//XXX
                }
            }
        }

        // Solve the optimization problem

        //optimal_solver_type solver;

        ptr_solver_->solve(dc, wp_, ws_, this->reference_share_penalty(), vm_util_map);

        // Check solution and act accordingly

        //FIXME: handle ref_penalty

        if (!ptr_solver_->result().solved())
        {
            throw ::std::runtime_error("[dcs::des::cloud::optimal_initial_placement_strategy] Unable to solve optimal problem.");
        }

        virtual_machines_placement<traits_type> deployment;

        physical_virtual_machine_map pm_vm_map(ptr_solver_->result().placement());
//[XXX]
        ::std::cerr << "CHECK SOLVER INITIAL PLACEMENT" << ::std::endl;//XXX
        for (typename physical_virtual_machine_map::const_iterator it = ptr_solver_->result().placement().begin(); it != ptr_solver_->result().placement().end(); ++it)//XXX
        {   //XXX
            ::std::cerr << "VM ID: " << (it->first.second) << " placed on PM ID: " << (it->first.first) << " with SHARE: " << ((it->second)[0].second) << ::std::endl;//XXX
        }//XXX
//[/XXX]
        physical_virtual_machine_iterator pm_vm_end_it(pm_vm_map.end());
        for (physical_virtual_machine_iterator pm_vm_it = pm_vm_map.begin(); pm_vm_it != pm_vm_end_it; ++pm_vm_it)
        {
            physical_machine_pointer ptr_pm(dc.physical_machine_ptr(pm_vm_it->first.first));
            virtual_machine_pointer ptr_vm(dc.virtual_machine_ptr(pm_vm_it->first.second));
            resource_share_container shares(pm_vm_it->second);

//::std::cerr << "Going to migrate VM (" << pm_vm_it->first.second << "): " << *ptr_vm << " into PM (" << pm_vm_it->first.first << "): " << *ptr_pm << ::std::endl; //XXX
            deployment.place(*ptr_vm,
                             *ptr_pm,
                             shares.begin(),
                             shares.end());
            DCS_DEBUG_TRACE("Placed: VM(" << ptr_vm->id() << ") -> PM(" << ptr_pm->id() << ")");//XXX
        }

        ::std::cerr << "[optimal_initial_placement] END Initial Placement" << ::std::endl;//XXX
        DCS_DEBUG_TRACE("END Initial Placement ==> " << deployment);///XXX
        return deployment;
    }
Exemplo n.º 10
0
double Security::value(const QDate &date, bool estimate, bool no_scheduled_shares) {
    if(estimate && date > QDate::currentDate()) return shares(date, estimate, no_scheduled_shares) * expectedQuotation(date);
    return shares(date, estimate, no_scheduled_shares) * getQuotation(date);
}
Exemplo n.º 11
0
double Security::value() {
    return shares() * getQuotation(QDate::currentDate());
}
Exemplo n.º 12
0
    void DrrnPsiClient::recv(Channel s0, Channel s1, span<block> inputs)
    {
        if (inputs.size() != mClientSetSize)
            throw std::runtime_error(LOCATION);

        Matrix<u64> bins(mNumSimpleBins, mBinSize);
        std::vector<u64> binSizes(mNumSimpleBins);
        u64 cuckooSlotsPerBin = (mCuckooParams.numBins() + mNumSimpleBins) / mNumSimpleBins;

        // Simple hashing with a PRP
        std::vector<block> hashs(inputs.size());
        AES hasher(mHashingSeed);
        u64 numCuckooBins = mCuckooParams.numBins();
        for (u64 i = 0; i < u64(inputs.size());)
        {
            auto min = std::min<u64>(inputs.size() - i, 8);
            auto end = i + min;
            hasher.ecbEncBlocks(inputs.data() + i, min, hashs.data() + i);
            for (; i < end; ++i)
            {
                hashs[i] = hashs[i] ^ inputs[i];
                for (u64 j = 0; j < mCuckooParams.mNumHashes; ++j)
                {
                    u64 idx = CuckooIndex<>::getHash(hashs[i], j, numCuckooBins) * mNumSimpleBins / mCuckooParams.numBins();

                    // insert this item in this bin. pack together the hash index and input index
                    bins(idx, binSizes[idx]++) = (j << 56) | i;
                }

                //if (!i)
                //{
                //    ostreamLock(std::cout) << "cinput[" << i << "] = " << inputs[i] << " -> " << hashs[i] << " ("
                //        << CuckooIndex<>::getHash(hashs[i], 0, numCuckooBins) << ", "
                //        << CuckooIndex<>::getHash(hashs[i], 1, numCuckooBins) << ", "
                //        << CuckooIndex<>::getHash(hashs[i], 2, numCuckooBins) << ")"
                //        << std::endl;
                //}
            }
        }



        // power of 2
        u64 numLeafBlocks = (cuckooSlotsPerBin + mBigBlockSize * 128 - 1) / (mBigBlockSize * 128);
        u64 gDepth = 2;
        u64 kDepth = std::max<u64>(gDepth, log2floor(numLeafBlocks)) - gDepth;
        u64 groupSize = (numLeafBlocks + (u64(1) << kDepth) - 1) / (u64(1) << kDepth);
        if (groupSize > 8) throw std::runtime_error(LOCATION);

        //std::cout << "kDepth:   " << kDepth << std::endl;
        //std::cout << "mBinSize: " << mBinSize << std::endl;

        u64 numQueries = mNumSimpleBins * mBinSize;
        auto permSize = numQueries * mBigBlockSize;

        // mask generation
        block rSeed = CCBlock;// mPrng.get<block>();
        AES rGen(rSeed);


        std::vector<block> shares(mClientSetSize * mCuckooParams.mNumHashes), r(permSize), piS1(permSize), s(permSize);
        //std::vector<u32> rIdxs(numQueries);
        //std::vector<u64> sharesIdx(shares.size());

        //TODO("use real masks");
        //memset(r.data(), 0, r.size() * sizeof(block));
        rGen.ecbEncCounterMode(r.size() * 0, r.size(), r.data());
        rGen.ecbEncCounterMode(r.size() * 1, r.size(), piS1.data());
        rGen.ecbEncCounterMode(r.size() * 2, r.size(), s.data());

        //auto encIter = enc.begin();
        auto shareIter = shares.begin();
        //auto shareIdxIter = sharesIdx.begin();
        u64 queryIdx = 0, dummyPermIdx = mClientSetSize * mCuckooParams.mNumHashes;

        std::unordered_map<u64, u64> inputMap;
        inputMap.reserve(mClientSetSize * mCuckooParams.mNumHashes);

        std::vector<u32> pi(permSize);
        auto piIter = pi.begin();


        u64 keySize = kDepth + 1 + groupSize;
        u64 mask = (u64(1) << 56) - 1;
        auto binIter = bins.begin();
        for (u64 bIdx = 0; bIdx < mNumSimpleBins; ++bIdx)
        {
            u64 i = 0;

            auto binOffset = (bIdx * numCuckooBins + mNumSimpleBins - 1) / mNumSimpleBins;

            std::vector<block> k0(keySize * mBinSize), k1(keySize * mBinSize);
            //std::vector<u64> idx0(mBinSize), idx1(mBinSize);
            auto k0Iter = k0.data(), k1Iter = k1.data();
            //auto idx0Iter = idx0.data(), idx1Iter = idx1.data();

            for (; i < binSizes[bIdx]; ++i)
            {
                span<block>
                    kk0(k0Iter, kDepth + 1),
                    g0(k0Iter + kDepth + 1, groupSize),
                    kk1(k1Iter, kDepth + 1),
                    g1(k1Iter + kDepth + 1, groupSize);

                k0Iter += keySize;
                k1Iter += keySize;

                u8 hashIdx = *binIter >> 56;
                u64 itemIdx = *binIter & mask;
                u64 cuckooIdx = CuckooIndex<>::getHash(hashs[itemIdx], hashIdx, numCuckooBins) - binOffset;
                ++binIter;

                auto bigBlockoffset = cuckooIdx % mBigBlockSize;
                auto bigBlockIdx = cuckooIdx / mBigBlockSize;

                BgiPirClient::keyGen(bigBlockIdx, mPrng.get<block>(), kk0, g0, kk1, g1);



                // the index of the mask that will mask this item
                auto rIdx = *piIter = itemIdx * mCuckooParams.mNumHashes + hashIdx * mBigBlockSize + bigBlockoffset;

                // the masked value that will be inputted into the PSI
                *shareIter = r[rIdx] ^ inputs[itemIdx];
                //*shareIter = inputs[itemIdx];

                //if (itemIdx == 0)
                //    ostreamLock(std::cout)
                //    << "item[" << i << "]    bin " << bIdx
                //    << " block " << bigBlockIdx 
                //    << " offset " << bigBlockoffset 
                //    << " psi " << *shareIter << std::endl;

                // This will be used to map itemed items in the intersection back to their input item
                inputMap.insert({ queryIdx, itemIdx });

                ++shareIter;
                ++piIter;
                ++queryIdx;
            }

            u64 rem = mBinSize - i;


            binIter += rem;
            for (u64 i = 0; i < rem; ++i)
            {
                *piIter++ = dummyPermIdx++;
            }

            //s0.asyncSendCopy(k0);
            //s0.asyncSendCopy(k1);
            //s1.asyncSendCopy(k1);
            //s1.asyncSendCopy(k0);

            s0.asyncSend(std::move(k0));
            s1.asyncSend(std::move(k1));

        }

        std::vector<u32> pi1(permSize), pi0(permSize), pi1Inv(permSize);
        for (u32 i = 0; i < pi1.size(); ++i) pi1[i] = i;
        PRNG prng(rSeed ^ OneBlock);
        std::random_shuffle(pi1.begin(), pi1.end(), prng);


        //std::vector<block> pi1RS(pi.size());
        for (u64 i = 0; i < permSize; ++i)
        {
            //auto pi1i = pi1[i];
            //pi1RS[i] = r[pi1i] ^ s[pi1i];

            pi1Inv[pi1[i]] = i;
            //std::cout << "pi1(r + s)[" << i << "] " << pi1RS[i] << std::endl;
        }
        std::vector<block> piS0(r.size());
        for (u64 i = 0; i < permSize; ++i)
        {
            //std::cout << "r[" << i << "] " << r[i] << std::endl;
            //std::cout << "pi(r + s)[" << i << "]=" << (r[pi[i]] ^ s[pi[i]]) << std::endl;


            pi0[i] = pi1Inv[pi[i]];
            piS0[i] = piS1[i] ^ s[pi[i]];
            //std::cout << "pi (r + s)[" << i << "] = " << (r[pi[i]] ^ s[pi[i]]) << " = " << r[pi[i]] << " ^ " << s[pi[i]] << " c " << pi[i] << std::endl;
            //std::cout << "pi`(r + s)[" << i << "] = " << pi1RS[pi0[i]]  <<" c " << pi0[pi1[i]] << std::endl;
        }

        s0.asyncSend(std::move(pi0));
        s0.asyncSend(std::move(piS0));
        //rGen.ecbEncBlocks(r.data(), r.size(), r.data());
        //for (u64 i = 0; i < shares.size(); ++i)
        //{
        //    std::cout << IoStream::lock << "cshares[" << i << "] " << shares[i] << " input[" << sharesIdx[i]<<"]" << std::endl << IoStream::unlock;
        //}
        mPsi.sendInput(shares, s0);

        mIntersection.reserve(mPsi.mIntersection.size());
        for (u64 i = 0; i < mPsi.mIntersection.size(); ++i) {
            // divide index by #hashes
            mIntersection.emplace(inputMap[mPsi.mIntersection[i]]);
        }

    }
Exemplo n.º 13
0
/**
 * Join the link graph job and destroy it.
 */
LinkGraphJob::~LinkGraphJob()
{
	this->JoinThread();

	/* Don't update stuff from other pools, when everything is being removed.
	 * Accessing other pools may be invalid. */
	if (CleaningPool()) return;

	/* Link graph has been merged into another one. */
	if (!LinkGraph::IsValidID(this->link_graph.index)) return;

	uint size = this->Size();
	for (NodeID node_id = 0; node_id < size; ++node_id) {
		Node from = (*this)[node_id];

		/* The station can have been deleted. Remove all flows originating from it then. */
		Station *st = Station::GetIfValid(from.Station());
		if (st == NULL) {
			this->EraseFlows(node_id);
			continue;
		}

		/* Link graph merging and station deletion may change around IDs. Make
		 * sure that everything is still consistent or ignore it otherwise. */
		GoodsEntry &ge = st->goods[this->Cargo()];
		if (ge.link_graph != this->link_graph.index || ge.node != node_id) {
			this->EraseFlows(node_id);
			continue;
		}

		LinkGraph *lg = LinkGraph::Get(ge.link_graph);
		FlowStatMap &flows = from.Flows();

		for (EdgeIterator it(from.Begin()); it != from.End(); ++it) {
			if (from[it->first].Flow() == 0) continue;
			StationID to = (*this)[it->first].Station();
			Station *st2 = Station::GetIfValid(to);
			if (st2 == NULL || st2->goods[this->Cargo()].link_graph != this->link_graph.index ||
					st2->goods[this->Cargo()].node != it->first ||
					(*lg)[node_id][it->first].LastUpdate() == INVALID_DATE) {
				/* Edge has been removed. Delete flows. */
				StationIDStack erased = flows.DeleteFlows(to);
				/* Delete old flows for source stations which have been deleted
				 * from the new flows. This avoids flow cycles between old and
				 * new flows. */
				while (!erased.IsEmpty()) ge.flows.erase(erased.Pop());
			} else if ((*lg)[node_id][it->first].LastUnrestrictedUpdate() == INVALID_DATE) {
				/* Edge is fully restricted. */
				flows.RestrictFlows(to);
			}
		}

		/* Swap shares and invalidate ones that are completely deleted. Don't
		 * really delete them as we could then end up with unroutable cargo
		 * somewhere. Do delete them and also reroute relevant cargo if
		 * automatic distribution has been turned off for that cargo. */
		for (FlowStatMap::iterator it(ge.flows.begin()); it != ge.flows.end();) {
			FlowStatMap::iterator new_it = flows.find(it->first);
			if (new_it == flows.end()) {
				if (_settings_game.linkgraph.GetDistributionType(this->Cargo()) != DT_MANUAL) {
					it->second.Invalidate();
					++it;
				} else {
					FlowStat shares(INVALID_STATION, 1);
					it->second.SwapShares(shares);
					ge.flows.erase(it++);
					for (FlowStat::SharesMap::const_iterator shares_it(shares.GetShares()->begin());
							shares_it != shares.GetShares()->end(); ++shares_it) {
						RerouteCargo(st, this->Cargo(), shares_it->second, st->index);
					}
				}
			} else {
				it->second.SwapShares(new_it->second);
				flows.erase(new_it);
				++it;
			}
		}
		ge.flows.insert(flows.begin(), flows.end());
		InvalidateWindowData(WC_STATION_VIEW, st->index, this->Cargo());
	}
}
Exemplo n.º 14
0
std::vector<RTSS_Share>
RTSS_Share::split(uint8_t M, uint8_t N,
                  const uint8_t S[], uint16_t S_len,
                  const std::vector<uint8_t>& identifier,
                  const std::string& hash_fn,
                  RandomNumberGenerator& rng)
   {
   if(M <= 1 || N <= 1 || M > N || N >= 255)
      throw Invalid_Argument("RTSS_Share::split: Invalid N or M");

   if(identifier.size() > 16)
      throw Invalid_Argument("RTSS_Share::split Invalid identifier size");

   const uint8_t hash_id = rtss_hash_id(hash_fn);

   std::unique_ptr<HashFunction> hash;
   if(hash_id > 0)
      hash = HashFunction::create_or_throw(hash_fn);

   // secret = S || H(S)
   secure_vector<uint8_t> secret(S, S + S_len);
   if(hash)
      secret += hash->process(S, S_len);

   if(secret.size() >= 0xFFFE)
      throw Encoding_Error("RTSS_Share::split secret too large for TSS format");

   // +1 byte for the share ID
   const uint16_t share_len = static_cast<uint16_t>(secret.size() + 1);

   secure_vector<uint8_t> share_header(RTSS_HEADER_SIZE);
   copy_mem(&share_header[0], identifier.data(), identifier.size());
   share_header[16] = hash_id;
   share_header[17] = M;
   share_header[18] = get_byte(0, share_len);
   share_header[19] = get_byte(1, share_len);

   // Create RTSS header in each share
   std::vector<RTSS_Share> shares(N);

   for(uint8_t i = 0; i != N; ++i)
      {
      shares[i].m_contents.reserve(share_header.size() + share_len);
      shares[i].m_contents = share_header;
      }

   // Choose sequential values for X starting from 1
   for(uint8_t i = 0; i != N; ++i)
      shares[i].m_contents.push_back(i+1);

   for(size_t i = 0; i != secret.size(); ++i)
      {
      std::vector<uint8_t> coefficients(M-1);
      rng.randomize(coefficients.data(), coefficients.size());

      for(uint8_t j = 0; j != N; ++j)
         {
         const uint8_t X = j + 1;

         uint8_t sum = secret[i];
         uint8_t X_i = X;

         for(size_t k = 0; k != coefficients.size(); ++k)
            {
            sum ^= gfp_mul(X_i, coefficients[k]);
            X_i  = gfp_mul(X_i, X);
            }

         shares[j].m_contents.push_back(sum);
         }
      }

   return shares;
   }