void Accumulator::_checkBranchesTermination(Accumulator const& consequence , Accumulator const& alternative) { if (consequence._terminated() || alternative._terminated()) { warning::oneOrTwoBranchesTerminated(*consequence._term_pos_or_nul_if_not_term , *alternative._term_pos_or_nul_if_not_term); } }
int main() { Accumulator acc; acc.add(5); // add 5 to the accumulator reset(acc); // reset the accumulator to 0 cout << acc.m_value; return 0; }
void report(char const* name, long const repeats) { std::cout.precision(10); std::cout << name << ": "; for (int i = 0; i < (20-int(strlen(name))); ++i) std::cout << ' '; std::cout << std::fixed << test::measure<Accumulator>(repeats) << " [s] "; Accumulator acc; acc.benchmark(); std::cout << std::hex << "{checksum: " << acc.val << "}"; std::cout << std::flush << std::endl; }
/// Specialization of test that tests Real inline void test(const Real& A, const Real& B, Accumulator& Result) { const Real abs_A = fabs(A); const Real abs_B = fabs(B); const Real threshold = 10*std::numeric_limits<Real>::epsilon(); if(abs_A < threshold && abs_B < threshold) { Result.ulps(ceil(fabs(abs_B - abs_A) / threshold)); } else { Result.ulps(std::fabs(boost::math::float_distance(A, B))); } };
void Talk::cmd_load(mrs_string fname, mrs_natural lineSize) { cout << "cmd_load called" << endl; src_ = new SoundFileSource("src"); src_->updControl("mrs_string/filename", fname); fname_ = fname; src_->updControl("mrs_natural/inSamples", lineSize); AbsMax* absmax = new AbsMax("absmax"); Series *series = new Series("plot"); series->addMarSystem(src_); series->addMarSystem(absmax); mrs_natural hops = src_->getctrl("mrs_natural/size")->to<mrs_natural>() * src_->getctrl("mrs_natural/nChannels")->to<mrs_natural>() / src_->getctrl("mrs_natural/inSamples")->to<mrs_natural>() + 1; Accumulator* acc = new Accumulator("acc"); acc->updControl("mrs_natural/nTimes", hops); acc->addMarSystem(series); realvec in(acc->getctrl("mrs_natural/inObservations")->to<mrs_natural>(), acc->getctrl("mrs_natural/inSamples")->to<mrs_natural>()); realvec out(acc->getctrl("mrs_natural/onObservations")->to<mrs_natural>(), acc->getctrl("mrs_natural/onSamples")->to<mrs_natural>()); acc->process(in,out); out.send(communicator_); // Util util; // fname_ = fname; // src_ = util.sfopen(fname, MRS_SF_READ); // if (src_ == NULL) // cout << "src_ = NULL" << endl; // if (src_ != NULL) // File exists // { // src_->initWindow(lineSize, lineSize, 0, 0); // PlotExtractor pextractor(src_, src_->winSize()); // fvec res(src_->iterations()); // pextractor.extract(0, src_->iterations(), res); // res.send(communicator_); // } // else // { // fvec res(0); // res.send(communicator_); // } }
bool CoinSpend::Verify(const Accumulator& a, const SpendMetaData &m) const { // Verify both of the sub-proofs using the given meta-data struct timeval tv0, tv1; double elapsed; gettimeofday(&tv0, NULL); bool result_cPoK = commitmentPoK.Verify(serialCommitmentToCoinValue, accCommitmentToCoinValue); gettimeofday(&tv1, NULL); elapsed = (tv1.tv_sec - tv0.tv_sec) + (tv1.tv_usec - tv0.tv_usec) / 1e6; cout << "GNOSIS DEBUG: cPoK time: " << elapsed << endl; bool result_accPoK = accumulatorPoK.Verify(a, accCommitmentToCoinValue); tv0 = tv1; gettimeofday(&tv1, NULL); elapsed = (tv1.tv_sec - tv0.tv_sec) + (tv1.tv_usec - tv0.tv_usec) / 1e6; cout << "GNOSIS DEBUG: accPoK time: " << elapsed << endl; bool result_snSoK = serialNumberSoK.Verify(coinSerialNumber, serialCommitmentToCoinValue, signatureHash(m)); tv0 = tv1; gettimeofday(&tv1, NULL); elapsed = (tv1.tv_sec - tv0.tv_sec) + (tv1.tv_usec - tv0.tv_usec) / 1e6; cout << "GNOSIS DEBUG: snSoK time: " << elapsed << endl; return (a.getDenomination() == this->denomination) && result_cPoK && result_accPoK && result_snSoK; }
/** Verifies that a commitment c is accumulated in accumulator a */ bool AccumulatorProofOfKnowledge:: Verify(const Accumulator& a, const CBigNum& valueOfCommitmentToCoin) const { CBigNum sg = params->accumulatorPoKCommitmentGroup.g; CBigNum sh = params->accumulatorPoKCommitmentGroup.h; CBigNum g_n = params->accumulatorQRNCommitmentGroup.g; CBigNum h_n = params->accumulatorQRNCommitmentGroup.h; //According to the proof, this hash should be of length k_prime bits. It is currently greater than that, which should not be a problem, but we should check this. CHashWriter hasher(0,0); hasher << *params << sg << sh << g_n << h_n << valueOfCommitmentToCoin << C_e << C_u << C_r << st_1 << st_2 << st_3 << t_1 << t_2 << t_3 << t_4; CBigNum c = CBigNum(hasher.GetHash()); //this hash should be of length k_prime bits CBigNum st_1_prime = (valueOfCommitmentToCoin.pow_mod(c, params->accumulatorPoKCommitmentGroup.modulus) * sg.pow_mod(s_alpha, params->accumulatorPoKCommitmentGroup.modulus) * sh.pow_mod(s_phi, params->accumulatorPoKCommitmentGroup.modulus)) % params->accumulatorPoKCommitmentGroup.modulus; CBigNum st_2_prime = (sg.pow_mod(c, params->accumulatorPoKCommitmentGroup.modulus) * ((valueOfCommitmentToCoin * sg.inverse(params->accumulatorPoKCommitmentGroup.modulus)).pow_mod(s_gamma, params->accumulatorPoKCommitmentGroup.modulus)) * sh.pow_mod(s_psi, params->accumulatorPoKCommitmentGroup.modulus)) % params->accumulatorPoKCommitmentGroup.modulus; CBigNum st_3_prime = (sg.pow_mod(c, params->accumulatorPoKCommitmentGroup.modulus) * (sg * valueOfCommitmentToCoin).pow_mod(s_sigma, params->accumulatorPoKCommitmentGroup.modulus) * sh.pow_mod(s_xi, params->accumulatorPoKCommitmentGroup.modulus)) % params->accumulatorPoKCommitmentGroup.modulus; CBigNum t_1_prime = (C_r.pow_mod(c, params->accumulatorModulus) * h_n.pow_mod(s_zeta, params->accumulatorModulus) * g_n.pow_mod(s_epsilon, params->accumulatorModulus)) % params->accumulatorModulus; CBigNum t_2_prime = (C_e.pow_mod(c, params->accumulatorModulus) * h_n.pow_mod(s_eta, params->accumulatorModulus) * g_n.pow_mod(s_alpha, params->accumulatorModulus)) % params->accumulatorModulus; CBigNum t_3_prime = ((a.getValue()).pow_mod(c, params->accumulatorModulus) * C_u.pow_mod(s_alpha, params->accumulatorModulus) * ((h_n.inverse(params->accumulatorModulus)).pow_mod(s_beta, params->accumulatorModulus))) % params->accumulatorModulus; CBigNum t_4_prime = (C_r.pow_mod(s_alpha, params->accumulatorModulus) * ((h_n.inverse(params->accumulatorModulus)).pow_mod(s_delta, params->accumulatorModulus)) * ((g_n.inverse(params->accumulatorModulus)).pow_mod(s_beta, params->accumulatorModulus))) % params->accumulatorModulus; bool result_st1 = (st_1 == st_1_prime); bool result_st2 = (st_2 == st_2_prime); bool result_st3 = (st_3 == st_3_prime); bool result_t1 = (t_1 == t_1_prime); bool result_t2 = (t_2 == t_2_prime); bool result_t3 = (t_3 == t_3_prime); bool result_t4 = (t_4 == t_4_prime); bool result_range = ((s_alpha >= -(params->maxCoinValue * CBigNum(2).pow(params->k_prime + params->k_dprime + 1))) && (s_alpha <= (params->maxCoinValue * CBigNum(2).pow(params->k_prime + params->k_dprime + 1)))); return result_st1 && result_st2 && result_st3 && result_t1 && result_t2 && result_t3 && result_t4 && result_range; }
void range_test(IteratorT A, IteratorT LastA, IteratorT B, IteratorT LastB, Accumulator& Result) { for(; A != LastA && B != LastB; ++A, ++B) test(*A, *B, Result); Result.exact(A == LastA && B == LastB); };
int ReadHipTycFile(Accumulator &accu) { int count = 0; FILE *f; const char *fname = "HipTyc"; f = fopen(fname,"r"); if (f == 0) { fprintf(stderr,"Could not open file \"%s\".\n",fname); exit(-1); } int hip,tyc1,tyc2,tyc3; char cids[32]; char sp[256]; int mag,b_v,VarFlag; double ra,dec,Plx,pm_ra,pm_dec; while (14==fscanf(f,"%d%d%d%d%s%d%lf%lf%lf%lf%lf%d%d%s", &hip,&tyc1,&tyc2,&tyc3,cids,&VarFlag, &ra,&dec,&Plx,&pm_ra,&pm_dec,&mag,&b_v,sp)) { const int rc = accu.addStar(tyc1,tyc2,tyc3,hip, cids[0]=='?'?"":cids, ra, // degrees dec, // degrees pm_ra,pm_dec,0.001*mag,0.001*b_v, Plx,sp[0]=='?'?"":sp); if (rc < 0) { // never mind: propably no magnitude for Hiparcos star // fprintf(stderr,"File \"%s\", record %d: Error 13 %d %d \"%s\"\n", // fname,count,rc,hip,sp); // exit(-1); } count++; } fclose(f); return count; }
bool CoinSpend::Verify(const Accumulator& a) const { // Verify both of the sub-proofs using the given meta-data return (a.getDenomination() == this->denomination) && commitmentPoK.Verify(serialCommitmentToCoinValue, accCommitmentToCoinValue) && accumulatorPoK.Verify(a, accCommitmentToCoinValue) && serialNumberSoK.Verify(coinSerialNumber, serialCommitmentToCoinValue, signatureHash()); }
void vector_test(const Eigen::Matrix<Real, NbRows, NbCols>& A, const Eigen::Matrix<Real, NbRows, NbCols>& B, Accumulator& Result) { for(int i = 0, k = 0; i != A.rows() && k != B.rows(); ++i, ++k) for(int j = 0, l = 0; j != A.cols() && l != B.cols(); ++j, ++l) test(A(i, j), B(k, l), Result); Result.exact(A.rows() == B.rows() && A.cols() == B.cols()); };
void vector_test(const VectorT& A, const VectorT& B, Accumulator& Result) { const Uint sizeA = A.size(); const Uint sizeB = B.size(); for(Uint i = 0, j = 0; i != sizeA && j != sizeB; ++i, ++j) test(A[i], B[j], Result); Result.exact(sizeA == sizeB); };
int main() { Accumulator accumulator; accumulator.add(10); accumulator.add(20); accumulator.add(30); accumulator.add(40); accumulator.add(50); //Use function call operators cout << "Total is: " << accumulator() << endl; int total = 0; accumulator(&total); cout << "Total is: " << total << endl; return 0; }
//well defined rows checker void horizontal_alignment::check_rows(Accumulator &Accumulate_Issues, vector<widget> &Dialog_controllers) { int i = 0, j = 0; auto n = Dialog_controllers.size(); vector<widget> issue; // check all widgets for (i = 0; i < n; i++) { for (j = i + 1; j < n; j++) { // no issue if one widget is pushbutton named "..." if(!((Dialog_controllers[i].Get_type() == L"PUSHBUTTON") && (Dialog_controllers[i].Get_name() == L"..." || (Dialog_controllers[i].Get_bottom() - Dialog_controllers[i].Get_top() <= 10 || Dialog_controllers[i].Get_right() - Dialog_controllers[i].Get_left() <= 10)) || (Dialog_controllers[j].Get_type() == L"PUSHBUTTON" && (Dialog_controllers[j].Get_name() == L"..." || (Dialog_controllers[j].Get_bottom() - Dialog_controllers[j].Get_top() <= 10 || Dialog_controllers[j].Get_right() - Dialog_controllers[j].Get_left() <= 10))))) { if (Dialog_controllers[i].Get_deep() == Dialog_controllers[j].Get_deep()) // verif if widgets are on the same level { // verif if widgets are close if (if_close(&Dialog_controllers[i], &Dialog_controllers[j]) && if_same_size(&Dialog_controllers[i], &Dialog_controllers[j]) && !if_cross_line(&Dialog_controllers[i], &Dialog_controllers[j], Dialog_controllers)) { // check for wrong alignment bool valid = if_not_aligned(&Dialog_controllers[i], &Dialog_controllers[j]); if (valid == true) { // increase the nr of issues for this type nrissues_rows++; issue.push_back(Dialog_controllers[i]); issue.push_back(Dialog_controllers[j]); // create issue obj unique_ptr < Issue > pointer = make_unique < horizontal_alignment_issue >(issue); // push issue Accumulate_Issues.push_issue(move(pointer)); issue.clear(); } } } } } } }
void hammer(long const repeats) { // Strategy: because the sum in an accumulator after each call // depends on the previous value of the sum, the CPU's pipeline // might be stalled while waiting for the previous addition to // complete. Therefore, we allocate an array of accumulators, // and update them in sequence, so that there's no dependency // between adjacent addition operations. // // Additionally, if there were only one accumulator, the // compiler or CPU might decide to update the value in a // register rather that writing it back to memory. we want each // operation to at least update the L1 cache. *** Note: This // concern is specific to the particular application at which // we're targeting the test. *** // This has to be at least as large as the number of // simultaneous accumulations that can be executing in the // compiler pipeline. A safe number here is larger than the // machine's maximum pipeline depth. If you want to test the L2 // or L3 cache, or main memory, you can increase the size of // this array. 1024 is an upper limit on the pipeline depth of // current vector machines. const std::size_t number_of_accumulators = 1024; live_code = 0; // reset to zero Accumulator a[number_of_accumulators]; for (long iteration = 0; iteration < repeats; ++iteration) { for (Accumulator* ap = a; ap < a + number_of_accumulators; ++ap) { ap->benchmark(); } } // Accumulate all the partial sums to avoid dead code // elimination. for (Accumulator* ap = a; ap < a + number_of_accumulators; ++ap) { live_code += ap->val; } }
// accumulate statistics void DTAccumulator::accumulate(Alignment *alignment, MatrixBase<float> &mFeatures, bool bNumerator) { Accumulator *accumulator = NULL; double dOccupationTotal = 0.0; for(unsigned int t=0 ; t < alignment->getFrames() ; ++t) { FrameAlignment *frameAlignment = alignment->getFrameAlignment(t); VectorStatic<float> vFeatureVector = mFeatures.getRow(t); for(FrameAlignment::iterator it = frameAlignment->begin() ; it != frameAlignment->end() ; ++it) { double dOccupationNum = (*it)->dOccupation; HMMState *hmmState = m_hmmManager->getHMMState((*it)->iHMMState); // get Gaussian occupation from the mixture occupation // (1) compute the mixture likelihood (all Gaussian components) double dLikelihoodTotal = -DBL_MAX; int iGaussianComponents = hmmState->getMixture().getNumberComponents(); double *dLikelihoodGaussian = new double[iGaussianComponents]; for(int iGaussian = 0 ; iGaussian < iGaussianComponents ; ++iGaussian) { dLikelihoodGaussian[iGaussian] = hmmState->computeEmissionProbabilityGaussian(iGaussian, mFeatures.getRow(t).getData(),-1); dLikelihoodGaussian[iGaussian] += log(hmmState->getMixture()(iGaussian)->weight()); dLikelihoodTotal = Numeric::logAddition(dLikelihoodTotal,dLikelihoodGaussian[iGaussian]); } // (2) accumulate statistics for each mixture component for(int iGaussian = 0 ; iGaussian < iGaussianComponents ; ++iGaussian) { double dProbGaussian = exp(dLikelihoodGaussian[iGaussian]-dLikelihoodTotal); assert(dProbGaussian >= 0.0); double dOccupationGaussian = dOccupationNum*dProbGaussian; unsigned int iKey = Accumulator::getPhysicalAccumulatorKey(hmmState->getId(),iGaussian); if (bNumerator) { accumulator = m_mAccumulatorNum[iKey]; } else { accumulator = m_mAccumulatorDen[iKey]; } accumulator->accumulateObservation(vFeatureVector,dOccupationGaussian); dOccupationTotal += dOccupationGaussian; } delete [] dLikelihoodGaussian; } } printf("accumulated: %12.6f\n",dOccupationTotal); }
// estimate the parameters of the given HMM-state void MAPEstimator::estimateParameters(HMMState *hmmState, Accumulator **accumulators, float fPriorKnowledgeWeight) { // (1) update the mean of each Gaussian component for(unsigned int g = 0 ; g < hmmState->getMixture().getNumberComponents() ; ++g) { Gaussian *gaussian = hmmState->getMixture()(g); Accumulator *accumulator = accumulators[g]; // if there occupation for this component? if (accumulator == NULL) { continue; } // mean (needs to be computed first in the case of full covariance) gaussian->mean().mul(fPriorKnowledgeWeight); gaussian->mean().add(accumulator->getObservation()); gaussian->mean().mul((float)(1.0f/(fPriorKnowledgeWeight+accumulator->getOccupation()))); } assert(hmmState->getMixture().getNumberComponents() > 0); }
TEST_F(AccumulatorTest,Double) { double sum = 0; Accumulator<double> accumulator; double x = 1; int sign = 1; for (int i = 0; i < 24; ++i) { sum += x; accumulator += sign + x; x *= 0.01; sign *= -1; } EXPECT_TRUE(accumulator.sum() == accumulator); EXPECT_TRUE(accumulator == accumulator.sum()); EXPECT_FALSE(sum == accumulator.sum()); EXPECT_NEAR(sum, accumulator.sum(), 1E-6); }
int main(int argc,char *argv[]) { if (argc != 3 || 1 != sscanf(argv[1],"%d",&restrict_output_level_min) || 1 != sscanf(argv[2],"%d",&restrict_output_level_max)) { cerr << "Usage: " << argv[0] << " level_min level_max" << endl << " (like " << argv[0] << " 0 6)" << endl << endl; return -1; } Accumulator accu; int n=0; n = ReadHipTycFile(accu); printf("HipTyc: %d records processed.\n",n); SqueezeHip(); for (int c=0;nomad_names[c];c++) { ReadNOMADFile(nomad_names[c],accu); } accu.writeOutput(output_file_names); return 0; }
// main method void padding_first_layer::check_padding_first_layer(Accumulator & Accumulate_Issues) { Layer = create_Map(dialogElements); Mij_line = create_Map_for_Mij_line(dialogElements); for (auto &iter : Layer) { for (int i = 0; i < iter.second.size(); i++) { for (int j = i + 1; j < iter.second.size(); j++) { if (should_check(iter.second[i], iter.second[j])) { int expected = getExpectedVerticalDistance(getKey(iter.second[i]), getKey(iter.second[j])); int real = computeVerticalDistance(iter.second[i], iter.second[j]); if (expected > 0 && real > expected && (!is_on_white_list(iter.second[i], iter.second[j]))) { // decrese the output distance inbetween two controllers if ((iter.second[i].Is_checkbox() || iter.second[i].Is_radio_button()) &&( iter.second[j].Is_checkbox() || iter.second[j].Is_radio_button())) expected -= 2; nrissues_padding_vertically++; unique_ptr<Issue> pointer = make_unique< padding_issue_vertically >(iter.second[i], iter.second[j], expected - real); Accumulate_Issues.push_issue(move(pointer)); } } } } } }
// Simulate the tracing of a path with the accumulator void simulate(Accumulator &accum, const char **events, int testno) { accum.begin(); accum.pushState(); // for each ray stop in the path (see test cases) ... while (*events) { const char *e = *events; // for each label in this hit while (*e) { ustring sym(e, 1); // advance our state with the label accum.move(sym); e++; } // always finish the hit with a stop label accum.move(Labels::STOP); events++; } // Here is were we have reached a light, accumulate color accum.accum(Color3(1, 1, 1)); // Restore state and flush accum.popState(); accum.end((void *)(long int)testno); }
bool EXECUTE(int ret_inst) { cout << "\n\t At any time during the exection of the program, the following keywords can be used\n"; cout << "\t'rc' : To change the current register contents\n"; cout << "\t'rd' : To display the current register contents\n"; cout << "\t'md' : To display the current memory and register contents\n"; cout << "\t'mc' : To change the current execution mode\n"; cout << "\t'rc' : To change the current break point state \n"; cout << "\t'fp' : To print all the current flag contents\n"; string tmp = "" , mode = ""; char input[100];input[0]=0; cout << "\n Set the Execution Mode by pressing one of the following :\n"; cout << "\t'm' : execute Microinstruction by Microinstruction\n"; cout << "\t'i' : execute Instruction by Instruction\n"; cout << "\t'p' : execute entire program (default mode)\n"; strcpy(input,"p"); while (true) { cout << "\tExecution Mode : "; getchar(); scanf("%[^\n]",input); mode = input ; if (mode != "p" && mode !="m" && mode!="i") { cout << "Invalid Entry . Press (m/i/p) .\n"; continue ; } break; } cout << "\tPress 'bp' to set additional break-points besides (brk) in the program : "; getchar(); scanf("%[^\n]",input); tmp = input ; bool be = false ; if (tmp == "bp") { if (SetBreakPoints() == false ) return false ; } cout << "\tPress be/bd to enable/disable all break-points (default disable)\n"; string Microinstruction=""; int count_inst = -1; // Counter to count the number of instructions executed cout << "\n\tProgram Execution Begins .......\n\n"; while ( TRUE ) { /* This is the main loop. All modules are executed in this order. NOTICE */ ret_inst = MS.Sequencer(ret_inst , DC , FL); if (ret_inst == 0) count_inst++; Microinstruction = MPM.Fetch(ret_inst); PC.Operation(Microinstruction , DB); //Program Counter Module MR.Operation(Microinstruction,DB); //Memory Address Module Mem.Operation(Microinstruction,DB,MR); //Memory Address Module DC.Operation(Microinstruction,DB); //Decoder Module MS.Operation(Microinstruction,DC); //MicroSequencer Module IOR.Operation(Microinstruction,DB,RG,FL); //Instr. Oper. Register Module RG.Operation(Microinstruction,DB,PC,SP,AC,OP,ALU1); //Register File Module OP.Operation(Microinstruction,DB); //Operand Module AC.S_Operation(Microinstruction,DB); // Special Accumulator Operation (only to EAR) ALU1.Operation(Microinstruction,DB,OP,FL); //ALU Module AC.Operation(Microinstruction,DB,ALU1); //Accumulator Module SP.Operation(Microinstruction,DB); //Stack Module MR.Operation(Microinstruction,DB); //Memory Address Module Mem.Operation(Microinstruction,DB,MR); //Memory Address Module RG.Operation(Microinstruction,DB,PC,SP,AC,OP,ALU1); //Register File Module OP.Operation(Microinstruction,DB); //Operand Module PC.S_Operation(Microinstruction, DB); // Special PC Operation // FL.Operation(Microinstruction); //Flag Register Module (only to LPC) if (Microinstruction == "000000000000000000001000000000000000000000") break; clocks++; if (Print(mode,count_inst,ret_inst,Microinstruction , be) == false) return false; } return true; }
bool GenerateAccumulatorWitness( const PublicCoin &coin, Accumulator& accumulator, AccumulatorWitness& witness, int& nMintsAdded, string& strError, CBlockIndex* pindexCheckpoint) { try { // Lock LogPrint("zero", "%s: generating\n", __func__); if (!LockMethod()) return false; LogPrint("zero", "%s: after lock\n", __func__); int nHeightMintAdded = SearchMintHeightOf(coin.getValue()); //get the checkpoint added at the next multiple of 10 int nHeightCheckpoint = nHeightMintAdded + (10 - (nHeightMintAdded % 10)); //the height to start accumulating coins to add to witness int nAccStartHeight = nHeightMintAdded - (nHeightMintAdded % 10); //Get the accumulator that is right before the cluster of blocks containing our mint was added to the accumulator CBigNum bnAccValue = 0; if (GetAccumulatorValue(nHeightCheckpoint, coin.getDenomination(), bnAccValue)) { if(!bnAccValue && Params().NetworkID() == CBaseChainParams::REGTEST){ accumulator.setInitialValue(); witness.resetValue(accumulator, coin); }else { accumulator.setValue(bnAccValue); witness.resetValue(accumulator, coin); } } //add the pubcoins from the blockchain up to the next checksum starting from the block CBlockIndex *pindex = chainActive[nHeightCheckpoint - 10]; int nChainHeight = chainActive.Height(); int nHeightStop = nChainHeight % 10; nHeightStop = nChainHeight - nHeightStop - 20; // at least two checkpoints deep //If looking for a specific checkpoint if (pindexCheckpoint) nHeightStop = pindexCheckpoint->nHeight - 10; //Iterate through the chain and calculate the witness int nCheckpointsAdded = 0; nMintsAdded = 0; libzerocoin::Accumulator witnessAccumulator = accumulator; if(!calculateAccumulatedBlocksFor( nAccStartHeight, nHeightStop, nHeightMintAdded, pindex, nCheckpointsAdded, bnAccValue, accumulator, witnessAccumulator, coin, strError )){ return error("GenerateAccumulatorWitness(): Calculate accumulated coins failed"); } witness.resetValue(witnessAccumulator, coin); if (!witness.VerifyWitness(accumulator, coin)) return error("%s: failed to verify witness", __func__); // A certain amount of accumulated coins are required if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()) { strError = _(strprintf("Less than %d mints added, unable to create spend", Params().Zerocoin_RequiredAccumulation()).c_str()); return error("%s : %s", __func__, strError); } // calculate how many mints of this denomination existed in the accumulator we initialized nMintsAdded += ComputeAccumulatedCoins(nAccStartHeight, coin.getDenomination()); LogPrint("zero", "%s : %d mints added to witness\n", __func__, nMintsAdded); return true; // TODO: I know that could merge all of this exception but maybe it's not really good.. think if we should have a different treatment for each one } catch (searchMintHeightException e) { return error("%s: searchMintHeightException: %s", __func__, e.message); } catch (ChecksumInDbNotFoundException e) { return error("%s: ChecksumInDbNotFoundException: %s", __func__, e.message); } catch (GetPubcoinException e) { return error("%s: GetPubcoinException: %s", __func__, e.message); } }
int main() { // Some constants to avoid refering to AOV's by number const int beauty = 0; const int diffuse2_3 = 1; const int light3 = 2; const int object_1 = 3; const int specular = 4; const int diffuse = 5; const int transpshadow = 6; const int reflections = 7; const int nocaustic = 8; const int naovs = 9; // The actual test cases. Each one is a list of ray hits with some labels. // We use 1 char labels for convenience. They will be converted to ustrings // by simulate. And then a list of expected AOV's for each. TestPath test[] = { { { "C_", "TS", "TS", "RD", "L_", NULL }, { beauty, specular, nocaustic, END_AOV} }, { { "C_", "TS", "TS", "RD", "RG", "L_", NULL }, { END_AOV } }, { { "C_", "TS", "TS", "RD", "RD", "L_", NULL }, { beauty, specular, diffuse2_3, nocaustic, END_AOV } }, { { "C_", "RG", "RD", "RG", "RD", "RG", "RD", "L_", NULL }, { END_AOV } }, { { "C_", "RG", "RD", "RG", "RD", "L_", NULL }, { nocaustic, END_AOV } }, { { "C_", "RD", "RD", "L_", NULL }, { beauty, diffuse, diffuse2_3, nocaustic, END_AOV } }, { { "C_", "RD", "RS", "RD", "L_", NULL }, { nocaustic, END_AOV } }, { { "C_", "RD", "Ts", "L_", NULL }, { transpshadow, END_AOV } }, { { "C_", "TS", "TS", "RD", "L_3", NULL }, { beauty, specular, light3, nocaustic, END_AOV } }, { { "C_", "RD1", "RD", "L_", NULL }, { beauty, diffuse, diffuse2_3, object_1, nocaustic, END_AOV } }, { { "C_", "RS", "RD", "RG", "L_", NULL }, { END_AOV } }, { { "C_", "RS", "RD", "L_", NULL }, { beauty, specular, reflections, nocaustic, END_AOV } }, { { NULL }, { END_AOV } } }; // Create our fake testing AOV's std::vector<MyAov> aovs; for (int i = 0; i < naovs; ++i) aovs.push_back (MyAov (test, i)); // Create the automata and add the rules AccumAutomata automata; ASSERT(automata.addRule("C[SG]*D*L", beauty)); ASSERT(automata.addRule("C[SG]*D{2,3}L", diffuse2_3)); ASSERT(automata.addRule("C[SG]*D*<L.'3'>", light3)); ASSERT(automata.addRule("C[SG]*<.D'1'>D*L", object_1)); ASSERT(automata.addRule("C<.[SG]>+D*L", specular)); ASSERT(automata.addRule("CD+L", diffuse)); ASSERT(automata.addRule("CD+<Ts>L", transpshadow)); ASSERT(automata.addRule("C<R[^D]>+D*L", reflections)); ASSERT(automata.addRule("C([SG]*D){1,2}L", nocaustic)); automata.compile(); // now create the accumulator Accumulator accum (&automata); // and set the AOV's for each id (beauty, diffuse2_3, etc ...) for (int i = 0; i < naovs; ++i) accum.setAov(i, &aovs[i], false, false); // do the simulation for each test case for (int i = 0; test[i].path[0]; ++i) simulate(accum, test[i].path, i); // And check. We unroll this loop for boost to give us a useful // error in case they fail ASSERT(aovs[beauty ].check()); ASSERT(aovs[diffuse2_3 ].check()); ASSERT(aovs[light3 ].check()); ASSERT(aovs[object_1 ].check()); ASSERT(aovs[specular ].check()); ASSERT(aovs[diffuse ].check()); ASSERT(aovs[transpshadow].check()); ASSERT(aovs[reflections ].check()); ASSERT(aovs[nocaustic ].check()); std::cout << "Light expressions check OK" << std::endl; }
void ReadNOMADFile(const char *fname,Accumulator &accu) { int count; FILE *f; f = fopen(fname,"r"); if (f == 0) { fprintf(stderr,"Could not open file \"%s\".\n",fname); exit(-1); } int total = 0; do { count = fread(buff,sizeof(Short_NOMAD_Record),READ_SIZE,f); total += count; printf("\rfread(%s,...) returned %6d, total = %8d", fname,count,total); fflush(stdout); int i; for (i=0;i<count;i++) { int mag = 30000; int b_v; if (buff[i].v >= 30000) { if (buff[i].b >= 30000) { if (buff[i].r >= 30000) { // cerr << "no magnitude at all" << endl; } else { mag = buff[i].r + 3499; // just an assumption b_v = 3499; } } else { mag = buff[i].b + 500; // just an assumption b_v = -500; } } else { mag = buff[i].v; if (buff[i].b >= 30000) { if (buff[i].r >= 30000) { b_v = 0; } else { b_v = buff[i].v-buff[i].r; // desperate } } else { b_v = buff[i].b-buff[i].v; } } int nr_of_measurements = 0; if (buff[i].b < 30000) nr_of_measurements++; if (buff[i].v < 30000) nr_of_measurements++; if (buff[i].r < 30000) nr_of_measurements++; if (mag < 19500 && ((buff[i].flags&SHORT_USEME) || ( ((buff[i].flags&(SHORT_ASTSRCBIT0|SHORT_ASTSRCBIT1|SHORT_ASTSRCBIT2))!=1 || (((buff[i].flags&SHORT_UBBIT)==0) && (mag>14000 || nr_of_measurements>1) && (mag>13000 || nr_of_measurements>2) )) && ((buff[i].flags&SHORT_SPIKE)==0) && ((buff[i].flags&SHORT_BSART)==0) && ((buff[i].flags&SHORT_TMONLY)==0)))) { if (accu.addStar(0,0,0,0,"", buff[i].ra/(3600.0*1000.0), // degrees (buff[i].spd-90*3600*1000)/(3600.0*1000.0), // degrees 0.1*buff[i].pm_ra,0.1*buff[i].pm_spd, 0.001*mag,0.001*b_v, 0,"") < 0) { fprintf(stderr,"File \"%s\", record %d: Error 16\n",fname,count); exit(-1); } } } } while (count == READ_SIZE); printf("\n"); fclose(f); }
bool GenerateAccumulatorWitness(const PublicCoin &coin, Accumulator& accumulator, AccumulatorWitness& witness, int nSecurityLevel, int& nMintsAdded, string& strError) { uint256 txid; if (!zerocoinDB->ReadCoinMint(coin.getValue(), txid)) { LogPrint("zero","%s failed to read mint from db\n", __func__); return false; } CTransaction txMinted; uint256 hashBlock; if (!GetTransaction(txid, txMinted, hashBlock)) { LogPrint("zero","%s failed to read tx\n", __func__); return false; } int nHeightMintAdded= mapBlockIndex[hashBlock]->nHeight; uint256 nCheckpointBeforeMint = 0; CBlockIndex* pindex = chainActive[nHeightMintAdded]; int nChanges = 0; //find the checksum when this was added to the accumulator officially, which will be two checksum changes later //reminder that checksums are generated when the block height is a multiple of 10 while (pindex->nHeight < chainActive.Tip()->nHeight - 1) { if (pindex->nHeight == nHeightMintAdded) { pindex = chainActive[pindex->nHeight + 1]; continue; } //check if the next checksum was generated if (pindex->nHeight % 10 == 0) { nChanges++; if (nChanges == 1) { nCheckpointBeforeMint = pindex->nAccumulatorCheckpoint; break; } } pindex = chainActive.Next(pindex); } //the height to start accumulating coins to add to witness int nAccStartHeight = nHeightMintAdded - (nHeightMintAdded % 10); //If the checkpoint is from the recalculated checkpoint period, then adjust it int nHeight_LastGoodCheckpoint = Params().Zerocoin_Block_LastGoodCheckpoint(); int nHeight_Recalculate = Params().Zerocoin_Block_RecalculateAccumulators(); if (pindex->nHeight < nHeight_Recalculate - 10 && pindex->nHeight > nHeight_LastGoodCheckpoint) { //The checkpoint before the mint will be the last good checkpoint nCheckpointBeforeMint = chainActive[nHeight_LastGoodCheckpoint]->nAccumulatorCheckpoint; nAccStartHeight = nHeight_LastGoodCheckpoint - 10; } //Get the accumulator that is right before the cluster of blocks containing our mint was added to the accumulator CBigNum bnAccValue = 0; if (GetAccumulatorValueFromDB(nCheckpointBeforeMint, coin.getDenomination(), bnAccValue)) { if (bnAccValue > 0) { accumulator.setValue(bnAccValue); witness.resetValue(accumulator, coin); } } //security level: this is an important prevention of tracing the coins via timing. Security level represents how many checkpoints //of accumulated coins are added *beyond* the checkpoint that the mint being spent was added too. If each spend added the exact same //amounts of checkpoints after the mint was accumulated, then you could know the range of blocks that the mint originated from. if (nSecurityLevel < 100) { //add some randomness to the user's selection so that it is not always the same nSecurityLevel += CBigNum::randBignum(10).getint(); //security level 100 represents adding all available coins that have been accumulated - user did not select this if (nSecurityLevel >= 100) nSecurityLevel = 99; } //add the pubcoins (zerocoinmints that have been published to the chain) up to the next checksum starting from the block pindex = chainActive[nAccStartHeight]; int nChainHeight = chainActive.Height(); int nHeightStop = nChainHeight % 10; nHeightStop = nChainHeight - nHeightStop - 20; // at least two checkpoints deep int nCheckpointsAdded = 0; nMintsAdded = 0; while (pindex->nHeight < nHeightStop + 1) { if (pindex->nHeight != nAccStartHeight && pindex->pprev->nAccumulatorCheckpoint != pindex->nAccumulatorCheckpoint) ++nCheckpointsAdded; //if a new checkpoint was generated on this block, and we have added the specified amount of checkpointed accumulators, //then initialize the accumulator at this point and break if (!InvalidCheckpointRange(pindex->nHeight) && (pindex->nHeight >= nHeightStop || (nSecurityLevel != 100 && nCheckpointsAdded >= nSecurityLevel))) { uint32_t nChecksum = ParseChecksum(chainActive[pindex->nHeight + 10]->nAccumulatorCheckpoint, coin.getDenomination()); CBigNum bnAccValue = 0; if (!zerocoinDB->ReadAccumulatorValue(nChecksum, bnAccValue)) { LogPrintf("%s : failed to find checksum in database for accumulator\n", __func__); return false; } accumulator.setValue(bnAccValue); break; } // if this block contains mints of the denomination that is being spent, then add them to the witness if (pindex->MintedDenomination(coin.getDenomination())) { //grab mints from this block CBlock block; if(!ReadBlockFromDisk(block, pindex)) { LogPrintf("%s: failed to read block from disk while adding pubcoins to witness\n", __func__); return false; } list<PublicCoin> listPubcoins; if(!BlockToPubcoinList(block, listPubcoins, true)) { LogPrintf("%s: failed to get zerocoin mintlist from block %n\n", __func__, pindex->nHeight); return false; } //add the mints to the witness for (const PublicCoin pubcoin : listPubcoins) { if (pubcoin.getDenomination() != coin.getDenomination()) continue; if (pindex->nHeight == nHeightMintAdded && pubcoin.getValue() == coin.getValue()) continue; witness.addRawValue(pubcoin.getValue()); ++nMintsAdded; } } pindex = chainActive[pindex->nHeight + 1]; } if (nMintsAdded < Params().Zerocoin_RequiredAccumulation()) { strError = _(strprintf("Less than %d mints added, unable to create spend", Params().Zerocoin_RequiredAccumulation()).c_str()); LogPrintf("%s : %s\n", __func__, strError); return false; } // calculate how many mints of this denomination existed in the accumulator we initialized int nZerocoinStartHeight = GetZerocoinStartHeight(); pindex = chainActive[nZerocoinStartHeight]; while (pindex->nHeight < nAccStartHeight) { nMintsAdded += count(pindex->vMintDenominationsInBlock.begin(), pindex->vMintDenominationsInBlock.end(), coin.getDenomination()); pindex = chainActive[pindex->nHeight + 1]; } LogPrint("zero","%s : %d mints added to witness\n", __func__, nMintsAdded); return true; }
/// Specialization of test that tests Uint inline void test(const Uint& A, const Uint& B, Accumulator& Result) { Result.exact(A == B); };
bool CalculateAccumulatorWitnessFor( const ZerocoinParams* params, int startHeight, int maxCalulationRange, CoinDenomination den, const CBloomFilter& filter, Accumulator& accumulator, AccumulatorWitness& witness, int& nMintsAdded, string& strError, list<CBigNum>& ret, int &heightStop ){ // Lock if (!LockMethod()) return false; try { // Dummy coin init PublicCoin temp(params, 0, den); // Dummy Acc init Accumulator testingAcc(params, den); //get the checkpoint added at the next multiple of 10 int nHeightCheckpoint = startHeight + (10 - (startHeight % 10)); // Get the base accumulator // TODO: This needs to be changed to the partial witness calculation on the next version. CBigNum bnAccValue = 0; if (GetAccumulatorValue(nHeightCheckpoint, den, bnAccValue)) { accumulator.setValue(bnAccValue); witness.resetValue(accumulator, temp); } // Add the pubcoins from the blockchain up to the next checksum starting from the block CBlockIndex *pindex = chainActive[nHeightCheckpoint -10]; int nChainHeight = chainActive.Height(); int nHeightStop = nChainHeight % 10; nHeightStop = nChainHeight - nHeightStop - 20; // at least two checkpoints deep if (nHeightStop - startHeight > maxCalulationRange) { int stop = (startHeight + maxCalulationRange); int nHeightStop = stop % 10; nHeightStop = stop - nHeightStop - 20; } heightStop = nHeightStop; nMintsAdded = 0; // Starts on top of the witness that the node sent libzerocoin::Accumulator witnessAccumulator(params, den, witness.getValue()); if(!calculateAccumulatedBlocksFor( startHeight, nHeightStop, pindex, bnAccValue, accumulator, den, filter, witnessAccumulator, ret, strError )) return error("CalculateAccumulatorWitnessFor(): Calculate accumulated coins failed"); // reset the value witness.resetValue(witnessAccumulator, temp); // calculate how many mints of this denomination existed in the accumulator we initialized nMintsAdded += ComputeAccumulatedCoins(startHeight, den); LogPrint("zero", "%s : %d mints added to witness\n", __func__, nMintsAdded); return true; } catch (ChecksumInDbNotFoundException e) { return error("%s: ChecksumInDbNotFoundException: %s", __func__, e.message); } catch (GetPubcoinException e) { return error("%s: GetPubcoinException: %s", __func__, e.message); } }
void Operation(string inst , Databus & DB,ProgramCounter & PC,Stack & St,Accumulator & AC,OperandRegister & Op, ALU & ALU1) { string oper=""; if (inst[ERG]=='1') { if (inst[MRG] == '0') { oper = snoop; } else { oper = inst.substr(SRG,4); } if (oper == "1100") { PC.Epc(DB); } else if (oper == "1101") { St.Esp(DB); } else if (oper == "1110") { AC.Ear(DB); } else if (oper == "1111") { Op.Eor(DB); } else strcpy(DB.DATA,value_of_register[oper].c_str()); } if (inst[LRG] == '1') { if (inst[MRG]=='0') { oper=snoop; } else { oper = inst.substr(SRG,4); } if (oper == "1100") { PC.Lpc(DB); } else if (oper == "1101") { St.Lsp(DB); } else if (oper == "1110") { AC.Lar(ALU1); } else if (oper == "1111") { Op.Lor(DB); } else { value_of_register[oper]=DB.DATA; } } return ; }