FESetupMessage* FEInitiator::setup(const string &signAlg) { #ifdef TIMER startTimer(); #endif // generate signature key if (signKey == NULL) signKey = Signature::Key::generateKey(signAlg); #ifdef TIMER printTimer("Signature key generation"); #endif #ifdef TIMER startTimer(); #endif // set up prover for forming escrow VEProver prover(verifiablePK); ZZ eCom = coin.getEndorsementCom(); // the label needs to be the public key for the signature scheme // create the verifiable escrow VECiphertext* escrow = new VECiphertext(prover.verifiableEncrypt(eCom, endorsement, coin.getCashGroup(), signKey->publicKeyString(), verifiablePK->hashAlg, stat)); #ifdef TIMER printTimer("Verifiable escrow generation"); #endif return new FESetupMessage(coin, escrow, *signKey); }
bool prove(const string& fname) { BOOST_TEST_MESSAGE( "## Running proof test for " << fname ); startTimer(); prover.check(ZKP_DIR + fname); // throws compilation errs printTimer("prover.check"); startTimer(); prover.compute(env.groups, env.variables); printTimer("prover.compute"); startTimer(); SigmaProof proof = prover.computeProof(); printTimer("prover.computeProof"); verifier.check(ZKP_DIR + fname); // need to get the right inputs for verifier variable_map publics = prover.getPublicVariables(); startTimer(); verifier.compute(env.groups, publics); printTimer("verifier.compute"); startTimer(); bool ok = verifier.verifyProof(proof); printTimer("verifier.verifyProof"); return ok; }
ProofMessage* CLBlindIssuer::getPartialSignature(const ZZ &C, const vector<ZZ>& publics, const ProofMessage &pm, int stat, const hashalg_t &hashAlg) { // at this point, verifier will know which program it is working with variable_map proverPublics = pm.proof.getCommitments(); variable_map pv = pm.publics; verifier.compute(v, proverPublics, pv); SigmaProof proof = pm.proof; startTimer(); bool verified = verifier.verify(proof, stat); printTimer("[CLBlindIssuer] verified recipient proof"); if(verified){ // XXX: should we be checking that public values are in the // proper range? same goes for recipient side of things too... if((int)publics.size() != numPublics) throw CashException(CashException::CE_SIZE_ERROR, "[CLBlindIssuer::getPartialSignature] Number of public inputs " "does not match the number the issuer was constructed with"); startTimer(); InterpreterProver prover; prover.check("ZKP/examples/cl-issue.txt", inputs, g); // want to keep the same inputs and groups, but need a new variable // map for doing issue program ZZ lx = v.at("l_x"); v.clear(); const GroupRSA* grp = (GroupRSA*) g.at("pkGroup"); v["l_x"] = lx; v["stat"] = grp->getStat(); v["modSize"] = grp->getModulusLength(); v["C"] = C; for(unsigned i = 0; i < publics.size(); i++) v["x_"+lexical_cast<string>(i+numPrivates+1)] = publics[i]; prover.compute(v); // set up partial signature to include in message for recipient variable_map partialSig; variable_map pVars = prover.getEnvironment().variables; partialSig["A"] = pVars.at("A"); partialSig["e"] = pVars.at("e"); partialSig["vdoubleprime"] = pVars.at("vdoubleprime"); variable_map p = prover.getPublicVariables(); SigmaProof pr = prover.computeProof(hashAlg); printTimer("[CLBlindIssuer] computed issuer proof"); return new ProofMessage(partialSig, p, pr); } else { throw CashException(CashException::CE_PARSE_ERROR, "[CLBlindIssuer::getPartialSignature] Proof did not verify"); } }
BuyMessage* Buyer::buy(Wallet* wallet, const vector<EncBuffer*>& ctext, const vector<hash_t>& ptHash, const ZZ &R) { startTimer(); makeCoin(*wallet, R); printTimer("[Buyer::buy] created coin"); return buy(ctext, ptHash); }
ProofMessage* CLBlindRecipient::getC(const vector<SecretValue>& privates, const hashalg_t &hashAlg) { if((int)privates.size() != numPrivates) throw CashException(CashException::CE_SIZE_ERROR, "[CLBlindRecipient::getC] Number of private inputs does not match " "the number the recipient was constructed with"); // add the private messages to the variable map, as well as the // randomness used to form their commitments for(unsigned i = 0; i < privates.size(); i++){ string index = lexical_cast<string>(i+1); v["x_"+index] = privates[i].first; v["r_"+index] = privates[i].second; } // XXX: what about public messages? startTimer(); prover.compute(v); variable_map publics = prover.getPublicVariables(); SigmaProof proof = prover.computeProof(hashAlg); printTimer("[CLBlindRecipient] created proof"); variable_map vals; variable_map pVars = prover.getEnvironment().variables; vals["C"] = pVars.at("C"); vals["vprime"] = pVars.at("vprime"); return new ProofMessage(vals, publics, proof); }
VECiphertext VEProver::verifiableEncrypt(const ZZ &commitment, const vector<ZZ> &opening, const Group* grp, const string &label, const hashalg_t &hashAlg, int stat) { // if we run encrypt, environment will have most of the information we need vector<ZZ> ciphertext = encrypt(opening, label, hashAlg, stat); // now need some more group information env.groups["cashGroup"] = grp; const GroupRSA* second = new GroupRSA(pk->getSecondGroup()); env.groups["secondGroup"] = second; env.variables["X"] = commitment; // again want to bind m, right? input_map inputs; inputs["m"] = opening.size(); InterpreterProver prover; prover.check("ZKP/examples/ve.txt", inputs, env.groups); startTimer(); prover.compute(env.variables); printTimer("Computed values for verifiable encryption"); startTimer(); SigmaProof proof = prover.computeProof(hashAlg); printTimer("Computed proof for verifiable encryption"); Environment e = prover.getEnvironment(); variable_map publics = prover.getPublicVariables(); // can take a lot of stuff out of this map before giving to verifier publics.erase("b"); publics.erase("d"); publics.erase("e"); publics.erase("f"); for (unsigned i = 0; i < opening.size(); i++) { publics.erase("a_"+lexical_cast<string>(i+1)); } publics.erase("X"); publics.erase("Xprime"); // XXX: there is repetition between ciphertext and publics, but having // squared values in publics saves the verifier from doing some // computation... is that worth it? VECiphertext result(ciphertext, e.variables.at("Xprime"), publics, proof); return result; }
int main() { int i,k,n; char *text; unsigned char *trans; FILE *f; initTimer(); // Open file f = fopen("/tmp/dbtss", "r"); if(f == 0) { printf("File not found.\n"); return 0; } // Obtain file size. fseek (f, 0 , SEEK_END); n = ftell (f); rewind (f); printf("File size: %d\n", n); text = malloc(sizeof(char)*(n)); k = fread(text, 1, n, f); printf("Read size: %d\n", k); fclose(f); addTimer("End reading"); // Translate trans = malloc(sizeof(char)*(n+50)); translate(trans, text, n, "ACGT|"); addTimer("End translating"); free(text); // Initialize tail for(i=n; i<n+50; i++) trans[i]=5; addTimer("End initialize tail"); // Sort int *result = malloc(sizeof(int)*n); count_radix(trans, result, n, 5); addTimer("End sorting"); printTimer(); freeTimer(); // for(i=0; i<n; i++){ // for(k=0; k<3; k++) // printf("%i", trans[result[i]+k]); // printf("\n"); // } return 0; }
int main(int argc, char** argv) { Timer totalTime; int matrixSize; int mat1[SIZE][SIZE], mat2[SIZE][SIZE], prod[SIZE][SIZE]; int i, j; // Check argument size if (argc < 2) { printf("You should give the matrix size as argument.\n"); return -1; } // Check matrix size matrixSize = atoi(argv[1]); if (matrixSize < 1 || matrixSize > 100) { printf("Matrix should be between 1 and 100.\n"); return -1; } // Init timer initTimer(&totalTime, "Total Time"); // Init matrices for (i = 0;i < matrixSize; i++) { for (j = 0; j < matrixSize; j++) { mat1[i][j] = i+j*2; } } for(i = 0; i < matrixSize; i++) { for (j = 0; j < matrixSize; j++) { mat2[i][j] = i+j*3; } } startTimer(&totalTime); matMult(mat1, mat2, prod, matrixSize); stopTimer(&totalTime); for (i = 0;i < matrixSize; i++) { printf("\n"); for (j = 0; j < matrixSize; j++) { printf("\t%d ", prod[i][j]); } } printf("\n\n"); printTimer(&totalTime); printf("Done !!! \n"); return 0; }
BuyMessage* Buyer::buy(const vector<EncBuffer*>& ct, const vector<hash_t>& ptHash) { if (inProgress) throw CashException(CashException::CE_FE_ERROR, "[Buyer::buy] Buy called on an already working buyer"); if (ct.empty()) throw CashException(CashException::CE_FE_ERROR, "[Buyer::buy] No ciphertext given"); if (ptHash.empty()) throw CashException(CashException::CE_FE_ERROR, "[Buyer::buy] No plaintext hash given"); // store ciphertexts ctext = ct; // compute hashes // XXX temporary fix: use regular hashes (size-1 hashes aren't matching) startTimer(); hash_t ptHashMerkle = Hash::hash(ptHash, pk->hashAlg, pk->hashKey, Hash::TYPE_MERKLE); hash_t ctHashMerkle = Hash::hash(ctext, pk->hashAlg, pk->hashKey, Hash::TYPE_MERKLE); // create contract createContract(); // set up the contract contract->setPTHashB(ptHashMerkle); contract->setCTHashB(ctHashMerkle); contract->setEncAlgB(ctext[0]->encAlg); contract->setPTHashBlocksB(ptHash.size()); contract->setCTHashBlocksB(ctext.size()); printTimer("[Buyer::buy] created contract"); startTimer(); // set up the escrow VECiphertext* escrow = new VECiphertext(makeEscrow()); printTimer("[Buyer::buy] created escrow"); // set inProgress inProgress = true; return new BuyMessage(coin, contract, escrow); }
void printTimerList(OutputStream* outputStream, TimerList* timerList) { int i; for (i = 0; i < timerList->size; i++) { Timer* timer = (Timer*) timerList->timers; timer += i; appendCRLF(outputStream); printTimer(outputStream, timer); } }
void FEInitiator::makeCoin(Wallet* wallet, const ZZ& R) { // get a coin #ifdef TIMER startTimer(); #endif Coin coin = wallet->nextCoin(R); #ifdef TIMER printTimer("Coin generation"); #endif setCoin(coin); }
bool CLBlindRecipient::verifySig(const ProofMessage &pm, int stat){ startTimer(); InterpreterVerifier verifier; verifier.check("ZKP/examples/cl-issue.txt", inputs); // XXX: does the verifier really not need any inputs of its own? // this would be a good place to incorporate public messages... variable_map q; variable_map pubs = pm.publics; verifier.compute(q, pubs, g); bool verified = verifier.verify(pm.proof, stat); printTimer("[CLBlindRecipient] verified issuer proof"); return verified; }
int main(int argc, char** argv) { int i, j; Timer neonTime; int16_t *mat1, *mat2; int32_t prod[sizeof(int32_t)*matrix_size][sizeof(int32_t)*matrix_size]; /* Get argument size */ matrix_size = atoi(argv[1]); if(matrix_size < 0 || matrix_size > 512) { printf("Matrix size must be between 0 and 512.\n"); return -1; } /* Initialize timer */ initTimer(&neonTime, "NEON Time"); /* Allocate matrices */ mat1 = malloc(matrix_size * matrix_size * sizeof(int16_t)); mat2 = malloc(matrix_size * matrix_size * sizeof(int16_t)); if (mat1 == NULL || mat2 == NULL) { printf("Out of memory\n"); } /* Initialize matrices */ for (i = 0; i < matrix_size; i++) { for (j = 0; j < matrix_size; j++) { mat1[i*matrix_size + j] = i+j*2; } } for(i = 0; i < matrix_size; i++) { for (j = 0; j < matrix_size; j++) { mat2[i*matrix_size + j] = i+j*3; } } /* Run the multiplication */ startTimer(&neonTime); matMult(mat1,mat2,prod); stopTimer(&neonTime); printTimer(&neonTime); /* for (i = 0;i < matrix_size; i++) { printf("\n"); for (j = 0; j < matrix_size; j++) { printf("\t%d ", prod[i][j]); } } printf("\nDone !!! \n"); } */ return 0; }
int NDBT_TestCase::execute(NDBT_Context* ctx) { char buf[64]; // For timestamp string ndbout << "- " << _name << " started [" << ctx->suite->getDate(buf, sizeof(buf)) << "]" << endl; ctx->setCase(this); // Copy test case properties to ctx Properties::Iterator it(&props); for(const char * key = it.first(); key != 0; key = it.next()){ PropertiesType pt; const bool b = props.getTypeOf(key, &pt); require(b == true); switch(pt){ case PropertiesType_Uint32:{ Uint32 val; props.get(key, &val); ctx->setProperty(key, val); break; } case PropertiesType_char:{ const char * val; props.get(key, &val); ctx->setProperty(key, val); break; } default: abort(); } } // start timer so that we get a time even if // test case consist only of initializer startTimer(ctx); int res; if ((res = runInit(ctx)) == NDBT_OK){ // If initialiser is ok, run steps res = runSteps(ctx); if (res == NDBT_OK){ // If steps is ok, run verifier res = runVerifier(ctx); } } stopTimer(ctx); printTimer(ctx); // Always run finalizer to clean up db runFinal(ctx); if (res == NDBT_OK) { ndbout << "- " << _name << " PASSED [" << ctx->suite->getDate(buf, sizeof(buf)) << "]" << endl; } else { ndbout << "- " << _name << " FAILED [" << ctx->suite->getDate(buf, sizeof(buf)) << "]" << endl; } return res; }
/******************************************************************************* * PROCEDURE: canny * PURPOSE: To perform canny edge detection. * NAME: Mike Heath * DATE: 2/15/96 *******************************************************************************/ void canny(unsigned char *image, int rows, int cols, float sigma, float tlow, float thigh, unsigned char **edge, char *fname) { FILE *fpdir=NULL; /* File to write the gradient image to. */ unsigned char *nms; /* Points that are local maximal magnitude. */ short int *smoothedim, /* The image after gaussian smoothing. */ *delta_x, /* The first devivative image, x-direction. */ *delta_y, /* The first derivative image, y-direction. */ *magnitude; /* The magnitude of the gadient image. */ float *dir_radians=NULL; /* Gradient direction image. */ Timer derivative, radian, magnitudeTimer, nonmax, hysteresis; initTimer(&derivative, "derivative"); initTimer(&radian, "radian"); initTimer(&magnitudeTimer, "magnitude"); initTimer(&nonmax, "nonmax"); initTimer(&hysteresis, "hysteresis"); /**************************************************************************** * Perform gaussian smoothing on the image using the input standard * deviation. ****************************************************************************/ if(VERBOSE) printf("Smoothing the image using a gaussian kernel.\n"); startTimer(&gaussianTime); smoothedim = gaussian_smooth(image, rows, cols, sigma); stopTimer(&gaussianTime); printTimer(&gaussianTime); /**************************************************************************** * Compute the first derivative in the x and y directions. ****************************************************************************/ if(VERBOSE) printf("Computing the X and Y first derivatives.\n"); startTimer(&derivative); derrivative_x_y(smoothedim, rows, cols, &delta_x, &delta_y); stopTimer(&derivative); printTimer(&derivative); /**************************************************************************** * This option to write out the direction of the edge gradient was added * to make the information available for computing an edge quality figure * of merit. ****************************************************************************/ if(fname != NULL) { /************************************************************************* * Compute the direction up the gradient, in radians that are * specified counteclockwise from the positive x-axis. *************************************************************************/ startTimer(&radian); radian_direction(delta_x, delta_y, rows, cols, &dir_radians, -1, -1); stopTimer(&radian); printTimer(&radian); /************************************************************************* * Write the gradient direction image out to a file. *************************************************************************/ if((fpdir = fopen(fname, "wb")) == NULL) { fprintf(stderr, "Error opening the file %s for writing.\n", fname); exit(1); } fwrite(dir_radians, sizeof(float), rows*cols, fpdir); fclose(fpdir); free(dir_radians); } /**************************************************************************** * Compute the magnitude of the gradient. ****************************************************************************/ /**************************************************************************** * Allocate an image to store the magnitude of the gradient. ****************************************************************************/ if((magnitude = (short *) malloc(rows*cols* sizeof(short))) == NULL) { fprintf(stderr, "Error allocating the magnitude image.\n"); exit(1); } if(VERBOSE) printf("Computing the magnitude of the gradient.\n"); startTimer(&magnitudeTimer); magnitude_x_y(delta_x, delta_y, rows, cols, magnitude); stopTimer(&magnitudeTimer); printTimer(&magnitudeTimer); /**************************************************************************** * Perform non-maximal suppression. ****************************************************************************/ if(VERBOSE) printf("Doing the non-maximal suppression.\n"); if((nms = (unsigned char *) malloc(rows*cols*sizeof(unsigned char)))==NULL) { fprintf(stderr, "Error allocating the nms image.\n"); exit(1); } startTimer(&nonmax); non_max_supp(magnitude, delta_x, delta_y, rows, cols, nms); stopTimer(&nonmax); printTimer(&nonmax); /**************************************************************************** * Use hysteresis to mark the edge pixels. ****************************************************************************/ if(VERBOSE) printf("Doing hysteresis thresholding.\n"); if( (*edge=(unsigned char *)malloc(rows*cols*sizeof(unsigned char))) == NULL ) { fprintf(stderr, "Error allocating the edge image.\n"); exit(1); } startTimer(&hysteresis); apply_hysteresis(magnitude, nms, rows, cols, tlow, thigh, *edge); stopTimer(&hysteresis); printTimer(&hysteresis); /**************************************************************************** * Free all of the memory that we allocated except for the edge image that * is still being used to store out result. ****************************************************************************/ free(smoothedim); free(delta_x); free(delta_y); free(magnitude); free(nms); }
int main(int argc, char *argv[]) { char *infilename = NULL; /* Name of the input image */ char *dirfilename = NULL; /* Name of the output gradient direction image */ char outfilename[128]; /* Name of the output "edge" image */ char composedfname[128]; /* Name of the output "direction" image */ unsigned char *image; /* The input image */ unsigned char *edge; /* The output edge image */ int rows, cols; /* The dimensions of the image. */ float sigma=2.5, /* Standard deviation of the gaussian kernel. */ tlow=0.5, /* Fraction of the high threshold in hysteresis. */ thigh=0.5; /* High hysteresis threshold control. The actual threshold is the (100 * thigh) percentage point in the histogram of the magnitude of the gradient image that passes non-maximal suppression. */ /**************************************************************************** * Get the command line arguments. ****************************************************************************/ if(argc < 2) { fprintf(stderr,"\n<USAGE> %s image sigma tlow thigh [writedirim]\n",argv[0]); fprintf(stderr,"\n image: An image to process. Must be in "); fprintf(stderr,"PGM format.\n"); exit(1); } infilename = argv[1]; Timer totalTime; initTimer(&totalTime, "Total Time"); initTimer(&gaussianTime, "Gaussian Time"); /**************************************************************************** * Read in the image. This read function allocates memory for the image. ****************************************************************************/ if(VERBOSE) printf("Reading the image %s.\n", infilename); if(read_pgm_image(infilename, &image, &rows, &cols) == 0) { fprintf(stderr, "Error reading the input image, %s.\n", infilename); exit(1); } /**************************************************************************** * Perform the edge detection. All of the work takes place here. ****************************************************************************/ if(VERBOSE) printf("Starting Canny edge detection.\n"); if(dirfilename != NULL) { sprintf(composedfname, "%s_s_%3.2f_l_%3.2f_h_%3.2f.fim", infilename, sigma, tlow, thigh); dirfilename = composedfname; } startTimer(&totalTime); MCPROF_START(); canny(image, rows, cols, sigma, tlow, thigh, &edge, dirfilename); MCPROF_STOP(); stopTimer(&totalTime); printTimer(&totalTime); /**************************************************************************** * Write out the edge image to a file. ****************************************************************************/ sprintf(outfilename, "%s_s_%3.2f_l_%3.2f_h_%3.2f.pgm", infilename, sigma, tlow, thigh); if(VERBOSE) printf("Writing the edge iname in the file %s.\n", outfilename); if(write_pgm_image(outfilename, edge, rows, cols, "", 255) == 0) { fprintf(stderr, "Error writing the edge image, %s.\n", outfilename); exit(1); } free(image); free(edge); return 0; }
QString ModelPrinter::printTimer(int idx) { return printTimer(model.timers[idx]); }
ESA build_ESA(char *pStr, int size, char *pAlphabet, char *pIgnore, int free_pStr) { // Check if the string includes a zero termination if(pStr[size] != '\0') { setError("The string MUST include a zero termination within the size\n"); if(free_pStr) free(pStr); return NULL; } initTimer(); int overshoot; ESA esa = malloc(sizeof(*esa)); if(!esa) { setError("Couldn't allocate memory for ESA.\n"); if(free_pStr) { free(pStr); freeTimer(); } return NULL; } unsigned char *text; int n = size + 1; // Include the zeroterninatin in the string // Calculate the overshoot overshoot=init_ds_ssort(500,2000); text = malloc((n + overshoot)*sizeof *text); if(!text) { setError("Couldn't allocate memory for translated text.\n"); free(esa); if(free_pStr) { free(pStr); freeTimer(); } return NULL; } // Translate the text and stop if it fails if(! translate(text, pStr, n-1, pAlphabet, pIgnore) ) { free(text); free(esa); if(free_pStr) free(pStr); freeTimer(); return NULL; } // Free pStr if possible if(free_pStr) free(pStr); // Save the text, alphabet and size in the esa structure setStr(esa, text); setSize(esa, n); setAlphabetSize(esa, strlen(pAlphabet)); setIgnoreAlphabetSize(esa, strlen(pIgnore)); setAlphabet(esa, pAlphabet); setIgnoreAlphabet(esa, pIgnore); addTimer("Initializing"); // Do the sorting, calc. lcp and calc. skip esa->suf = malloc(sizeof(int) * n); if(!esa->suf) { free(text); free(esa); freeTimer(); setError("Couldn't allocate memory for suffix column in suffix array.\n"); return NULL; } ds_ssort(esa->pStr, esa->suf, n, MAXPSSMSIZE); addTimer("DS-Sort"); esa->lcp = malloc(sizeof(unsigned char) * n); if(!esa->lcp) { setError("Couldn't allocate memory for LCP column in suffix array.\n"); free(esa->suf); free(text); free(esa); freeTimer(); return NULL; } calcLcpNaiv(esa); addTimer("Calc Lcp"); // The line below can be commented in to verify that there are "errors" in the suffix array // it will scan the array for errors and report the minimum depth at which an error was found // the last parameter specifies the max depth to search to). // As a side effect it calculates lcp (when used for this purpose the depth parameter should equa // that used when calling ds_ssort). // verifyNaively(esa, n, MAX_DEPTH); esa->skip = malloc(sizeof(int) * n); if(!esa->skip) { setError("Couldn't allocate memory for SKIP column in suffix array.\n"); free(esa->lcp); free(esa->suf); free(text); free(esa); freeTimer(); return NULL; } if(calcSkip(esa) == 0) { free(esa->skip); free(esa->lcp); free(esa->suf); free(text); free(esa); freeTimer(); return NULL; } addTimer("Calc Skip"); printTimer(); freeTimer(); return esa; }
vector<ZZ> VEProver::encrypt(const vector<ZZ> &messages, const string &label, const hashalg_t &hashAlg, int stat) { Environment e; // first create and give in our group ZZ bigN = pk->getN(); e.groups["RSAGroup"] = new GroupRSA("arbiter", bigN, stat); ZZ bigNSquared = power(bigN, 2); e.groups["G"] = new GroupSquareMod("arbiter", bigNSquared, stat); // now add in elements e.variables["f"] = pk->getF(); e.variables["b"] = pk->getB(); vector<ZZ> as = pk->getAValues(); // XXX: only add as many a values as there as message values // should come up with something better for this assert(as.size() >= messages.size()); for (unsigned i = 0; i < messages.size(); i++) { string name = "a_" + lexical_cast<string>(i+1); e.variables[name] = as[i]; } // now add x_i's for (unsigned i = 0; i < messages.size(); i++) { string name = "x_" + lexical_cast<string>(i+1); e.variables[name] = messages[i]; } input_map inputs; int m = messages.size(); inputs["m"] = m; // now do the computation: this gives us r, u_i, v InterpreterProver calculator; calculator.check("ZKP/examples/encrypt.txt", inputs, e.groups); startTimer(); calculator.compute(e.variables); printTimer("Computed stuff for normal encryption"); // get new environment e = calculator.getEnvironment(); // now need to compute w = abs([d * e^hash(...)]^r mod N^2) ZZ d = pk->getD(); ZZ eVal = pk->getE(); e.variables["d"] = d; e.variables["e"] = eVal; // need hash vector to be u_1, ..., u_m, v // set initial size for ciphertext so we can order it vector<ZZ> ciphertext(m+1); for (variable_map::iterator it = e.variables.begin(); it != e.variables.end(); ++it) { if (it->first.find("u_") != string::npos) { // XXX: this is string parsing -- very undesirable! int index = lexical_cast<int>(it->first.substr(2)); ciphertext[index-1] = it->second; } else if (it->first.find("v") != string::npos) { ciphertext[m] = it->second; } } string hashKey = pk->getHashKey(); ZZ hash = CommonFunctions::ZZFromBytes(Hash::hash(ciphertext, label, hashAlg, hashKey)); e.variables["hash"] = hash; ZZ eHash = PowerMod(eVal, hash, bigNSquared); ZZ de = MulMod(d, eHash, bigNSquared); ZZ r = e.variables.at("r"); ZZ w = CommonFunctions::abs(PowerMod(de, r, bigNSquared), bigNSquared); // insert w into environment e.variables["w"] = w; // save environment env = e; // now output full ciphertext u_1,...,u_m,v,w ciphertext.push_back(w); return ciphertext; }
/******************************************************************************* * PROCEDURE: gaussian_smooth * PURPOSE: Blur an image with a gaussian filter. * NAME: Mike Heath * DATE: 2/15/96 *******************************************************************************/ short int* gaussian_smooth(unsigned char *image, int rows, int cols, float sigma) { int r, c, rr, cc, /* Counter variables. */ windowsize, /* Dimension of the gaussian kernel. */ center; /* Half of the windowsize. */ float *tempim,*tempim1, /* Buffer for separable filter gaussian smoothing. */ *kernel, /* A one dimensional gaussian kernel. */ dot, /* Dot product summing variable. */ sum; /* Sum of the kernel weights variable. */ /**************************************************************************** * Create a 1-dimensional gaussian smoothing kernel. ****************************************************************************/ if(VERBOSE) printf(" Computing the gaussian smoothing kernel.\n"); make_gaussian_kernel(sigma, &kernel, &windowsize); center = windowsize / 2; /**************************************************************************** * Allocate a temporary buffer image and the smoothed image. ****************************************************************************/ if((tempim = (float *) malloc(rows*cols* sizeof(float))) == NULL) { fprintf(stderr, "Error allocating the buffer image.\n"); exit(1); } short int* smoothedim; if(((smoothedim) = (short int *) malloc(rows*cols*sizeof(short int))) == NULL) { fprintf(stderr, "Error allocating the smoothed image.\n"); exit(1); } startTimer(&totalTime); //Neon impelementation of gaussian smooth starts here /**************************************************************************** * Blur in the x - direction. ****************************************************************************/ int loop; int floop; //Modification of input image for neon implementation //For Filter 1 float * new_image; //For Filter 2 float *new_image_col; //kernel is changed to 17 from 15 for neon (two 0s at the beginning and the end) float new_kernel[17]; //Generating now kernel filter for (floop = 0 ; floop < 17 ; floop++) { if(floop == 0 || floop == 16 ) new_kernel[floop] = 0 ; else new_kernel [floop] = kernel[floop -1]; } //For filter 1, new cols number for neon unsigned int new_cols; new_cols=cols+16; unsigned int i, k; unsigned int a; unsigned int m; unsigned int n, j; //Malloc of new image used by neon new_image = (float*)malloc(new_cols*rows*sizeof(float)); for( i =0; i<rows; i++){ memset(&new_image[i*new_cols],0,8*sizeof(float)); for( k=0; k<cols;k++){ new_image[i*new_cols+8+k] = (float)image[i*cols+k]; } memset(&new_image[i*new_cols+8+cols],0,8*sizeof(float)); } // Neon handles four piexel at a time float32x4_t neon_input; float32x4_t neon_filter; float32x4_t temp_sum; float32x2_t tempUpper; float32x2_t tempLower; float32_t zero = 0; float32_t temp_output; float Basekernel = 0.0f; float kernelSum; //When using the new filter, we always assume the image has more than 9 pixels in a row //Base sum for the filter for( a=8; a<=16; a++){ Basekernel += new_kernel[a]; } //Filter 1, filtering row by row for(m=0; m<rows; m++){ for( n=0; n<cols; n++){ temp_sum = vdupq_n_f32(0); if(n==0){ kernelSum = Basekernel; } else if(n <=8){ kernelSum += new_kernel[8-n]; } else if(n>=cols-8){ kernelSum -=new_kernel[cols-n+8]; } //For each pixel, filtering is performed four times for( j=0; j<4; j++) { int kk=0; if(j>=2) { kk=1; } neon_input = vld1q_f32(&new_image[m*new_cols+n+j*4+kk]); neon_filter = vld1q_f32(&new_kernel[j*4+kk]); temp_sum = vmlaq_f32(temp_sum,neon_input,neon_filter); } unsigned int t; for( t=0; t<=3; t++){ temp_output += vgetq_lane_f32(temp_sum,t ); } temp_output += new_image[m*new_cols+n+8] * new_kernel[8]; temp_output /= kernelSum; tempim[m*cols+n] = temp_output; temp_output=0; } } for(r=0; r<rows; r++) { for(c=0; c<cols; c++) { dot = 0.0; sum = 0.0; for(cc=(-center); cc<=center; cc++) { if(((c+cc) >= 0) && ((c+cc) < cols)) { dot += (float)image[r*cols+(c+cc)] * kernel[center+cc]; sum += kernel[center+cc]; } } tempim1[r*cols+c] = dot/sum; } } /**************************************************************************** * Blur in the y - direction. ****************************************************************************/ unsigned int new_rows; new_rows=rows+16; new_image_col = (float*)malloc(new_rows*cols*sizeof(float)); if(VERBOSE) printf(" Bluring the image in the Y-direction.\n"); for( i =0; i<cols; i++){//actually nember of new rows are the number of columns here memset(&new_image_col[i*new_rows],0,8*sizeof(float)); for( k=0; k<rows;k++){ new_image_col[i*new_rows+8+k] = tempim[k*cols+i]; //new_image_col[i*new_rows+8+k] = imagetest1[k*cols+i]; } memset(&new_image_col[i*new_rows+8+rows],0,8*sizeof(float)); } Basekernel = 0.0; for( a=8; a<=16; a++){ Basekernel += new_kernel[a]; } for(m=0; m<cols; m++){// it was rows at br for( n=0; n<rows; n++){ temp_sum = vdupq_n_f32(0); if(n==0){ kernelSum = Basekernel; } else if(n <=8){ kernelSum += new_kernel[8-n]; } else if(n>=rows-8){ kernelSum -=new_kernel[rows-n+8]; } for( j=0; j<4; j++) { int kk=0; if(j>=2) { kk=1; } neon_input = vld1q_f32(&new_image_col[m*new_rows+n+j*4+kk]); neon_filter = vld1q_f32(&new_kernel[j*4+kk]); temp_sum = vmlaq_f32(temp_sum,neon_input,neon_filter); } unsigned int t; for( t=0; t<=3; t++){ temp_output += vgetq_lane_f32(temp_sum,t ); } temp_output += new_image_col[m*new_rows+n+8] * new_kernel[8]; temp_output = (temp_output * BOOSTBLURFACTOR) / kernelSum + 0.5; smoothedim[n*cols+m] = (short int )temp_output; temp_output=0; } } stopTimer(&totalTime); printTimer(&totalTime); free(tempim); free(kernel); return smoothedim; }
int main(void) { while (1) { state = 0; int setTime = 15; numPlayers = 2; initScreen(); clearScreen(); initCharBuffer(); clean_up(); initKeyboard(); initState0(); initAI(); //Bypass the menu system for testing if (IORD(keys,0) == 8) { initPlayer(pOne, MARIO, "pOne", 50, 100, HUMAN); initPlayer(pTwo, LUIGI, "pTwo", 50, 100, COMPUTER); state = 2; } else { while (state == 0) { decode_scancode(ps2, &decode_mode, buf, &ascii); state_0(decode_mode, buf[0]); }; initState1(pOne); if(aOn)file_handle = initAudio(fname); if(aOn)alt_irq_register(AUDIO_0_IRQ, &ab, (alt_isr_func) write_fifo); if(aOn) alt_up_audio_enable_write_interrupt(ab->audio); while (state == 1) { decode_scancode(ps2, &decode_mode, buf, &ascii); state_1(decode_mode, buf[0], ascii); if(aOn)loop_audio(file_handle, fname, ab); }; } //clean_up(); clearCharBuffer(); clearScreen(); //enable keyboard IRQ void* keyboard_control_register_ptr = (void*) (KEYBOARD_BASE + 4); alt_irq_register(KEYBOARD_IRQ, keyboard_control_register_ptr, keyboard_ISR); alt_up_ps2_enable_read_interrupt(ps2); //Draw field and UI to both buffers initField(); updateField(); drawName(p[pOne].name, p[pTwo].name, p[pThree].name, p[pFour].name); drawGas(p[pOne].gas); drawHealth(p[pOne].hp, p[pTwo].hp, p[pThree].hp, p[pFour].hp); drawBullet(p[pOne].bulletType); //drawWindIndicator(1); updateScreen(); updateField(); drawName(p[pOne].name, p[pTwo].name, p[pThree].name, p[pFour].name); drawGas(p[pOne].gas); drawHealth(p[pOne].hp, p[pTwo].hp, p[pThree].hp, p[pFour].hp); drawBullet(p[pOne].bulletType); //drawWindIndicator(1); float time; alt_timestamp_start(); int start_timer_flag = 1; //printf("NUM PLAYERA %i\n", numPlayers); int i; while (state == 2) { int fallFlag = 1; //Checks to see if any players are falling while (fallFlag == 1) { fallFlag = 0; for (i = 0; i < numPlayers; i++) { if (p[i].alive) { if (p[i].y + TANK_HEIGHT >= SCREEN_HEIGHT-1) { p[i].hp = 0; p[i].alive = DEAD; } checkPlayerFalling(i); if (p[i].isFalling) { undrawPlayer(i); updatePlayer(i); fallFlag = 1; } } } if (fallFlag == 1) { updateScreen(); } } if(start_timer_flag){ start_time = (float) alt_timestamp() / (float) alt_timestamp_freq(); start_timer_flag = 0; } time = (float) alt_timestamp() / (float) alt_timestamp_freq()-start_time; if (time >= setTime) { setPlayerTurn(); } if (p[turn].type == HUMAN) { runGame(); } else { p[turn].deg = 0; aiMain(turn); setPlayerTurn(); } printTimer(setTime - time); int deadCount = 0; for (i = 0; i < numPlayers; i++) { if (p[i].alive == DEAD) deadCount++; } if (deadCount == numPlayers - 1) { usleep(500000); state = 3; } } alt_up_ps2_disable_read_interrupt(ps2); if(aOn)alt_up_audio_disable_write_interrupt(ab->audio); GameOverScreen(); } }