OTExtensionWithMatrix OTExtensionWithMatrix::setup(TwoPartyPlayer& player, int128 delta, OT_ROLE role, bool passive) { BaseOT baseOT(128, 128, &player, INV_ROLE(role)); PRNG G; G.ReSeed(); baseOT.set_receiver_inputs(delta); baseOT.exec_base(false); return OTExtensionWithMatrix(baseOT, &player, passive); }
void BitMatrixSlice::randomize(int row, PRNG& G) { const int block_size = RAND_SIZE / sizeof(bm.squares[0].rows[0]); auto iSquare = bm.squares.begin() + start; for ( ; iSquare < bm.squares.end() - block_size; ) { G.next(); for (int j = 0; j < block_size; j++) (iSquare++)->rows[row] = G.get_doubleword_no_check(); } for ( ; iSquare < bm.squares.end(); iSquare++) iSquare->randomize(row, G); }
int main() { RC4 rc4; PRNG *prng = &rc4; prng->initialize("Key"); for(int x = 0; x < 10; x++) std::cout << std::hex << (int) prng->get_byte() << " "; std::cout << std::endl; prng->initialize("Key"); for(int x = 0; x < 15; x++) std::cout << std::hex << (int) prng->get_byte() << " "; std::cout << std::endl; return 0; }
int main() { //std::ofstream fout("Tests.txt"); PRNG randoms; //Build vector of functions for later use std::vector<void (*)(std::vector<int>&, bool, std::ostream&)> fasts; fasts.push_back(NaiveQuickSort); fasts.push_back(QuickSortMedian); fasts.push_back(QuickSort); //Test the multithreaded algorithms cout <<"\n----Testing Algorithms----\n"; for(unsigned int i = 0; i < fasts.size(); i++) { //Build test vectors std::vector<int> rands; for(unsigned int j = 0; j < 10000000; j++) { rands.push_back(randoms.randInt()); } if(i==0) cout << "Naive Algorithm----\n"; if(i==1) cout << "Adding Median of Three----\n"; if(i==2) cout << "Multithreading, Median of Three, ShellSort on small data---\n"; SortOperation(rands, fasts[i], cout); cout << "\n"; } //Test the std::sort method as well std::vector<int> rands; for(unsigned int j = 0; j < 10000000; j++) { rands.push_back(randoms.randInt()); } cout << "Testing std::sort---\n"; clock_t start = clock(); std::sort(rands.begin(),rands.end()); clock_t finish = clock(); cout << (static_cast<double>(finish - start) / static_cast<double>(CLOCKS_PER_SEC)); cout << std::endl; //fout.close(); system("PAUSE"); return 0; }
void MAC_Check<T>::Check(const Player& P) { if (WaitingForCheck() == 0) return; //cerr << "In MAC Check : " << popen_cnt << endl; octet seed[SEED_SIZE]; this->timers[SEED].start(); Create_Random_Seed(seed,P,SEED_SIZE); this->timers[SEED].stop(); PRNG G; G.SetSeed(seed); Share<T> sj; T a,gami,h,temp; a.assign_zero(); gami.assign_zero(); vector<T> tau(P.num_players()); for (int i=0; i<popen_cnt; i++) { h.almost_randomize(G); temp.mul(h,vals[i]); a.add(a,temp); temp.mul(h,macs[i]); gami.add(gami,temp); } vals.erase(vals.begin(), vals.begin() + popen_cnt); macs.erase(macs.begin(), macs.begin() + popen_cnt); temp.mul(this->alphai,a); tau[P.my_num()].sub(gami,temp); //cerr << "\tCommit and Open" << endl; this->timers[COMMIT].start(); Commit_And_Open(tau,P); this->timers[COMMIT].stop(); //cerr << "\tFinal Check" << endl; T t; t.assign_zero(); for (int i=0; i<P.num_players(); i++) { t.add(t,tau[i]); } if (!t.is_zero()) { throw mac_fail(); } popen_cnt=0; }
void HistogramImage::render(std::vector<unsigned char> &rgb, double scale, double exponent) { // Tone mapping from 64-bit-per-channel to 8-bit-per-channel, with dithering. PRNG rng; rng.seed(0); unsigned i = 0; unsigned e = mWidth * mHeight * kChannels; rgb.resize(e); for (; i != e; ++i) { double u = std::max(0.0, mCounts[i] * scale); double dither = rng.uniform(); double v = 255.0 * pow(u, exponent) + dither; rgb[i] = std::max(0.0, std::min(255.9, v)); } }
int main(){ unsigned int seed_value[32]; for(int i=0; i<32; i++){ seed_value[i] = i*2; // Arbitrary seed value } InitWELLRNG1024a(seed_value); PRNG* rng = PRNGFactory::generatePRNG("well"); rng->set(seed_value); for(int i=0; i<10; i++){ double original_generator = WELLRNG1024a(); double PRNGFactory_generator = rng->get_double(); std::cout << original_generator << " " << PRNGFactory_generator << "\n"; if(original_generator != PRNGFactory_generator){ std::cout << "The streams do not match\n"; exit(0); } } high_resolution_clock::time_point t1, t2; // Measure the time it takes the original generator to produce 1 billion values t1 = high_resolution_clock::now(); for(int i=0; i<1000000000; i++){ unsigned long original_stream = WELLRNG1024a(); } t2 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>( t2 - t1 ).count(); std::cout << "Original well generator used "<< duration << " microseconds to generate 1 billion values" << std::endl; // Measure the time it takes the new generator to produce 1 billion values t1 = high_resolution_clock::now(); for(int i=0; i<1000000000; i++){ unsigned long PRNG_stream = rng->get_double(); } t2 = high_resolution_clock::now(); duration = duration_cast<microseconds>( t2 - t1 ).count(); std::cout << "PRNGFactory xorgens generator used "<< duration << " microseconds to generate 1 billion values" << std::endl; return 0; }
void PartSetup<FD>::insecure_debug_keys(vector<PartSetup<FD> >& setups, int nplayers, bool simple_pk) { cout << "generating INSECURE keys for debugging" << endl; setups.clear(); Rq_Element zero(params, evaluation, evaluation), one(params, evaluation, evaluation); zero.assign_zero(); one.assign_one(); PRNG G; G.ReSeed(); if (simple_pk) pk.assign(zero, zero, zero, zero - one); else pk.KeyGen(one, G, nplayers); setups.resize(nplayers, *this); setups[0].sk.assign(one); for (int i = 1; i < nplayers; i++) setups[i].sk.assign(zero); }
// For now, this just directly puts them into 'frags' void Board::randomizeRow(unsigned int i) { unsigned int maxInt = 8; // the higher, the more blank spaces //maxInt = 400; // good to keep whole pieces separate // maxInt = 8; // good for individual squares PRNG* rng = Tetris::TApp::theApp->rng; int j = rng->uniform() % clms; auto k = nFromIJ(i, j); unsigned int pi = rng->uniform() % maxInt; TCode p = ((1 <= pi) && (pi <= 7)) ? ((TCode)pi) : N; if (N != p) { Shape s = Shape(p); s.setRandomShape(); bool ok = testShape(s, i, j); if (ok) { placeShape(s,i,j); s.showCoords(); cout << endl << flush; } } return; }
unsigned Random<T_PRNG>::CalcChecksum(const PRNG& rng) { // This is designed in a way that makes the checksum be equivalent // to the state of the OldLCG for compatibility with old versions Serializer ser; rng.serialize(ser); unsigned checksum = 0; while(ser.GetBytesLeft() >= sizeof(unsigned)) checksum += ser.PopUnsignedInt(); while(ser.GetBytesLeft()) checksum += ser.PopUnsignedChar(); return checksum; }
void PartSetup<FD>::fake(vector<FHE_SK>& sks, vector<T>& alphais, int nplayers, bool distributed) { insecure("global key generation"); if (distributed) cout << "Faking distributed key generation" << endl; else cout << "Faking key generation with extra noise" << endl; PRNG G; G.ReSeed(); pk = FHE_PK(params, FieldD.get_prime()); FHE_SK sk(params, FieldD.get_prime()); calpha = Ciphertext(params); sks.resize(nplayers, pk); alphais.resize(nplayers); if (distributed) DistKeyGen::fake(pk, sks, FieldD.get_prime(), nplayers); else { Rq_Element sk = FHE_SK(pk).s(); for (int i = 0; i < nplayers; i++) { Rq_Element ski = pk.sample_secret_key(G); sks[i].assign(ski); sk += ski; } pk.KeyGen(sk, G, nplayers); } for (int i = 0; i < nplayers; i++) { Plaintext_<FD> m(FieldD); m.randomize(G,Diagonal); Ciphertext calphai = pk.encrypt(m); calpha += calphai; alphais[i] = m.element(0); } }
void Zobrist::init() { PRNG prng; // turn turn = prng.next64(); // epFile for (int i=0; i<8; i++) epFile[i] = prng.next64(); // piece memset( piece, 0, sizeof(piece) ); for (Color c=ctWhite; c<=ctBlack; c++) for (Piece p=ptPawn; p<=ptKing; p++) for (Square sq = 0; sq < 64; sq++ ) piece[c][p][sq] = prng.next64(); // castling cast[ ctWhite ][0] = cast[ ctBlack ][0] = 0; for (Color c=ctWhite; c<=ctBlack; c++) for (uint i=1; i<=0x88; i++) cast[c][i] = prng.next64(); }
void OTExtensionWithMatrix::transfer(int nOTs, const BitVector& receiverInput) { #ifdef OTEXT_TIMER timeval totalstartv, totalendv; gettimeofday(&totalstartv, NULL); #endif cout << "\tDoing " << nOTs << " extended OTs as " << role_to_str(ot_role) << endl; if (nOTs % nbaseOTs != 0) throw invalid_length(); //"nOTs must be a multiple of nbaseOTs\n"); if (nOTs == 0) return; // add k + s to account for discarding k OTs nOTs += 2 * 128; int slice = nOTs / nsubloops / 128; BitMatrix t1(nOTs), u(nOTs); senderOutputMatrices.resize(2, BitMatrix(nOTs)); // resize to account for extra k OTs that are discarded PRNG G; G.ReSeed(); BitVector newReceiverInput(nOTs); for (unsigned int i = 0; i < receiverInput.size_bytes(); i++) { newReceiverInput.set_byte(i, receiverInput.get_byte(i)); } //BitVector newReceiverInput(receiverInput); newReceiverInput.resize(nOTs); receiverOutputMatrix.resize(nOTs); for (int loop = 0; loop < nloops; loop++) { // randomize last 128 + 128 bits that will be discarded for (int i = 0; i < 4; i++) newReceiverInput.set_word(nOTs/64 - i, G.get_word()); // subloop for first part to interleave communication with computation for (int start = 0; start < nOTs / 128; start += slice) { vector<octetStream> os(2); BitMatrixSlice receiverOutputSlice(receiverOutputMatrix, start, slice); BitMatrixSlice senderOutputSlices[2] = { BitMatrixSlice(senderOutputMatrices[0], start, slice), BitMatrixSlice(senderOutputMatrices[1], start, slice) }; BitMatrixSlice t1Slice(t1, start, slice); BitMatrixSlice uSlice(u, start, slice); // expand with PRG and create correlation if (ot_role & RECEIVER) { for (int i = 0; i < nbaseOTs; i++) { receiverOutputSlice.randomize(i, G_sender[i][0]); t1Slice.randomize(i, G_sender[i][1]); } t1Slice ^= receiverOutputSlice; t1Slice ^= newReceiverInput; t1Slice.pack(os[0]); // t1 = receiverOutputMatrix; // t1 ^= newReceiverInput; // receiverOutputMatrix.print_side_by_side(t1); } #ifdef OTEXT_TIMER timeval commst1, commst2; gettimeofday(&commst1, NULL); #endif // send t0 + t1 + x send_if_ot_receiver(player, os, ot_role); // sender adjusts using base receiver bits if (ot_role & SENDER) { for (int i = 0; i < nbaseOTs; i++) // randomize base receiver output senderOutputSlices[0].randomize(i, G_receiver[i]); // u = t0 + t1 + x uSlice.unpack(os[1]); senderOutputSlices[0].conditional_xor(baseReceiverInput, u); } #ifdef OTEXT_TIMER gettimeofday(&commst2, NULL); #ifdef VERBOSE double commstime = timeval_diff(&commst1, &commst2); cout << "\t\tCommunication took time " << commstime/1000000 << endl << flush; #endif times["Communication"] += timeval_diff(&commst1, &commst2); #endif // transpose t0[i] onto receiverOutput and tmp (q[i]) onto senderOutput[i][0] #ifdef VERBOSE cout << "Starting matrix transpose\n" << flush << endl; #endif #ifdef OTEXT_TIMER timeval transt1, transt2; gettimeofday(&transt1, NULL); #endif // transpose in 128-bit chunks if (ot_role & RECEIVER) receiverOutputSlice.transpose(); if (ot_role & SENDER) senderOutputSlices[0].transpose(); #ifdef OTEXT_TIMER gettimeofday(&transt2, NULL); #ifdef VERBOSE double transtime = timeval_diff(&transt1, &transt2); cout << "\t\tMatrix transpose took time " << transtime/1000000 << endl << flush; #endif times["Matrix transpose"] += timeval_diff(&transt1, &transt2); #endif } // correlation check if (!passive_only) { #ifdef OTEXT_TIMER timeval startv, endv; gettimeofday(&startv, NULL); #endif check_correlation(nOTs, newReceiverInput); #ifdef OTEXT_TIMER gettimeofday(&endv, NULL); #ifdef VERBOSE double elapsed = timeval_diff(&startv, &endv); cout << "\t\tTotal correlation check time: " << elapsed/1000000 << endl << flush; #endif times["Total correlation check"] += timeval_diff(&startv, &endv); #endif } hash_outputs(nOTs); #ifdef OTEXT_TIMER #ifdef VERBOSE gettimeofday(&totalendv, NULL); double elapsed = timeval_diff(&totalstartv, &totalendv); cout << "\t\tTotal thread time: " << elapsed/1000000 << endl << flush; #endif #endif } #ifdef OTEXT_TIMER gettimeofday(&totalendv, NULL); times["Total thread"] += timeval_diff(&totalstartv, &totalendv); #endif receiverOutputMatrix.resize(nOTs - 2 * 128); senderOutputMatrices[0].resize(nOTs - 2 * 128); senderOutputMatrices[1].resize(nOTs - 2 * 128); }
int main(int ac, char **av) { el::Configurations confFromFile("./rpdemo-logger.conf"); el::Loggers::reconfigureAllLoggers(confFromFile); using KBase::ReportingLevel; using KBase::PRNG; using KBase::MtchPstn; using KBase::dSeed; using RfrmPri::RPModel; using RfrmPri::RPState; using RfrmPri::RPActor; //using RfrmPri::printPerm; auto sTime = KBase::displayProgramStart(RfrmPri::appName, RfrmPri::appVersion); uint64_t seed = dSeed; // arbitrary; bool siP = true; bool cpP = false; bool runP = true; unsigned int sNum = 1; bool xmlP = false; bool rp2P = false; std::string inputXML = ""; auto showHelp = [sNum]() { printf("\n"); printf("Usage: specify one or more of these options\n"); printf("\n"); printf("--cp start all actors from the central position \n"); printf("--rp2 create RP2 objects \n"); printf("--si start each actor from their most self-interested position \n"); printf(" If neither si nor cp are specified, it will use si. \n"); printf(" If both si and cp are specified, it will use second specified. \n"); printf("--help print this message and exit \n"); printf("--seed <n> set a 64bit seed \n"); printf(" 0 means truly random \n"); printf(" default: %020llu \n", dSeed); printf("--sNum <n> choose a scenario number \n"); printf(" default: %u \n", sNum); printf(" 0: random example, potentially VERY large \n"); printf(" 1: hard-coded example, moderate size \n"); printf("--xml <f> read XML scenario from a given file \n"); printf("\n"); printf("For example, rpdemo --si --xml rpdata.xml, would read the file rpdata.xml \n"); printf("and start all actors from self-interested positions.\n"); printf("\n"); printf("If both scenario number and XML file are specified, it will use only the XML.\n"); printf("\n"); printf("If neither scenario number nor XML file are specified, \n"); printf("it will run a hard-coded example, as if --sNum 1 had been specified.\n"); printf("\n"); }; // a list of <keyword, description, λ-fn> // might be enough to do this - except for the arguments to options. if (ac > 1) { for (int i = 1; i < ac; i++) { if (strcmp(av[i], "--seed") == 0) { i++; seed = std::stoull(av[i]); } else if (strcmp(av[i], "--sNum") == 0) { i++; sNum = atoi(av[i]); } else if (strcmp(av[i], "--xml") == 0) { xmlP = true; i++; inputXML = av[i]; } else if (strcmp(av[i], "--rp2") == 0) { rp2P = true; } else if (strcmp(av[i], "--si") == 0) { cpP = false; siP = true; } else if (strcmp(av[i], "--cp") == 0) { siP = false; cpP = true; } else if (strcmp(av[i], "--help") == 0) { runP = false; } else { runP = false; printf("Unrecognized argument: %s\n", av[i]); } } } else { runP = false; } if (!runP) { showHelp(); return 0; } if (0 == seed) { PRNG * rng = new PRNG(); seed = rng->setSeed(0); // 0 == get a random number delete rng; rng = nullptr; } LOG(INFO) << KBase::getFormattedString("Using PRNG seed: %020llu", seed); LOG(INFO) << KBase::getFormattedString("Same seed in hex: 0x%016llX", seed); // Unix correctly prints all digits with lu, lX, llu, and llX. // Windows only prints part, with lu, lX, llu, and llX. const bool parP = KBase::testMultiThreadSQLite(false, KBase::ReportingLevel::Medium); if (parP) { LOG(INFO) << "Can continue with multi-threaded execution"; } else { LOG(INFO) << "Must continue with single-threaded execution"; } if (rp2P) { RfrmPri2::rp2Creation(seed); return 0; } auto rpm = new RPModel("", seed); if (xmlP) { rpm->readXML(inputXML); LOG(INFO) << "done reading XML"; } else { switch (sNum) { case 0: case 1: rpm->initScen(sNum); break; default: LOG(INFO) << "Unrecognized scenario number" << sNum; assert(false); break; } } unsigned int numA = rpm->numAct; // the actors are as yet unnamed unsigned int numR = rpm->numItm; //unsigned int numC = rpm->numCat; auto rps0 = new RPState(rpm); rpm->addState(rps0); // NOTE WELL: Records each actor's most self-interested position, but does not set them. // Further, it appends Central Position after the last actor position auto siPstns = RfrmPri::scanAllPossiblePositions(rpm); assert(numA + 1 == siPstns.size()); const KBase::VUI bestPerm = siPstns[numA]; assert(numR == bestPerm.size()); assert(numA == rps0->pstns.size()); // pre-allocated by constructor, all nullptr's // Move them all to either the CP or to SI positions which // maximize their direct utility, regardless of expected utility. for (unsigned int i = 0; i < numA; i++) { auto pi = new MtchPstn(); pi->numCat = numR; pi->numItm = numR; if (cpP) { pi->match = bestPerm; } else { pi->match = siPstns[i]; } rps0->pstns[i] = pi; } assert(numA == rps0->pstns.size()); rps0->step = [rps0]() { return rps0->stepSUSN(); }; unsigned int maxIter = 100; rpm->stop = [maxIter, rpm](unsigned int iter, const KBase::State * s) { bool doneP = iter > maxIter; if (doneP) { LOG(INFO) << "Max iteration limit of" << maxIter << "exceeded"; } auto s2 = ((const RPState *)(rpm->history[iter])); for (unsigned int i = 0; i < iter; i++) { auto s1 = ((const RPState *)(rpm->history[i])); if (RPModel::equivStates(s1, s2)) { doneP = true; LOG(INFO) << "State number" << iter << "matched state number" << i; } } return doneP; }; rps0->setUENdx(); rpm->run(); // we already displayed each state as it was processed, // so there is no need to show it again //rpm->showHist(); delete rpm; // and actors, and states rpm = nullptr; rps0 = nullptr; KBase::displayProgramEnd(sTime); return 0; }
void square128::randomize(int row, PRNG& G) { rows[row] = G.get_doubleword(); }
void square128::randomize(PRNG& G) { G.get_octets((octet*)&rows, sizeof(rows)); }
void MainThread::think() { Move bestMove; // --------------------- // 合法手がないならここで投了 // --------------------- if (rootMoves.size() == 0) { bestMove = MOVE_RESIGN; Signals.stop = true; goto ID_END; } // --------------------- // 定跡の選択部 // --------------------- { static PRNG prng; auto it = book.find(rootPos.sfen()); if (it != book.end()) { // 定跡にhitした。逆順で出力しないと将棋所だと逆順にならないという問題があるので逆順で出力する。 const auto& move_list = it->second; for (auto it = move_list.rbegin(); it != move_list.rend();it++ ) sync_cout << "info pv " << it->bestMove << " " << it->nextMove << " (" << fixed << setprecision(2) << (100* it->prob) << "%)" // 採択確率 << " score cp " << it->value << " depth " << it->depth << sync_endl; // このなかの一つをランダムに選択 // 無難な指し手が選びたければ、採択回数が一番多い、最初の指し手(move_list[0])を選ぶべし。 bestMove = move_list[prng.rand(move_list.size())].bestMove; Signals.stop = true; goto ID_END; } } // --------------------- // 通常の思考処理 // --------------------- { rootDepth = 0; Value alpha, beta; StateInfo si; auto& pos = rootPos; // --- 置換表のTTEntryの世代を進める。 TT.new_search(); // --------------------- // 思考の終了条件 // --------------------- std::thread* timerThread = nullptr; // 探索深さ、ノード数、詰み手数が指定されていない == 探索時間による制限 if (!(Limits.depth || Limits.nodes || Limits.mate)) { // 時間制限があるのでそれに従うために今回の思考時間を計算する。 // 今回に用いる思考時間 = 残り時間の1/60 + 秒読み時間 auto us = pos.side_to_move(); // 2秒未満は2秒として問題ない。(CSAルールにおいて) auto availableTime = std::max(2000, Limits.time[us] / 60 + Limits.byoyomi[us]); // 思考時間は秒単位で繰り上げ availableTime = (availableTime / 1000) * 1000; // 50msより小さいと思考自体不可能なので下限を50msに。 availableTime = std::max(50, availableTime - Options["NetworkDelay"]); auto endTime = Limits.startTime + availableTime; // タイマースレッドを起こして、終了時間を監視させる。 timerThread = new std::thread([&] { while (now() < endTime && !Signals.stop) sleep(10); Signals.stop = true; }); } // --------------------- // 反復深化のループ // --------------------- while (++rootDepth < MAX_PLY && !Signals.stop && (!Limits.depth || rootDepth <= Limits.depth)) { // 本当はもっと探索窓を絞ったほうが効率がいいのだが…。 alpha = -VALUE_INFINITE; beta = VALUE_INFINITE; PVIdx = 0; // MultiPVではないのでPVは1つで良い。 YaneuraOuNano::search<Root>(rootPos, alpha, beta, rootDepth*ONE_PLY); // それぞれの指し手に対するスコアリングが終わったので並べ替えおく。 std::stable_sort(rootMoves.begin(), rootMoves.end()); // 読み筋を出力しておく。 sync_cout << USI::pv(pos, rootDepth, alpha, beta) << sync_endl; } bestMove = rootMoves.at(0).pv[0]; // --------------------- // タイマースレッド終了 // --------------------- Signals.stop = true; if (timerThread != nullptr) { timerThread->join(); delete timerThread; } } ID_END:; // 反復深化の終了。 // --------------------- // 指し手をGUIに返す // --------------------- // ponder中であるならgoコマンドか何かが送られてきてからのほうがいいのだが、とりあえずponderの処理は後回しで…。 sync_cout << "bestmove " << bestMove << sync_endl; }
void MainThread::think() { MoveList<LEGAL_ALL> ml(rootPos); Move m = (ml.size() == 0) ? MOVE_RESIGN : ml.at(size_t(my_rand.rand(ml.size()))).move; sync_cout << "bestmove " << m << sync_endl; }
void PairwiseGenerator<FD>::run() { PRNG G; G.ReSeed(); MAC_Check<typename FD::T> MC(machine.setup<FD>().alphai); while (total < machine.nTriplesPerThread) { timers["Randomization"].start(); a.randomize(G); b.randomize(G); timers["Randomization"].stop(); size_t prover_memory = EC.generate_proof(C, a, ciphertexts, cleartexts); timers["Plaintext multiplication"].start(); c.mul(a, b); timers["Plaintext multiplication"].stop(); timers["FFT of b"].start(); for (int i = 0; i < machine.sec; i++) b_mod_q.at(i).from_vec(b.at(i).get_poly()); timers["FFT of b"].stop(); timers["Proof exchange"].start(); size_t verifier_memory = EC.create_more(ciphertexts, cleartexts); timers["Proof exchange"].stop(); volatile_memory = max(prover_memory, verifier_memory); Rq_Element values({machine.setup<FD>().params, evaluation, evaluation}); for (int k = 0; k < machine.sec; k++) { producer.ai = a[k]; producer.bi = b[k]; producer.ci = c[k]; for (int j = 0; j < 3; j++) { timers["Plaintext multiplication"].start(); producer.macs[j].mul(machine.setup<FD>().alpha, producer.values[j]); timers["Plaintext multiplication"].stop(); if (j == 1) values = b_mod_q[k]; else { timers["Plaintext conversion"].start(); values.from_vec(producer.values[j].get_poly()); timers["Plaintext conversion"].stop(); } for (auto m : multipliers) m->multiply_alpha_and_add(producer.macs[j], values); } producer.reset(); total += producer.sacrifice(P, MC); } timers["Checking"].start(); MC.Check(P); timers["Checking"].stop(); } cout << "Could save " << 1e-9 * a.report_size(CAPACITY) << " GB" << endl; timers.insert(EC.timers.begin(), EC.timers.end()); timers.insert(producer.timers.begin(), producer.timers.end()); timers["Networking"] = P.timer; }
int Narrator::script(int st, PRNG &prng) { static ChaosParticles chaosA(flow, runner.config["chaosParticles"]); static ChaosParticles chaosB(flow, runner.config["chaosParticles"]); static OrderParticles orderParticles(flow, runner.config["orderParticles"]); static Precursor precursor(flow, runner.config["precursor"]); static RingsEffect ringsA(flow, runner.config["ringsA"]); static RingsEffect ringsB(flow, runner.config["ringsB"]); static RingsEffect ringsC(flow, runner.config["ringsC"]); static PartnerDance partnerDance(flow, runner.config["partnerDance"]); static CameraFlowDebugEffect flowDebugEffect(flow, runner.config["flowDebugEffect"]); static Forest forest(flow, runner.config["forest"]); static DarknessEffect darkness; rapidjson::Value& config = runner.config["narrator"]; Sampler s(prng.uniform32()); switch (st) { ////////////////////////////////////////////////////////////////////////////////////////////// // Special states case 1: { // Darkness only ("off") crossfade(&darkness, 1); delayForever(); } case 2: { // Precursor only (sleep mode) precursor.reseed(prng.uniform32()); crossfade(&precursor, 1); delayForever(); } case 3: { // Debugging the computer vision system crossfade(&flowDebugEffect, 1); delayForever(); } ////////////////////////////////////////////////////////////////////////////////////////////// // Opening sequence case 0: { // Darkness until opening crossfade(&darkness, 1); delayUntilDate(config["opening"]["date"]); return config["opening"]["nextState"].GetInt(); } ////////////////////////////////////////////////////////////////////////////////////////////// // Cyclic states default: { endCycle(); return 10; } case 10: { // Order trying to form out of the tiniest sparks; runs for an unpredictable time, fails. precursor.reseed(prng.uniform32()); crossfade(&precursor, s.value(config["precursorCrossfade"])); // Bootstrap delay(s.value(config["precursorBootstrap"])); // Wait for darkness while (!precursor.isDone) { doFrame(); } return 20; } case 20: { // Bang. Explosive energy, hints of self-organization ChaosParticles *pChaosA = &chaosA; ChaosParticles *pChaosB = &chaosB; int bangCount = s.value(config["bangCount"]); for (int i = 0; i < bangCount; i++) { pChaosA->reseed(prng.circularVector() * s.value(config["bangSeedRadius"]), prng.uniform32()); crossfade(pChaosA, s.value(config["bangCrossfadeDuration"])); delay((1 << i) * s.value(config["bangDelayBasis"])); std::swap(pChaosA, pChaosB); } attention(s, config["bangAttention"]); return 30; } case 30: { // Textures of light, exploring something formless. Slow crossfade in ringsA.reseed(prng.uniform32()); crossfade(&ringsA, s.value(config["ringsA-Crossfade"])); attention(s, config["ringsA-Attention"]); return 40; } case 40: { // Add energy, explore another layer. ringsB.reseed(prng.uniform32()); crossfade(&ringsB, s.value(config["ringsB-Crossfade"])); attention(s, config["ringsB-Attention"]); return 50; } case 50: { // Biology happens, order emerges. Cellular look, emergent order. orderParticles.reseed(prng.uniform32()); orderParticles.symmetry = 10; crossfade(&orderParticles, s.value(config["orderCrossfade"])); while (orderParticles.symmetry > 4) { attention(s, config["orderStepAttention"]); orderParticles.symmetry--; } attention(s, config["orderStepAttention"]); return 60; } case 60: { // Two partners, populations of particles. // Spiralling inwards. Depression. Beauty on the edge of destruction, // pressing forward until nothing remains. partnerDance.reseed(prng.uniform32()); crossfade(&partnerDance, s.value(config["partnerCrossfade"])); attention(s, config["partnerAttention"]); return 70; } case 70: { // Sinking deeper. Interlude before a change. ringsC.reseed(prng.uniform32()); crossfade(&ringsC, s.value(config["ringsC-Crossfade"])); attention(s, config["ringsC-Attention"]); return 80; } case 80: { // Continuous renewal and regrowth. Destruction happens unintentionally, // regrowth is quick and generative. The only way to lose is to stagnate. forest.reseed(prng.uniform32()); crossfade(&forest, s.value(config["forestCrossfade"])); attention(s, config["forestAttention"]); return 90; } } }
void modp::randomize(PRNG& G, const Zp_Data& ZpD) { G.randomBnd(x, ZpD.get_prA(), ZpD.pr_byte_length); }
int main(int ac, char ** av) { using std::cout; using std::endl; using std::string; using KBase::PRNG; auto sTime = KBase::displayProgramStart(); uint64_t seed = KBase::dSeed; bool testP = false; bool run = true; auto showHelp = []() { printf("\n"); printf("Usage: specify one or more of these options\n"); printf("--help print this message\n"); printf("--test test some basic utilities\n"); printf("--seed <n> set a 64bit seed\n"); printf(" 0 means truly random\n"); printf(" default: %020llu \n", KBase::dSeed); }; if (ac > 1) { for (int i = 1; i < ac; i++) { if (strcmp(av[i], "--seed") == 0) { i++; seed = std::stoull(av[i]); } else if (strcmp(av[i], "--test") == 0) { testP = true; } else if (strcmp(av[i], "--help") == 0) { run = false; } else { run = false; printf("Unrecognized argument %s\n", av[i]); } } } if (!run) { showHelp(); return 0; } PRNG * rng = new PRNG(); seed = rng->setSeed(seed); // 0 == get a random number printf("Using PRNG seed: %020llu \n", seed); printf("Same seed in hex: 0x%016llX \n", seed); unsigned int n = 1000; printf("\nTesting %i ... ", n); QuadMap::testX(n); printf("done \n"); printf("\nFilling occurance matrix ..."); auto om = QuadMap::fillOccuranceMatrix(1000, 1000, 0.0, 4.0); printf("done \n"); auto t = new QuadMap::QMApp(seed); t->run(); delete t; t = nullptr; KBase::displayProgramEnd(sTime); return 0; }
void PRNG::SetSeed(PRNG& G) { octet tmp[SEED_SIZE]; G.get_octets(tmp, sizeof(tmp)); SetSeed(tmp); }
int main(int argc, const char** argv) { ezOptionParser opt; opt.add( "", // Default. 1, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "This player's number, 0/1 (required).", // Help description. "-p", // Flag token. "--player" // Flag token. ); opt.add( "5000", // Default. 0, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "Base port number (default: 5000).", // Help description. "-pn", // Flag token. "--portnum" // Flag token. ); opt.add( "localhost", // Default. 0, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "Host name(s) that player 0 is running on (default: localhost). Split with commas.", // Help description. "-h", // Flag token. "--hostname" // Flag token. ); opt.add( "1024", 0, 1, 0, "Number of extended OTs to run (default: 1024).", "-n", "--nOTs" ); opt.add( "128", // Default. 0, // Required? 1, // Number of args expected. 0, // Delimiter if expecting multiple args. "Number of base OTs to run (default: 128).", // Help description. "-b", // Flag token. "--nbase" // Flag token. ); opt.add( "s", 0, 1, 0, "Mode for OT. a (asymmetric) or s (symmetric, i.e. play both sender/receiver) (default: s).", "-m", "--mode" ); opt.add( "1", 0, 1, 0, "Number of threads (default: 1).", "-x", "--nthreads" ); opt.add( "1", 0, 1, 0, "Number of loops (default: 1).", "-l", "--nloops" ); opt.add( "1", 0, 1, 0, "Number of subloops (default: 1).", "-s", "--nsubloops" ); opt.add( "", // Default. 0, // Required? 0, // Number of args expected. 0, // Delimiter if expecting multiple args. "Run in passive security mode.", // Help description. "-pas", // Flag token. "--passive" // Flag token. ); opt.add( "", // Default. 0, // Required? 0, // Number of args expected. 0, // Delimiter if expecting multiple args. "Write results to files.", // Help description. "-o", // Flag token. "--output" // Flag token. ); opt.add( "", // Default. 0, // Required? 0, // Number of args expected. 0, // Delimiter if expecting multiple args. "Use fake base OTs.", // Help description. "-f", // Flag token. "--fake" // Flag token. ); opt.parse(argc, argv); string hostname, ot_mode, usage; int my_num, portnum_base, nthreads, nloops, nsubloops, nbase; long nOTs; bool passive = false; opt.get("-p")->getInt(my_num); opt.get("-pn")->getInt(portnum_base); opt.get("-h")->getString(hostname); opt.get("-n")->getLong(nOTs); opt.get("-m")->getString(ot_mode); opt.get("--nthreads")->getInt(nthreads); opt.get("--nloops")->getInt(nloops); opt.get("--nsubloops")->getInt(nsubloops); opt.get("--nbase")->getInt(nbase); if (opt.isSet("-pas")) passive = true; if (!opt.isSet("-p")) { opt.getUsage(usage); cout << usage; exit(0); } cout << "Player 0 host name = " << hostname << endl; cout << "Creating " << nOTs << " extended OTs in " << nthreads << " threads\n"; cout << "Running in mode " << ot_mode << endl; if (passive) cout << "Running with PASSIVE security only\n"; if (nbase < 128) cout << "WARNING: only using " << nbase << " seed OTs, using these for OT extensions is insecure.\n"; OT_ROLE ot_role; if (ot_mode.compare("s") == 0) ot_role = BOTH; else if (ot_mode.compare("a") == 0) { if (my_num == 0) ot_role = SENDER; else ot_role = RECEIVER; } else { cerr << "Invalid OT mode argument: " << ot_mode << endl; exit(1); } // PRG for generating inputs etc PRNG G; G.ReSeed(); // Several names for multiplexing vector<Names> N; unsigned int pos = 0; while (pos < hostname.length()) { string::size_type new_pos = hostname.find(',', pos); if (new_pos == string::npos) new_pos = hostname.length(); int len = new_pos - pos; string name = hostname.substr(pos, len); pos = new_pos + 1; vector<string> names(2); names[my_num] = "localhost"; names[1-my_num] = name; N.push_back(Names(my_num, portnum_base, names)); } TwoPartyPlayer* P = new TwoPartyPlayer(N[0], 1 - my_num, 500); timeval baseOTstart, baseOTend; gettimeofday(&baseOTstart, NULL); // swap role for base OTs BaseOT baseOT = BaseOT(nbase, 128, 1 - my_num, P, INV_ROLE(ot_role)); FakeOT fakeOT = FakeOT(nbase, 128, 1 - my_num, P, INV_ROLE(ot_role)); BaseOT* bot_; if (opt.isSet("-f")) { cout << "WARNING: using fake base OTs, not secure\n"; bot_ = &fakeOT; } else { cout << "Using Chou-Orlandi base OTs\n"; bot_ = &baseOT; } BaseOT& bot = *bot_; bot.exec_base(); gettimeofday(&baseOTend, NULL); double basetime = timeval_diff(&baseOTstart, &baseOTend); cout << "\t\tBaseTime (" << role_to_str(ot_role) << "): " << basetime/1000000 << endl << flush; // Receiver send something to force synchronization // (since Sender finishes baseOTs before Receiver) int a = 3; vector<octetStream> os(2); os[0].store(a); P->send_receive_player(os); os[1].get(a); cout << a << endl; #ifdef BASE_OT_DEBUG // check base OTs bot.check(); // check after extending with PRG a few times for (int i = 0; i < 8; i++) { bot.extend_length(); bot.check(); } cout << "Verifying base OTs (debugging)\n"; #endif // divide nOTs between threads and loops nOTs = DIV_CEIL(nOTs, nthreads * nloops); // round up to multiple of base OTs and subloops // discount for discarded OTs nOTs = DIV_CEIL(nOTs + 2 * 128, nbase * nsubloops) * nbase * nsubloops - 2 * 128; cout << "Running " << nOTs << " OT extensions per thread and loop\n" << flush; BitVector receiverInput(nOTs); receiverInput.randomize(G); // convert baseOT selection bits to BitVector // (not already BitVector due to legacy PVW code) BitVector baseReceiverInput(nbase); for (int i = 0; i < nbase; i++) { baseReceiverInput.set_bit(i, bot.receiver_inputs[i]); } cout << "Initialize OT Extension\n"; vector<OT_thread_info> tinfos(nthreads); vector<pthread_t> threads(nthreads); timeval OTextstart, OTextend; gettimeofday(&OTextstart, NULL); #ifndef __MACH__ timespec start, end; clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); #endif // copy base inputs/outputs for each thread vector<BitVector> base_receiver_input_copy(nthreads); vector<vector< vector<BitVector> > > base_sender_inputs_copy(nthreads, vector<vector<BitVector> >(nbase, vector<BitVector>(2))); vector< vector<BitVector> > base_receiver_outputs_copy(nthreads, vector<BitVector>(nbase)); vector<TwoPartyPlayer*> players(nthreads); for (int i = 0; i < nthreads; i++) { tinfos[i].receiverInput.assign(receiverInput); base_receiver_input_copy[i].assign(baseReceiverInput); for (int j = 0; j < nbase; j++) { base_sender_inputs_copy[i][j][0].assign(bot.sender_inputs[j][0]); base_sender_inputs_copy[i][j][1].assign(bot.sender_inputs[j][1]); base_receiver_outputs_copy[i][j].assign(bot.receiver_outputs[j]); } // now setup resources for each thread // round robin with the names players[i] = new TwoPartyPlayer(N[i%N.size()], 1 - my_num, (i+1) * 1000); tinfos[i].thread_num = i+1; tinfos[i].other_player_num = 1 - my_num; tinfos[i].nOTs = nOTs; tinfos[i].ot_ext = new OTExtensionWithMatrix(nbase, bot.length(), nloops, nsubloops, players[i], base_receiver_input_copy[i], base_sender_inputs_copy[i], base_receiver_outputs_copy[i], ot_role, passive); // create the thread pthread_create(&threads[i], NULL, run_otext_thread, &tinfos[i]); // extend base OTs with PRG for the next thread bot.extend_length(); } // wait for threads to finish for (int i = 0; i < nthreads; i++) { pthread_join(threads[i],NULL); cout << "thread " << i+1 << " finished\n" << flush; } map<string,long long>& times = tinfos[0].ot_ext->times; for (map<string,long long>::iterator it = times.begin(); it != times.end(); it++) { long long sum = 0; for (int i = 0; i < nthreads; i++) sum += tinfos[i].ot_ext->times[it->first]; cout << it->first << " on average took time " << double(sum) / nthreads / 1e6 << endl; } gettimeofday(&OTextend, NULL); #ifndef __MACH__ clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); cout << "Processor time: " << double(timespec_diff(&start, &end)) / 1e9 << endl; #endif double totaltime = timeval_diff(&OTextstart, &OTextend); cout << "Time for OTExt threads (" << role_to_str(ot_role) << "): " << totaltime/1000000 << endl << flush; if (opt.isSet("-o")) { char filename[1024]; sprintf(filename, RECEIVER_INPUT, my_num); ofstream outf(filename); receiverInput.output(outf, false); outf.close(); sprintf(filename, RECEIVER_OUTPUT, my_num); outf.open(filename); for (unsigned int i = 0; i < tinfos[0].ot_ext->receiverOutput.size(); i++) tinfos[0].ot_ext->receiverOutput[i].output(outf, false); outf.close(); for (int i = 0; i < 2; i++) { sprintf(filename, SENDER_OUTPUT, my_num, i); outf.open(filename); for (int j = 0; j < nOTs; j++) tinfos[0].ot_ext->senderOutput[i][j].output(outf, false); outf.close(); } } }
int main(){ int seed_value = 5; // An arbitrary seed value xor4096i(seed_value); // Seed the original number generator PRNG* rng = PRNGFactory::generatePRNG("xorgens"); // Seed the PRNGFactory number generator rng->set_type("int"); // Determine whether to produce integers or doubles rng->set(seed_value); // Set the seed value // Test that the generators produce the same values for 100 million iterations for(int i=0; i<5; i++){ unsigned long original_generator = xor4096i(0); unsigned long PRNGFactory_generator = rng->get_long(); std::cout << original_generator << " " << PRNGFactory_generator << "\n"; if(original_generator != PRNGFactory_generator){ std::cout << "The streams do not match\n"; exit(0); } } high_resolution_clock::time_point t1, t2; // Measure the time it takes the original generator to produce 1 billion values t1 = high_resolution_clock::now(); for(int i=0; i<500000000; i++){ unsigned long original_stream = xor4096i(0); } t2 = high_resolution_clock::now(); auto duration = duration_cast<microseconds>( t2 - t1 ).count(); std::cout << "Original xorgens generator used "<< duration/1000000.0 << " seconds to generate 500000000 values" << std::endl; // Measure the time it takes the original generator to produce 1 billion values t1 = high_resolution_clock::now(); for(int i=0; i<500000000; i++){ unsigned long PRNG_stream = rng->get_long(); } t2 = high_resolution_clock::now(); duration = duration_cast<microseconds>( t2 - t1 ).count(); std::cout << "PRNGFactory xorgens generator used "<< duration/1000000.0 << " seconds to generate 500000000 values" << std::endl; // print("Original xorgens generator:"); // // Seed integer number generator // xor4096i(5); // // Generator random long // print(xor4096i(0)); // // Seed real number generator // xor4096r(10); // // Generator random real number // print(xor4096r(0)); // print("PRNGFactory version:"); // // Allocate memory for a new xorgens RNG. // PRNG* rng = PRNGFactory::generatePRNG("xorgens"); // // Set type to generate longs // rng->set_type("int"); // rng->set(5); // print(rng->get_long()); // print(rng->get_long()); // PRNG* rng_i = PRNGFactory::generatePRNG("xorgens"); // // Set type to generate longs // rng_i->set_type("int"); // rng_i->set(5); // print(rng->get_long()); // print(rng_i->get_long()); // PRNG* rng_r = PRNGFactory::generatePRNG("xorgens"); // // Set type to generate longs // rng_r->set_type("real"); // rng_r->set(10); // print(rng_r->get_double()); return 0; }
int main(int ac, char **av) { using KBase::ReportingLevel; using KBase::PRNG; using KBase::MtchPstn; using KBase::dSeed; using RfrmPri::RPModel; using RfrmPri::RPState; using RfrmPri::RPActor; using RfrmPri::printPerm; auto sTime = KBase::displayProgramStart(RfrmPri::appName, RfrmPri::appVersion); uint64_t seed = dSeed; // arbitrary; bool siP = true; bool cpP = false; bool runP = true; unsigned int sNum = 1; bool xmlP = false; bool rp2P = false; string inputXML = ""; auto showHelp = [sNum]() { printf("\n"); printf("Usage: specify one or more of these options\n"); printf("\n"); printf("--cp start all actors from the central position \n"); printf("--rp2 create RP2 objects \n"); printf("--si start each actor from their most self-interested position \n"); printf(" If neither si nor cp are specified, it will use si. \n"); printf(" If both si and cp are specified, it will use second specified. \n"); printf("--help print this message and exit \n"); printf("--seed <n> set a 64bit seed \n"); printf(" 0 means truly random \n"); printf(" default: %020llu \n", dSeed); printf("--sNum <n> choose a scenario number \n"); printf(" default: %u \n", sNum); printf("--xml <f> read XML scenario from a given file \n"); printf("\n"); printf("For example, rpdemo --si --xml rpdata.xml, would read the file rpdata.xml \n"); printf("and start all actors from self-interested positions.\n"); printf("\n"); printf("If both scenario number and XML file are specified, it will use only the XML.\n"); printf("\n"); printf("If neither scenario number nor XML file are specified, \n"); printf("it will run a hard-coded example, as if --sNum 1 had been specified.\n"); printf("\n"); }; // a list of <keyword, description, λ-fn> // might be enough to do this - except for the arguments to options. if (ac > 1) { for (int i = 1; i < ac; i++) { if (strcmp(av[i], "--seed") == 0) { i++; seed = std::stoull(av[i]); } else if (strcmp(av[i], "--sNum") == 0) { i++; sNum = atoi(av[i]); } else if (strcmp(av[i], "--xml") == 0) { xmlP = true; i++; inputXML = av[i]; } else if (strcmp(av[i], "--rp2") == 0) { rp2P = true; } else if (strcmp(av[i], "--si") == 0) { cpP = false; siP = true; } else if (strcmp(av[i], "--cp") == 0) { siP = false; cpP = true; } else if (strcmp(av[i], "--help") == 0) { runP = false; } else { runP = false; printf("Unrecognized argument: %s\n", av[i]); } } } else { runP = false; } if (!runP) { showHelp(); return 0; } if (0 == seed) { PRNG * rng = new PRNG(); seed = rng->setSeed(0); // 0 == get a random number delete rng; rng = nullptr; } printf("Using PRNG seed: %020llu \n", seed); printf("Same seed in hex: 0x%016llX \n", seed); // Unix correctly prints all digits with lu, lX, llu, and llX. // Windows only prints part, with lu, lX, llu, and llX. if (rp2P) { RfrmPri2::rp2Creation(seed); return 0; } auto rpm = new RPModel("", seed); if (xmlP) { rpm->readXML(inputXML); cout << "done reading XML" << endl << flush; } else { switch (sNum) { case 0: rpm->initScen(sNum); break; case 1: rpm->initScen(sNum); break; default: cout << "Unrecognized scenario number " << sNum << endl << flush; assert(false); break; } } unsigned int numA = rpm->numAct; // the actors are as yet unnamed unsigned int numR = rpm->numItm; //unsigned int numC = rpm->numCat; auto rps0 = new RPState(rpm); rpm->addState(rps0); auto pstns = RfrmPri::scanPositions(rpm); KBase::VUI bestPerm = pstns[numA]; assert(numR == bestPerm.size()); // Either start them all at the CP or have each to choose an initial position which // maximizes their direct utility, regardless of expected utility. for (unsigned int i = 0; i < numA; i++) { auto pi = new MtchPstn(); pi->numCat = numR; pi->numItm = numR; if (cpP) { pi->match = bestPerm; } if (siP) { pi->match = pstns[i]; } rps0->addPstn(pi); } assert(numA == rps0->pstns.size()); rps0->step = [rps0]() { return rps0->stepSUSN(); }; unsigned int maxIter = 100; rpm->stop = [maxIter, rpm](unsigned int iter, const KBase::State * s) { bool doneP = iter > maxIter; if (doneP) { printf("Max iteration limit of %u exceeded \n", maxIter); } auto s2 = ((const RPState *)(rpm->history[iter])); for (unsigned int i = 0; i < iter; i++) { auto s1 = ((const RPState *)(rpm->history[i])); if (RPModel::equivStates(s1, s2)) { doneP = true; printf("State number %u matched state number %u \n", iter, i); } } return doneP; }; rps0->setUENdx(); rpm->run(); // we already displayed each state as it was processed, // so there is no need to show it again //rpm->showHist(); delete rpm; // and actors, and states rpm = nullptr; rps0 = nullptr; KBase::displayProgramEnd(sTime); return 0; }