Esempio n. 1
0
int CollectDataFlow(const std::string &DFTBinary, const std::string &DirPath,
                    const Vector<SizedFile> &CorporaFiles) {
  Printf("INFO: collecting data flow: bin: %s dir: %s files: %zd\n",
         DFTBinary.c_str(), DirPath.c_str(), CorporaFiles.size());
  MkDir(DirPath);
  auto Temp = TempPath(".dft");
  for (auto &F : CorporaFiles) {
    // For every input F we need to collect the data flow and the coverage.
    // Data flow collection may fail if we request too many DFSan tags at once.
    // So, we start from requesting all tags in range [0,Size) and if that fails
    // we then request tags in [0,Size/2) and [Size/2, Size), and so on.
    // Function number => DFT.
    std::unordered_map<size_t, Vector<uint8_t>> DFTMap;
    std::unordered_set<std::string> Cov;
    std::queue<std::pair<size_t, size_t>> Q;
    Q.push({0, F.Size});
    while (!Q.empty()) {
      auto R = Q.front();
      Printf("\n\n\n********* Trying: [%zd, %zd)\n", R.first, R.second);
      Q.pop();
      Command Cmd;
      Cmd.addArgument(DFTBinary);
      Cmd.addArgument(std::to_string(R.first));
      Cmd.addArgument(std::to_string(R.second));
      Cmd.addArgument(F.File);
      Cmd.addArgument(Temp);
      Printf("CMD: %s\n", Cmd.toString().c_str());
      if (ExecuteCommand(Cmd)) {
        // DFSan has failed, collect tags for two subsets.
        if (R.second - R.first >= 2) {
          size_t Mid = (R.second + R.first) / 2;
          Q.push({R.first, Mid});
          Q.push({Mid, R.second});
        }
      } else {
        Printf("********* Success: [%zd, %zd)\n", R.first, R.second);
        std::ifstream IF(Temp);
        std::string L;
        while (std::getline(IF, L, '\n')) {
          // Data flow collection has succeeded.
          // Merge the results with the other runs.
          if (L.empty()) continue;
          if (L[0] == 'C') {
            // Take coverage lines as is, they will be the same in all attempts.
            Cov.insert(L);
          } else if (L[0] == 'F') {
            size_t FunctionNum = 0;
            std::string DFTString;
            if (ParseDFTLine(L, &FunctionNum, &DFTString)) {
              auto &DFT = DFTMap[FunctionNum];
              if (DFT.empty()) {
                // Haven't seen this function before, take DFT as is.
                DFT = DFTStringToVector(DFTString);
              } else if (DFT.size() == DFTString.size()) {
                // Have seen this function already, merge DFTs.
                DFTStringAppendToVector(&DFT, DFTString);
              }
            }
          }
        }
      }
    }
    auto OutPath = DirPlusFile(DirPath, Hash(FileToVector(F.File)));
    // Dump combined DFT to disk.
    Printf("Producing DFT for %s\n", OutPath.c_str());
    std::ofstream OF(OutPath);
    for (auto &DFT: DFTMap)
      OF << "F" << DFT.first << " " << DFT.second << std::endl;
    for (auto &C : Cov)
      OF << C << std::endl;
  }
  RemoveFile(Temp);
  // Write functions.txt.
  Command Cmd;
  Cmd.addArgument(DFTBinary);
  Cmd.setOutputFile(DirPlusFile(DirPath, "functions.txt"));
  ExecuteCommand(Cmd);
  return 0;
}
Esempio n. 2
0
void HashGridLookup::ReHash(float currentPhotonRadius2) {
#else
void HashGridLookup::ReHash(float /*currentPhotonRadius*/) {
#endif

	const unsigned int hitPointsCount = engine->hitPointTotal;
	const BBox &hpBBox = hitPointsbbox;

	// Calculate the size of the grid cell
#if defined USE_SPPMPA || defined USE_PPMPA
	float maxPhotonRadius2 = currentPhotonRadius2;
#else
	float maxPhotonRadius2 = 0.f;
	for (unsigned int i = 0; i < hitPointsCount; ++i) {
		HitPointStaticInfo *ihp = &workerHitPointsInfo[i];
		HitPoint *hp = &workerHitPoints[i];

		if (ihp->type == SURFACE)
		maxPhotonRadius2 = Max(maxPhotonRadius2, hp->accumPhotonRadius2);
	}

#endif
	const float cellSize = sqrtf(maxPhotonRadius2) * 2.f;
	//std::cerr << "Hash grid cell size: " << cellSize << std::endl;
	invCellSize = 1.f / cellSize;

	// TODO: add a tunable parameter for hashgrid size
	//hashGridSize = hitPointsCount;
	if (!hashGrid) {
		hashGrid = new std::list<uint>*[hashGridSize];

		for (unsigned int i = 0; i < hashGridSize; ++i)
			hashGrid[i] = NULL;
	} else {
		for (unsigned int i = 0; i < hashGridSize; ++i) {
			delete hashGrid[i];
			hashGrid[i] = NULL;
		}
	}

	//std::cerr << "Building hit points hash grid:" << std::endl;
	//std::cerr << "  0k/" << hitPointsCount / 1000 << "k" << std::endl;
	//unsigned int maxPathCount = 0;
//	double lastPrintTime = WallClockTime();
	unsigned long long entryCount = 0;

	for (unsigned int i = 0; i < hitPointsCount; ++i) {

//		if (WallClockTime() - lastPrintTime > 2.0) {
//			std::cerr << "  " << i / 1000 << "k/" << hitPointsCount / 1000 << "k" << std::endl;
//			lastPrintTime = WallClockTime();
//		}

		//HitPointInfo *hp = engine->GetHitPointInfo(i);
		HitPointStaticInfo *hp = &workerHitPointsInfo[i];

		if (hp->type == SURFACE) {

#if defined USE_SPPMPA || defined USE_PPMPA

			const float photonRadius = sqrtf(currentPhotonRadius2);

#else
			HitPoint *hpp = &workerHitPoints[i];
			const float photonRadius = sqrtf(hpp->accumPhotonRadius2);

#endif
			const Vector rad(photonRadius, photonRadius, photonRadius);
			const Vector bMin = ((hp->position - rad) - hpBBox.pMin) * invCellSize;
			const Vector bMax = ((hp->position + rad) - hpBBox.pMin) * invCellSize;

			for (int iz = abs(int(bMin.z)); iz <= abs(int(bMax.z)); iz++) {
				for (int iy = abs(int(bMin.y)); iy <= abs(int(bMax.y)); iy++) {
					for (int ix = abs(int(bMin.x)); ix <= abs(int(bMax.x)); ix++) {

						int hv = Hash(ix, iy, iz);

						//if (hv == engine->hitPointTotal - 1)

						if (hashGrid[hv] == NULL)
							hashGrid[hv] = new std::list<uint>();

//						std::list<unsigned int>* hps = hashGrid[hv];
//						if (hps) {
//							std::list<unsigned int>::iterator iter = hps->begin();
//							while (iter != hps->end()) {
//								if (*iter == i) {
//									printf("found");
//									exit(0);
//								}
//							}
//						}

						hashGrid[hv]->push_front(i);
						++entryCount;

						/*// hashGrid[hv]->size() is very slow to execute
						 if (hashGrid[hv]->size() > maxPathCount)
						 maxPathCount = hashGrid[hv]->size();*/
					}
				}
			}
		}
	}

	hashGridEntryCount = entryCount;

	//std::cerr << "Max. hit points in a single hash grid entry: " << maxPathCount << std::endl;
//	std::cerr << "Total hash grid entry: " << entryCount << std::endl;
//	std::cerr << "Avg. hit points in a single hash grid entry: " << entryCount
//			/ hashGridSize << std::endl;

	//printf("Sizeof %d\n", sizeof(HitPoint*));

	// HashGrid debug code
	/*for (unsigned int i = 0; i < hashGridSize; ++i) {
	 if (hashGrid[i]) {
	 if (hashGrid[i]->size() > 10) {
	 std::cerr << "HashGrid[" << i << "].size() = " <<hashGrid[i]->size() << std::endl;
	 }
	 }
	 }*/
}

#if defined USE_SPPM || defined USE_PPM
void HashGridLookup::AddFlux(PointerFreeScene *ss, const float /*alpha*/, const Point &hitPoint,
		const Normal &shadeN, const Vector wi, const Spectrum photonFlux,
		float /*currentPhotonRadius2*/) {
#else
void HashGridLookup::AddFlux(PointerFreeScene *ss, const float /*alpha*/, const Point &hitPoint,
		const Normal &shadeN, const Vector wi, const Spectrum photonFlux,
		float currentPhotonRadius2) {
#endif

	// Look for eye path hit points near the current hit point
	Vector hh = (hitPoint - hitPointsbbox.pMin) * invCellSize;
	const int ix = abs(int(hh.x));
	const int iy = abs(int(hh.y));
	const int iz = abs(int(hh.z));

	//	std::list<uint> *hps = hashGrid[Hash(ix, iy, iz, hashGridSize)];
	//	if (hps) {
	//		std::list<uint>::iterator iter = hps->begin();
	//		while (iter != hps->end()) {
	//
	//			HitPoint *hp = &hitPoints[*iter++];


	uint gridEntry = Hash(ix, iy, iz);
	std::list<unsigned int>* hps = hashGrid[gridEntry];

	if (hps) {
		std::list<unsigned int>::iterator iter = hps->begin();
		while (iter != hps->end()) {

			HitPointStaticInfo *hp = &workerHitPointsInfo[*iter];
			HitPoint *ihp = &workerHitPoints[*iter++];

//			Vector v = hp->position - hitPoint;

#if defined USE_SPPM || defined USE_PPM
			//if ((Dot(hp->normal, shadeN) > 0.5f) && (Dot(v, v) <= ihp->accumPhotonRadius2)) {

			const float dist2 = DistanceSquared(hp->position, hitPoint);
			if ((dist2 > ihp->accumPhotonRadius2))
			continue;

			const float dot = Dot(hp->normal, wi);
			if (dot <= 0.0001f)
			continue;

#else
			const float dist2 = DistanceSquared(hp->position, hitPoint);
			if ((dist2 > currentPhotonRadius2))
				continue;

			const float dot = Dot(hp->normal, wi);
			if (dot <= 0.0001f)
				continue;
#endif

			//const float g = (hp->accumPhotonCount * alpha + alpha)
			//		/ (hp->accumPhotonCount * alpha + 1.f);


			//hp->photonRadius2 *= g;
			__sync_fetch_and_add(&ihp->accumPhotonCount, 1);

			Spectrum f;

			POINTERFREESCENE::Material *hitPointMat = &ss->materials[hp->materialSS];

			switch (hitPointMat->type) {

			case MAT_MATTE:
				ss->Matte_f(&hitPointMat->param.matte, hp->wo, wi, shadeN, f);
				break;

			case MAT_MATTEMIRROR:
				ss->MatteMirror_f(&hitPointMat->param.matteMirror, hp->wo, wi, shadeN, f);
				break;

			case MAT_MATTEMETAL:
				ss->MatteMetal_f(&hitPointMat->param.matteMetal, hp->wo, wi, shadeN, f);
				break;

			case MAT_ALLOY:
				ss->Alloy_f(&hitPointMat->param.alloy, hp->wo, wi, shadeN, f);
				break;
			default:
				break;

			}

			//f = hp->material->f(hp->wo, wi, shadeN);

			Spectrum flux = photonFlux * AbsDot(shadeN, wi) * hp->throughput * f;
			//if ((*iter-1) == 200) printf("%f\n", photonFlux.g);

#pragma omp critical
			{

				ihp->accumReflectedFlux = (ihp->accumReflectedFlux + flux) /** g*/;
			}
			//
			//				hp->accumReflectedFlux.r += flux.r;
			//				hp->accumReflectedFlux.r += flux.r;
			//				hp->accumReflectedFlux.r += flux.r;

			//printf("%f\n", f.r);


		}

	}
}
Esempio n. 3
0
bool CWalletDB::WriteKey(const CPubKey& vchPubKey, const CPrivKey& vchPrivKey, const CKeyMetadata& keyMeta)
{
    nWalletDBUpdateCounter++;

    if (!Write(std::make_pair(std::string("keymeta"), vchPubKey),
               keyMeta, false))
        return false;

    // hash pubkey/privkey to accelerate wallet load
    std::vector<unsigned char> vchKey;
    vchKey.reserve(vchPubKey.size() + vchPrivKey.size());
    vchKey.insert(vchKey.end(), vchPubKey.begin(), vchPubKey.end());
    vchKey.insert(vchKey.end(), vchPrivKey.begin(), vchPrivKey.end());

    return Write(std::make_pair(std::string("key"), vchPubKey), std::make_pair(vchPrivKey, Hash(vchKey.begin(), vchKey.end())), false);
}
Esempio n. 4
0
	explicit unordered_map(
		size_type bucket_count = unordered_map_default_bucket_count,
		const Hash& hash = Hash(),
		const KeyEqual& equal = KeyEqual(),
		const Allocator& alloc = Allocator())
			: _Base(bucket_count, hash, equal, alloc) {}
Esempio n. 5
0
/*++
 * Function:	Get_Server_sd
 *
 * Purpose:	When a client login attempt is made, fetch a usable server
 *              socket descriptor.  This means that either we reuse an
 *              existing sd, or we open a new one.  Hide that abstraction from
 *              the caller...
 *
 * Parameters:	ptr to username string
 *		ptr to password string
 *              const ptr to client hostname or IP string (for logging only)
 *
 * Returns:	int sd on success
 *              -1 on failure
 *
 * Authors:	dgm
 *
 *--
 */
extern int Get_Server_sd( char *Username,
                          char *Password,
                          const char *ClientAddr )
{
    char *fn = "Get_Server_sd()";
    unsigned int HashIndex;
    ICC_Struct *HashEntry = NULL;
    char SendBuf[BUFSIZE];
    unsigned int BufLen = BUFSIZE - 1;
    char md5pw[16];
    char *tokenptr;
    char *endptr;
    char *last;
    ICC_Struct *ICC_Active;
    ICC_Struct *ICC_tptr;
    ITD_Struct Server;
    int rc;
    unsigned int Expiration;

    Expiration = PC_Struct.cache_expiration_time;
    memset( &Server, 0, sizeof Server );

    /* need to md5 the passwd regardless, so do that now */
    md5_calc( md5pw, Password, strlen( Password ) );

    /* see if we have a reusable connection available */
    ICC_Active = NULL;
    HashIndex = Hash( Username, HASH_TABLE_SIZE );

    LockMutex( &mp );

    /*
     * Now we just iterate through the linked list at this hash index until
     * we either find the string we're looking for or we find a NULL.
     */
    for ( HashEntry = ICC_HashTable[ HashIndex ];
            HashEntry;
            HashEntry = HashEntry->next )
    {
        if ( ( strcmp( Username, HashEntry->username ) == 0 ) &&
                ( HashEntry->logouttime > 1 ) )
        {
            ICC_Active = HashEntry;
            /*
             * we found this username in our hash table.  Need to know if
             * the password matches.
             */
            if ( memcmp( md5pw, ICC_Active->hashedpw, sizeof md5pw ) )
            {
                /* the passwords don't match.  Shake this guy. */
                UnLockMutex( &mp );
                syslog(LOG_INFO, "LOGIN: '******' (%s) failed: password incorrect", Username, ClientAddr );
                return( -1 );
            }

            /*
             * We found a matching password on an inactive server socket.  We
             * can use this guy.  Before we release the mutex, set the
             * logouttime such that we mark this connection as "active" again.
             */
            ICC_Active->logouttime = 0;

            /*
             * The fact that we have this stored in a table as an open server
             * socket doesn't really mean that it's open.  The server could've
             * closed it on us.
             * We need a speedy way to make sure this is still open.
             * We'll set the fd to non-blocking and try to read from it.  If we
             * get a zero back, the connection is closed.  If we get
             * EWOULDBLOCK (or some data) we know it's still open.  If we do
             * read data, make sure we read all the data so we "drain" any
             * puss that may be left on this socket.
             */
            fcntl( ICC_Active->server_sd, F_SETFL,
                   fcntl( ICC_Active->server_sd, F_GETFL, 0) | O_NONBLOCK );

            while ( ( rc = recv( ICC_Active->server_sd, Server.ReadBuf,
                                 sizeof Server.ReadBuf, 0 ) ) > 0 );

            if ( !rc )
            {
                syslog(LOG_NOTICE, "%s: Unable to reuse server sd [%d] for user '%s' (%s).  Connection closed by server.", fn, ICC_Active->server_sd, Username, ClientAddr );
                ICC_Active->logouttime = 1;
                continue;
            }

            if ( errno != EWOULDBLOCK )
            {
                syslog(LOG_NOTICE, "%s: Unable to reuse server sd [%d] for user '%s' (%s). recv() error: %s", fn, ICC_Active->server_sd, Username, ClientAddr, strerror( errno ) );
                ICC_Active->logouttime = 1;
                continue;
            }


            fcntl( ICC_Active->server_sd, F_SETFL,
                   fcntl( ICC_Active->server_sd, F_GETFL, 0) & ~O_NONBLOCK );


            /* now release the mutex and return the sd to the caller */
            UnLockMutex( &mp );

            /*
             * We're reusing an existing server socket.  There are a few
             * counters we have to deal with.
             */
            IMAPCount->RetainedServerConnections--;
            IMAPCount->InUseServerConnections++;
            IMAPCount->TotalServerConnectionsReused++;

            if ( IMAPCount->InUseServerConnections >
                    IMAPCount->PeakInUseServerConnections )
                IMAPCount->PeakInUseServerConnections = IMAPCount->InUseServerConnections;

            syslog(LOG_INFO, "LOGIN: '******' (%s) on existing sd [%d]", Username, ClientAddr, ICC_Active->server_sd );
            return( ICC_Active->server_sd );
        }
    }

    UnLockMutex( &mp );

    /*
     * We don't have an active connection for this user.
     * Open a connection to the IMAP server so we can attempt to login
     */
    Server.sd = socket( AF_INET, SOCK_STREAM, IPPROTO_TCP );
    if ( Server.sd == -1 )
    {
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: Unable to open server socket: %s",
               Username, ClientAddr, strerror( errno ) );
        return( -1 );
    }

    if ( connect( Server.sd, (struct sockaddr *)&ISD.srv,
                  sizeof(ISD.srv) ) == -1 )
    {
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: Unable to connect to IMAP server: %s", Username, ClientAddr, strerror( errno ) );
        close( Server.sd );
        return( -1 );
    }


    /* Read & throw away the banner line from the server */

    if ( IMAP_Line_Read( &Server ) == -1 )
    {
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: No banner line received from IMAP server",
               Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }

    /*
     * Send the login command off to the IMAP server.
     */
    snprintf( SendBuf, BufLen, "A0001 LOGIN %s %s\r\n",
              Username, Password );

    if ( send( Server.sd, SendBuf, strlen(SendBuf), 0 ) == -1 )
    {
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: send() failed attempting to send LOGIN command to IMAP server: %s", Username, ClientAddr, strerror( errno ) );
        close( Server.sd );
        return( -1 );
    }

    /*
     * Read the server response
     */
    if ( ( rc = IMAP_Line_Read( &Server ) ) == -1 )
    {
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: No response from IMAP server after sending LOGIN command", Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }


    /*
     * Try to match up the tag in the server response to the client tag.
     */
    endptr = Server.ReadBuf + rc;

    tokenptr = memtok( Server.ReadBuf, endptr, &last );

    if ( !tokenptr )
    {
        /*
         * no tokens found in server response?  Not likely, but we still
         * have to check.
         */
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: server response to LOGIN command contained no tokens.", Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }

    if ( memcmp( (const void *)tokenptr, (const void *)"A0001",
                 strlen( tokenptr ) ) )
    {
        /*
         * non-matching tag read back from the server... Lord knows what this
         * is, so we'll fail.
         */
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: server response to LOGIN command contained non-matching tag.", Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }


    /*
     * Now that we've matched the tags up, see if the response was 'OK'
     */
    tokenptr = memtok( NULL, endptr, &last );

    if ( !tokenptr )
    {
        /* again, not likely but we still have to check... */
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: Malformed server response to LOGIN command", Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }

    if ( memcmp( (const void *)tokenptr, "OK", 2 ) )
    {
        /*
         * If the server sent back a "NO" or "BAD", we can look at the actual
         * server logs to figure out why.  We don't have to break our ass here
         * putting the string back together just for the sake of logging.
         */
        syslog(LOG_INFO, "LOGIN: '******' (%s) failed: non-OK server response to LOGIN command", Username, ClientAddr );
        close( Server.sd );
        return( -1 );
    }

    /*
     * put this in our used list and remove it from the free list
     */
    for( ; ; )
    {
        LockMutex( &mp );

        if ( ICC_free->next )
        {
            /* generate the hash index */
            HashIndex = Hash( Username, HASH_TABLE_SIZE );

            /* temporarily store the address of the next free structure */
            ICC_tptr = ICC_free->next;

            /*
             * We want to add the newest "used" structure at the front of
             * the list at the hash index.
             */
            ICC_free->next = ICC_HashTable[ HashIndex ];
            ICC_HashTable[ HashIndex ] = ICC_free;

            /*
             * less typing and more readability, set an "active" pointer.
             */
            ICC_Active = ICC_free;

            /* now point the free listhead to the next available free struct */
            ICC_free = ICC_tptr;

            /* fill in the newest used (oxymoron?) structure */
            strncpy( ICC_Active->username, Username,
                     sizeof ICC_Active->username );
            memcpy( ICC_Active->hashedpw, md5pw, sizeof ICC_Active->hashedpw );
            ICC_Active->logouttime = 0;    /* zero means, "it's active". */
            ICC_Active->server_sd = Server.sd;

            UnLockMutex( &mp );

            IMAPCount->InUseServerConnections++;
            IMAPCount->TotalServerConnectionsCreated++;

            if ( IMAPCount->InUseServerConnections >
                    IMAPCount->PeakInUseServerConnections )
                IMAPCount->PeakInUseServerConnections = IMAPCount->InUseServerConnections;
            syslog(LOG_INFO, "LOGIN: '******' (%s) on new sd [%d]", Username, ClientAddr, Server.sd );
            return( Server.sd );
        }

        /*
         * There weren't any free ICC structs.  Try to free one.  Make sure
         * we unlock the mutex, since ICC_Recycle needs to obtain it.
         */
        UnLockMutex( &mp );

        Expiration = abs( Expiration / 2 );

        /*
         * Eventually, we have to fail
         */
        if ( Expiration <= 2 )
        {
            syslog(LOG_INFO, "LOGIN: '******' (%s) failed: Out of free ICC structs.", Username, ClientAddr );
            close( Server.sd );
            return( -1 );
        }

        ICC_Recycle( Expiration );

    }

}
int HashFunction::MakeAddress (string key, unsigned int depth){

   unsigned int hash = Hash(key);
   return MakeAddress(hash,depth);
}
Esempio n. 7
0
uint256 CBlock::BuildMerkleTree(bool* fMutated) const
{
    /* WARNING! If you're reading this because you're learning about crypto
       and/or designing a new system that will use merkle trees, keep in mind
       that the following merkle tree algorithm has a serious flaw related to
       duplicate txids, resulting in a vulnerability (CVE-2012-2459).

       The reason is that if the number of hashes in the list at a given time
       is odd, the last one is duplicated before computing the next level (which
       is unusual in Merkle trees). This results in certain sequences of
       transactions leading to the same merkle root. For example, these two
       trees:

                    A               A
                  /  \            /   \
                B     C         B       C
               / \    |        / \     / \
              D   E   F       D   E   F   F
             / \ / \ / \     / \ / \ / \ / \
             1 2 3 4 5 6     1 2 3 4 5 6 5 6

       for transaction lists [1,2,3,4,5,6] and [1,2,3,4,5,6,5,6] (where 5 and
       6 are repeated) result in the same root hash A (because the hash of both
       of (F) and (F,F) is C).

       The vulnerability results from being able to send a block with such a
       transaction list, with the same merkle root, and the same block hash as
       the original without duplication, resulting in failed validation. If the
       receiving node proceeds to mark that block as permanently invalid
       however, it will fail to accept further unmodified (and thus potentially
       valid) versions of the same block. We defend against this by detecting
       the case where we would hash two identical hashes at the end of the list
       together, and treating that identically to the block having an invalid
       merkle root. Assuming no double-SHA256 collisions, this will detect all
       known ways of changing the transactions without affecting the merkle
       root.
    */
    vMerkleTree.clear();
    vMerkleTree.reserve(vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
    for (std::vector<CTransaction>::const_iterator it(vtx.begin()); it != vtx.end(); ++it)
        vMerkleTree.push_back(it->GetHash());
    int j = 0;
    bool mutated = false;
    for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
    {
        for (int i = 0; i < nSize; i += 2)
        {
            int i2 = std::min(i+1, nSize-1);
            if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
                // Two identical hashes at the end of the list at a particular level.
                mutated = true;
            }
            vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]),  END(vMerkleTree[j+i]),
                                       BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
        }
        j += nSize;
    }
    if (fMutated) {
        *fMutated = mutated;
    }
    return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
Esempio n. 8
0
// Management thread
void NiAdminThread(THREAD *thread, void *param)
{
	NAT_ADMIN *a = (NAT_ADMIN *)param;
	NAT *n;
	SOCK *s;
	UCHAR random[SHA1_SIZE];
	UINT err;
	// Validate arguments
	if (thread == NULL || param == NULL)
	{
		return;
	}

	// Random number generation
	Rand(random, sizeof(random));

	a->Thread = thread;
	AddRef(a->Thread->ref);
	s = a->Sock;
	AddRef(s->ref);

	n = a->Nat;

	LockList(n->AdminList);
	{
		Add(n->AdminList, a);
	}
	UnlockList(n->AdminList);

	NoticeThreadInit(thread);

	err = ERR_AUTH_FAILED;

	if (StartSSL(s, n->AdminX, n->AdminK))
	{
		PACK *p;

		// Send the random number
		p = NewPack();
		PackAddData(p, "auth_random", random, sizeof(random));

		if (HttpServerSend(s, p))
		{
			PACK *p;
			// Receive a password
			p = HttpServerRecv(s);
			if (p != NULL)
			{
				UCHAR secure_password[SHA1_SIZE];
				UCHAR secure_check[SHA1_SIZE];

				if (PackGetData2(p, "secure_password", secure_password, sizeof(secure_password)))
				{
					SecurePassword(secure_check, n->HashedPassword, random);

					if (Cmp(secure_check, secure_password, SHA1_SIZE) == 0)
					{
						UCHAR test[SHA1_SIZE];
						// Password match
						Hash(test, "", 0, true);
						SecurePassword(test, test, random);

#if	0
						if (Cmp(test, secure_check, SHA1_SIZE) == 0 && s->RemoteIP.addr[0] != 127)
						{
							// A client can not connect from the outside with blank password
							err = ERR_NULL_PASSWORD_LOCAL_ONLY;
						}
						else
#endif

						{
							// Successful connection
							err = ERR_NO_ERROR;
							NiAdminMain(n, s);
						}
					}
				}

				FreePack(p);
			}
		}

		FreePack(p);

		if (err != ERR_NO_ERROR)
		{
			p = PackError(err);
			HttpServerSend(s, p);
			FreePack(p);
		}
	}

	Disconnect(s);
	ReleaseSock(s);
}
	/*
	ZHashValue value override.  Uses the Java 6 string hash function.  Equivalent to a call
	to Hash.

	@return (ZHashValue) - hash code for this string
	*/
	operator ZHashValue () const 
		{ return Hash(); }
Esempio n. 10
0
 /**
  * Constructor.
  * @param n initial table size.
  * @param hash hash function.
  * @param equal equality function.
  */
 MyHashMap(size_t n, Hash const& hash = Hash(), Equal const& equal = Equal())
         : Table(n, hash, equal) {
 }
Esempio n. 11
0
int TPZWillamWarnke::ClassId() const{
    return Hash("TPZWillamWarnke") ^ WILLAMWARNKEPARENT::ClassId() << 1;
}
Esempio n. 12
0
 /**
  * Default constructor.
  */
 MyHashMap(Hash const& hash = Hash(), Equal const& equal = Equal())
         : Table(MyHashMapHashWrapper<K,V,Hash,Equal>(hash, equal),
                 MyHashMapHashWrapper<K,V,Hash,Equal>(hash, equal)) {
 }
Esempio n. 13
0
 /**
  * Constructor.
  * @param n initial table size.
  * @param hash hash function.
  * @param equal equality function
  */
 MyHashTable(size_t n, Hash const& hash = Hash(), Equal const& equal =
         Equal())
         : hashFunc(hash), eqFunc(equal), tableCapacity_(0), tableSize_(0),
           maxSize_(0), size_(0), table(0), collisions_(0) {
     initialize(n);
 }
Esempio n. 14
0
	Hash hash(const Provider& provider)
	{
		auto tmp = simstd::make_unique<HashImpl>(provider);
		return tmp->is_valid() ? Hash(simstd::move(tmp)) : Hash();
	}
Esempio n. 15
0
float Process(YARPImageOf<YarpPixelBGR>& ref, 
	      YARPImageOf<YarpPixelBGR>& target)
{
  static float bounce = 0;
  static int hash_ref[HASH_SIZE];
  static int hash_target[HASH_SIZE];
  static int hash_target_ylo[HASH_SIZE];
  static int hash_target_yhi[HASH_SIZE];
//  printf("Clearing hash tables\n");
  for (int r=0; r<HASH_SIZE; r++)
    {
      hash_ref[r] = hash_target[r] = 0;
      hash_target_ylo[r] = hash_target_yhi[r] = 0;
    }
//  printf("Comparing images\n");
  int h = ref.GetHeight();
  int w = ref.GetWidth();
  assert(h==target.GetHeight());
  assert(w==target.GetWidth());
  for (int y=0; y<h; y++)
    {
      for (int x=0; x<w; x++)
	{
	  YarpPixelBGR pix_ref = ref(x,y);
	  YarpPixelBGR pix_target = target(x,y);
	  int idx_ref = Hash(pix_ref);
	  int idx_target = Hash(pix_target);
	  hash_ref[idx_ref]++;
	  hash_target[idx_target]++;
	  if (y>=h/2)
	    {
	      hash_target_yhi[idx_target]++;
	    }
	  else
	    {
	      hash_target_ylo[idx_target]++;
	    }
	}
    }
  int votes = 0;
  float dir = 0;
  for (int r=0; r<HASH_SIZE; r++)
    {
      int diff = hash_ref[r] - hash_target[r];
      if (fabs(diff)>3)
	{
	  int hi = hash_target_yhi[r];
	  int lo = hash_target_ylo[r];
	  if (fabs(hi-lo)>3)
	    {
	      float power = fabs(hi-lo)*fabs(diff);
	      if (power>20) power = 20;
	      float direction = power;
	      if (diff>0)
		{
		  if (hi<lo)
		    {
		      direction = -direction;
		    }
		}
	      else
		{
		  if (hi>lo)
		    {
		      direction = -direction;
		    }
		}
	      
	      votes++;
	      dir += direction;
	    }
	}
    }
  printf("%8d votes, verdict is %8.4g ", votes, dir);
  bounce = 0.8*bounce + 0.2*((dir>0)?1:-1);
  if (bounce>0.5) printf("LOOK DOWN");
  if (bounce<-0.5) printf("LOOK UP");
  printf("\n");
  return dir;
}
Esempio n. 16
0
TSS_RESULT
TCSP_LoadKeyByUUID_Internal(TCS_CONTEXT_HANDLE hContext,	/* in */
			    TSS_UUID *KeyUUID,			/* in */
			    TCS_LOADKEY_INFO * pLoadKeyInfo,	/* in, out */
			    TCS_KEY_HANDLE * phKeyTCSI)		/* out */
{
	UINT32 keyslot = 0, keySize;
	UINT32 ordinal;
	TSS_RESULT result;
	TSS_UUID parentUuid;
	BYTE keyBlob[0x1000];
	UINT16 blobSize = sizeof(keyBlob);
	UINT64 offset;
	TCS_KEY_HANDLE parentTCSKeyHandle;

	if (TPM_VERSION_IS(1,2))
		ordinal = TPM_ORD_LoadKey2;
	else
		ordinal = TPM_ORD_LoadKey;

	LogDebugFn("Enter: uuid: 0x%lx auth? 0x%x ***********", (unsigned long)KeyUUID,
		  pLoadKeyInfo == NULL ? 0xdeadbeef : pLoadKeyInfo->authData.AuthHandle);

	if ((result = ctx_verify_context(hContext)))
		return result;

	memset(&parentUuid, 0, sizeof(TSS_UUID));

	if (pLoadKeyInfo &&
	    memcmp(&pLoadKeyInfo->parentKeyUUID, &parentUuid, sizeof(TSS_UUID))) {
		if (ps_get_key_by_uuid(&pLoadKeyInfo->keyUUID, keyBlob, &blobSize))
			return TCSERR(TSS_E_PS_KEY_NOTFOUND);

		if (mc_get_handles_by_uuid(&pLoadKeyInfo->parentKeyUUID, &parentTCSKeyHandle,
					   &keyslot))
			return TCSERR(TCS_E_KM_LOADFAILED);

		return LoadKeyByBlob_Internal(ordinal, hContext, parentTCSKeyHandle,
					      blobSize, keyBlob,
					      &pLoadKeyInfo->authData,
					      phKeyTCSI, &keyslot);
	}

	/* if KeyUUID is already loaded, increment the ref count and return */
	if (mc_get_handles_by_uuid(KeyUUID, phKeyTCSI, &keyslot) == TSS_SUCCESS) {
		if (keyslot) {
			if (ctx_mark_key_loaded(hContext, *phKeyTCSI)) {
				LogError("Error marking key as loaded");
				return TCSERR(TSS_E_INTERNAL_ERROR);
			}
			return TSS_SUCCESS;
		}
	}
	/*********************************************************************
	 *	The first thing to do in this func is setup all the info and make sure
	 *		that we get it all from either the keyfile or the keyCache
	 *		also, it's important to return if the key is already loaded
	 ***********************************************************************/
	LogDebugFn("calling ps_get_key_by_uuid");
	if (ps_get_key_by_uuid(KeyUUID, keyBlob, &blobSize))
		return TCSERR(TSS_E_PS_KEY_NOTFOUND);
	/* convert UINT16 to UIN32 */
	keySize = blobSize;

	LogDebugFn("calling getParentUUIDByUUID");
	/*---	Get my parent's UUID.  Since My key is registered, my parent should be as well. */
	if ((result = getParentUUIDByUUID(KeyUUID, &parentUuid)))
		return TCSERR(TCS_E_KM_LOADFAILED);

	if ((result = TCSP_LoadKeyByUUID_Internal(hContext, &parentUuid,
						  pLoadKeyInfo, &parentTCSKeyHandle)))
		return result;

	LogDebugFn("calling LoadKeyByBlob_Internal");
	/*******************************************************
	 * If no errors have happend up till now, then the parent is loaded and ready for use.
	 * The parent's TCS Handle should be in parentTCSKeyHandle.
	 ******************************************************/
	if ((result = LoadKeyByBlob_Internal(ordinal, hContext, parentTCSKeyHandle,
					     keySize, keyBlob,
					     NULL,
					     phKeyTCSI, &keyslot))) {
		LogDebugFn("LoadKeyByBlob_Internal returned 0x%x", result);
		if (result == TCPA_E_AUTHFAIL && pLoadKeyInfo) {
			BYTE blob[1000];

			/* set up a load key info struct */
			memcpy(&pLoadKeyInfo->parentKeyUUID, &parentUuid, sizeof(TSS_UUID));
			memcpy(&pLoadKeyInfo->keyUUID, KeyUUID, sizeof(TSS_UUID));

			/* calculate the paramDigest */
			offset = 0;
			LoadBlob_UINT32(&offset, ordinal, blob);
			LoadBlob(&offset, keySize, blob, keyBlob);
			if (Hash(TSS_HASH_SHA1, offset, blob,
				 (BYTE *)&pLoadKeyInfo->paramDigest.digest))
				result = TCSERR(TSS_E_INTERNAL_ERROR);

			result = TCSERR(TCS_E_KM_LOADFAILED);
		}
	}

	return result;
}
Esempio n. 17
0
void GroupNodeDef_Init()
{
	str4cpy(gGroupNodeDef.mName, "group");
	gGroupNodeDef.mHash = Hash(gGroupNodeDef.mName);
	gGroupNodeDef.mAllocSize = sizeof(Group);
}
Esempio n. 18
0
void ThreadSendAlert()
{
    if (!mapArgs.count("-sendalert") && !mapArgs.count("-printalert"))
        return;

    MilliSleep(60*1000); // Wait a minute so we get connected

    //
    // Alerts are relayed around the network until nRelayUntil, flood
    // filling to every node.
    // After the relay time is past, new nodes are told about alerts
    // when they connect to peers, until either nExpiration or
    // the alert is cancelled by a newer alert.
    // Nodes never save alerts to disk, they are in-memory-only.
    //
    CAlert alert;
    alert.nRelayUntil   = GetTime() + 15 * 60;
    alert.nExpiration   = GetTime() + 365 * 60 * 60;
    alert.nID           = 1000;  // use https://github.com/zcash/zcash/wiki/specification#assigned-numbers to keep track of alert IDs
    alert.nCancel       = 0;   // cancels previous messages up to this ID number

    // These versions are protocol versions
    // 170002 : 1.0.0
    alert.nMinVer       = 170002;
    alert.nMaxVer       = 170002;

    //
    // main.cpp: 
    //  1000 for Misc warnings like out of disk space and clock is wrong
    //  2000 for longer invalid proof-of-work chain 
    //  Higher numbers mean higher priority
    //  4000 or higher will put the RPC into safe mode
    alert.nPriority     = 5000;
    alert.strComment    = "";
    alert.strStatusBar  = "URGENT: Upgrade required: see https://z.cash";
    alert.strRPCError   = "URGENT: Upgrade required: see https://z.cash";

    // Set specific client version/versions here. If setSubVer is empty, no filtering on subver is done:
    // alert.setSubVer.insert(std::string("/MagicBean:0.7.2/"));

    // Sign
    const CChainParams& chainparams = Params();
    std::string networkID = chainparams.NetworkIDString();
    bool fIsTestNet = networkID.compare("test") == 0;
    std::vector<unsigned char> vchTmp(ParseHex(fIsTestNet ? pszTestNetPrivKey : pszPrivKey));
    CPrivKey vchPrivKey(vchTmp.begin(), vchTmp.end());

    CDataStream sMsg(SER_NETWORK, CLIENT_VERSION);
    sMsg << *(CUnsignedAlert*)&alert;
    alert.vchMsg = std::vector<unsigned char>(sMsg.begin(), sMsg.end());
    CKey key;
    if (!key.SetPrivKey(vchPrivKey, false))
    {
        printf("ThreadSendAlert() : key.SetPrivKey failed\n");
        return;
    }
    if (!key.Sign(Hash(alert.vchMsg.begin(), alert.vchMsg.end()), alert.vchSig))
    {
        printf("ThreadSendAlert() : key.Sign failed\n");
        return;
    }

    // Test
    CDataStream sBuffer(SER_NETWORK, CLIENT_VERSION);
    sBuffer << alert;
    CAlert alert2;
    sBuffer >> alert2;
    if (!alert2.CheckSignature(chainparams.AlertKey()))
    {
        printf("ThreadSendAlert() : CheckSignature failed\n");
        return;
    }
    assert(alert2.vchMsg == alert.vchMsg);
    assert(alert2.vchSig == alert.vchSig);
    alert.SetNull();
    printf("\nThreadSendAlert:\n");
    printf("hash=%s\n", alert2.GetHash().ToString().c_str());
    printf("%s\n", alert2.ToString().c_str());
    printf("vchMsg=%s\n", HexStr(alert2.vchMsg).c_str());
    printf("vchSig=%s\n", HexStr(alert2.vchSig).c_str());

    // Confirm
    if (!mapArgs.count("-sendalert"))
        return;
    while (vNodes.size() < 1 && !ShutdownRequested())
        MilliSleep(500);
    if (ShutdownRequested())
        return;

    // Send
    printf("ThreadSendAlert() : Sending alert\n");
    int nSent = 0;
    {
        LOCK(cs_vNodes);
        BOOST_FOREACH(CNode* pnode, vNodes)
        {
            if (alert2.RelayTo(pnode))
            {
                printf("ThreadSendAlert() : Sent alert to %s\n", pnode->addr.ToString().c_str());
                nSent++;
            }
        }
    }
    printf("ThreadSendAlert() : Alert sent to %d nodes\n", nSent);
}
Esempio n. 19
0
CMasternodePaymentDB::ReadResult CMasternodePaymentDB::Read(CMasternodePayments& objToLoad, bool fDryRun)
{

    int64_t nStart = GetTimeMillis();
    // open input file, and associate with CAutoFile
    FILE *file = fopen(pathDB.string().c_str(), "rb");
    CAutoFile filein(file, SER_DISK, CLIENT_VERSION);
    if (filein.IsNull())
    {
        error("%s : Failed to open file %s", __func__, pathDB.string());
        return FileError;
    }

    // use file size to size memory buffer
    int fileSize = boost::filesystem::file_size(pathDB);
    int dataSize = fileSize - sizeof(uint256);
    // Don't try to resize to a negative number if file is small
    if (dataSize < 0)
        dataSize = 0;
    vector<unsigned char> vchData;
    vchData.resize(dataSize);
    uint256 hashIn;

    // read data and checksum from file
    try {
        filein.read((char *)&vchData[0], dataSize);
        filein >> hashIn;
    }
    catch (std::exception &e) {
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return HashReadError;
    }
    filein.fclose();

    CDataStream ssObj(vchData, SER_DISK, CLIENT_VERSION);

    // verify stored checksum matches input data
    uint256 hashTmp = Hash(ssObj.begin(), ssObj.end());
    if (hashIn != hashTmp)
    {
        error("%s : Checksum mismatch, data corrupted", __func__);
        return IncorrectHash;
    }


    unsigned char pchMsgTmp[4];
    std::string strMagicMessageTmp;
    try {
        // de-serialize file header (masternode cache file specific magic message) and ..
        ssObj >> strMagicMessageTmp;

        // ... verify the message matches predefined one
        if (strMagicMessage != strMagicMessageTmp)
        {
            error("%s : Invalid masternode payement cache magic message", __func__);
            return IncorrectMagicMessage;
        }


        // de-serialize file header (network specific magic number) and ..
        ssObj >> FLATDATA(pchMsgTmp);

        // ... verify the network matches ours
        if (memcmp(pchMsgTmp, Params().MessageStart(), sizeof(pchMsgTmp)))
        {
            error("%s : Invalid network magic number", __func__);
            return IncorrectMagicNumber;
        }

        // de-serialize data into CMasternodePayments object
        ssObj >> objToLoad;
    }
    catch (std::exception &e) {
        objToLoad.Clear();
        error("%s : Deserialize or I/O error - %s", __func__, e.what());
        return IncorrectFormat;
    }

    LogPrintf("Loaded info from mnpayments.dat  %dms\n", GetTimeMillis() - nStart);
    LogPrintf("  %s\n", objToLoad.ToString());
    if(!fDryRun) {
        LogPrintf("Masternode payments manager - cleaning....\n");
        objToLoad.CleanPaymentList();
        LogPrintf("Masternode payments manager - result:\n");
        LogPrintf("  %s\n", objToLoad.ToString());
    }

    return Ok;
}
Esempio n. 20
0
TDBTSettingHandle CSettings::FindSetting(TDBTSettingDescriptor & Descriptor)
{
	if (Descriptor.Flags & DBT_SDF_FoundValid)
		return Descriptor.FoundHandle;

	uint32_t namelength = static_cast<uint32_t>( strlen(Descriptor.pszSettingName) );
	uint32_t namehash;

	if (Descriptor.Flags & DBT_SDF_HashValid)
	{
		namehash = Descriptor.Hash;
	} else {
		namehash = Hash(Descriptor.pszSettingName, namelength);
		Descriptor.Hash = namehash;
		Descriptor.Flags = Descriptor.Flags | DBT_SDF_HashValid;
	}

	Descriptor.Flags = Descriptor.Flags & ~DBT_SDF_FoundValid;

	CSettingsTree * tree;
	TDBTSettingHandle res = 0;
	CBlockManager * file = &m_BlockManagerPri;
	if (Descriptor.Entity == 0)
		file = &m_BlockManagerSet;

	CBlockManager::ReadTransaction trans(*file);

	if ((Descriptor.Entity == 0) || (Descriptor.Options == 0))
	{
		tree = getSettingsTree(Descriptor.Entity);
		if (tree == NULL)
			return DBT_INVALIDPARAM;

		res = tree->_FindSetting(namehash, Descriptor.pszSettingName, namelength);

		if (res)
		{
			Descriptor.FoundInEntity = Descriptor.Entity;
			Descriptor.FoundHandle = res;
			Descriptor.Flags = Descriptor.Flags | DBT_SDF_FoundValid;
		}

		if (Descriptor.Entity == 0)
			res = res | cSettingsFileFlag;

		return res;
	}

	uint32_t cf = m_Entities.getFlags(Descriptor.Entity);
	if (cf == DBT_INVALIDPARAM)
		return DBT_INVALIDPARAM;

	// search the setting
	res = 0;

	TDBTEntityIterFilter f;
	f.cbSize = sizeof(f);
	if (cf & DBT_NF_IsGroup)
	{
		f.fDontHasFlags = 0;
		f.fHasFlags = DBT_NF_IsGroup;
	} else {
		f.fDontHasFlags = DBT_NF_IsGroup;
		f.fHasFlags = 0;
	}
	f.Options = Descriptor.Options;

	TDBTEntityIterationHandle i = m_Entities.IterationInit(f, Descriptor.Entity);
	if ((i == DBT_INVALIDPARAM) || (i == 0))
		return DBT_INVALIDPARAM;

	TDBTEntityHandle e = m_Entities.IterationNext(i);
	TDBTEntityHandle found = 0;
	while ((res == 0) && (e != 0))
	{
		tree = getSettingsTree(e);
		if (tree)
		{
			res = tree->_FindSetting(namehash, Descriptor.pszSettingName, namelength);
			found = e;
		}

		e = m_Entities.IterationNext(i);
	}

	m_Entities.IterationClose(i);

	if (res)
	{
		Descriptor.FoundInEntity = found;
		Descriptor.FoundHandle = res;
		Descriptor.Flags = Descriptor.Flags | DBT_SDF_FoundValid;
	}

	return res;
}
Esempio n. 21
0
int main(int argc, char* argv[])
{
  TEnv Env(argc, argv);
  TStr PrefixPath = Env.GetArgs() > 1 ? Env.GetArg(1) : TStr("");

  double ts1 = Tick();
  TTableContext Context;
  TVec<PTable> NodeTblV = TVec<PTable>();
  TVec<PTable> EdgeTblV = TVec<PTable>();
  Schema NodeSchema = Schema();
  Schema EdgeSchema = Schema();
  LoadFlickrTables(PrefixPath, Context, NodeTblV, NodeSchema, EdgeTblV, EdgeSchema);

  double ts2 = Tick();

  int ExpectedSz = 0;
  for (TVec<PTable>::TIter it = NodeTblV.BegI(); it < NodeTblV.EndI(); it++) {
    PTable Table = *it;
    ExpectedSz += Table->GetNumRows();
  }

  THash<TStr, TInt> Hash(ExpectedSz);
  TStrV OriNIdV(ExpectedSz);

  MergeNodeTables(NodeTblV, NodeSchema, Hash, OriNIdV);
  PTable EdgeTable = MergeEdgeTables(EdgeTblV, EdgeSchema, Hash, Context);

  double ts3 = Tick();
  TStrV V;
  TStrV VE;
  VE.Add(EdgeSchema.GetVal(2).GetVal1());
  PNEANet Graph = TSnap::ToNetwork<PNEANet>(EdgeTable, EdgeSchema.GetVal(0).GetVal1(), EdgeSchema.GetVal(1).GetVal1(),
						V, V, VE, aaLast);
  double ts4 = Tick();

  //int nExps = 1;
  int nExps = 40;
  TIntFltH PageRankResults;
  for (int i = 0; i < nExps; i++) {
    PageRankResults = TIntFltH(ExpectedSz);
#ifdef USE_OPENMP
    TSnap::GetWeightedPageRankMP2(Graph, PageRankResults, EdgeSchema.GetVal(2).GetVal1(), 0.849999999999998, 0.0001, 10);
#else
    TSnap::GetWeightedPageRank(Graph, PageRankResults, EdgeSchema.GetVal(2).GetVal1(), 0.849999999999998, 0.0001, 10);
#endif
  }
  double ts5 = Tick();

  PSOut ResultOut = TFOut::New(PrefixPath + TStr("page-rank-results.tsv"));
  for (TIntFltH::TIter it = PageRankResults.BegI(); it < PageRankResults.EndI(); it++) {
    ResultOut->PutStrFmtLn("%s\t%f9", OriNIdV[it.GetKey()].CStr(), it.GetDat().Val);
  }
  double ts6 = Tick();

  bool isPar = false;
#ifdef USE_OPENMP
  isPar = true;
#endif

//  PSOut FeaturesOut = TFOut::New(PrefixPath + "features.txt");
//  FeaturesOut->PutStrFmtLn("Photo %d", PPhotoTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Users %d", PUserTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Tags %d", PTagTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comments %d", PCommentTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Locations %d", PLocationTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Owner %d", PPhotoOwnerTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Comment %d", PPhotoCommentTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Photo - Location %d", PPhotoLocationTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comment - User %d", PCommentUserTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Comment - User %d", PCommentUserTbl->GetNumRows().Val);
////  FeaturesOut->PutStrFmtLn("Photo - Tagger %d", PPhotoTaggerTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Tagger - Tag %d", PTaggerTagTbl->GetNumRows().Val);
//  FeaturesOut->PutStrFmtLn("Total number of nodes = %d", Graph->GetNodes());
//  FeaturesOut->PutStrFmtLn("Total number of edges = %d", Graph->GetEdges());

  PSOut TimeOut = TFOut::New(PrefixPath + TStr("time.txt"), true);
  TimeOut->PutStrFmtLn("Experiment Weighted - %s - %s", PrefixPath.CStr(), (isPar ? "Parallel" : "Sequential"));
  TimeOut->PutStrFmtLn("Input Time = %f", GetCPUTimeUsage(ts1, ts2));
  TimeOut->PutStrFmtLn("Preprocessing Time = %f", GetCPUTimeUsage(ts2, ts3));
  TimeOut->PutStrFmtLn("Conversion Time = %f", GetCPUTimeUsage(ts3, ts4));
  TimeOut->PutStrFmtLn("Computing Time = %f", GetCPUTimeUsage(ts4, ts5)/nExps);
  TimeOut->PutStrFmtLn("Output Time = %f", GetCPUTimeUsage(ts5, ts6));

  return 0;
}
Esempio n. 22
0
TDBTSettingHandle CSettings::WriteSetting(TDBTSetting & Setting, TDBTSettingHandle hSetting)
{
	uint32_t sig = cSettingSignature;
	uint32_t size = 0;
	TSetting * setting = NULL;

	if (!hSetting && !(Setting.Descriptor && Setting.Descriptor->Entity))
		return DBT_INVALIDPARAM;

	CBlockManager * file = &m_BlockManagerPri;
	bool fileflag = false;

	if (hSetting & cSettingsFileFlag)
	{
		file = &m_BlockManagerSet;
		hSetting = hSetting & ~cSettingsFileFlag;
		fileflag = true;
	}

	CSettingsTree * tree = NULL;

	if (hSetting == 0)
	{
		if (Setting.Descriptor->Entity == 0)
		{
			file = &m_BlockManagerSet;
			fileflag = true;
		}

		CBlockManager::WriteTransaction trans(*file);
		
		if ((Setting.Descriptor) && (Setting.Descriptor->pszSettingName)) // setting needs a name
		{
			tree = getSettingsTree(Setting.Descriptor->Entity);
			_EnsureModuleExists(Setting.Descriptor->pszSettingName);
		}

	} else {
		CBlockManager::WriteTransaction trans(*file);

		setting = file->ReadBlock<TSetting>(hSetting, size, sig);

		if (setting) // check if hSetting is valid
			tree = getSettingsTree(setting->Entity);
	}

	if (tree == NULL)
		return DBT_INVALIDPARAM;

	uint32_t blobsize = 0;

	if (Setting.Type & DBT_STF_VariableLength)
	{
		switch (Setting.Type)
		{
			case DBT_ST_ANSI: case DBT_ST_UTF8:
				{
					if (Setting.Value.Length == 0)
						blobsize = static_cast<uint32_t>(strlen(Setting.Value.pAnsi) + 1);
					else
						blobsize = Setting.Value.Length;
				} break;
			case DBT_ST_WCHAR:
				{
					if (Setting.Value.Length == 0)
						blobsize = sizeof(wchar_t) * static_cast<uint32_t>(wcslen(Setting.Value.pWide) + 1);
					else
						blobsize = sizeof(wchar_t) * (Setting.Value.Length);
				} break;
			default:
				blobsize = Setting.Value.Length;
				break;
		}
	}

	size = sizeof(TSetting) + static_cast<uint32_t>(strlen(Setting.Descriptor->pszSettingName)) + 1 + blobsize;

	if (hSetting == 0) // create new setting
	{
		setting = file->CreateBlock<TSetting>(hSetting, cSettingSignature, size);

		setting->Entity = Setting.Descriptor->Entity;
		setting->Flags = 0;
		setting->AllocSize = blobsize;

		if (Setting.Descriptor && (Setting.Descriptor->Flags & DBT_SDF_HashValid))
		{
			tree->_AddSetting(Setting.Descriptor->Hash, hSetting);
		} else  {
			tree->_AddSetting(Hash(Setting.Descriptor->pszSettingName, static_cast<uint32_t>(strlen(Setting.Descriptor->pszSettingName))), hSetting);
		}

	} else {
		uint32_t tmp = 0;
		setting = file->ReadBlock<TSetting>(hSetting, tmp, sig);

		if (((Setting.Type & DBT_STF_VariableLength) == 0) && (setting->Type & DBT_STF_VariableLength))
		{ // shrink setting (variable size->fixed size)
			file->ResizeBlock(hSetting, setting, size);
		}

		if ((Setting.Type & DBT_STF_VariableLength) && ((setting->Type & DBT_STF_VariableLength) == 0))
		{ // trick it
			setting->AllocSize = 0;
		}
	}

	setting->Type = Setting.Type;
	setting->NameLength = static_cast<uint32_t>(strlen(Setting.Descriptor->pszSettingName));
	memcpy(setting + 1, Setting.Descriptor->pszSettingName, setting->NameLength + 1);

	if (Setting.Type & DBT_STF_VariableLength)
	{
		setting->AllocSize = file->ResizeBlock(hSetting, setting, size) -
				                (sizeof(TSetting) + setting->NameLength + 1);

		setting->BlobLength = blobsize;

		memcpy(reinterpret_cast<uint8_t*>(setting + 1) + setting->NameLength + 1, Setting.Value.pBlob, blobsize);
	} else {
		memset(&(setting->Value), 0, sizeof(setting->Value));
		switch (Setting.Type)
		{
			case DBT_ST_BOOL:
				setting->Value.Bool = Setting.Value.Bool; break;
			case DBT_ST_BYTE: case DBT_ST_CHAR:
				setting->Value.Byte = Setting.Value.Byte; break;
			case DBT_ST_SHORT: case DBT_ST_WORD:
				setting->Value.Short = Setting.Value.Short; break;
			case DBT_ST_INT: case DBT_ST_DWORD:
				setting->Value.Int = Setting.Value.Int; break;
			default:
				setting->Value.QWord = Setting.Value.QWord; break;
		}
	}
	
	file->UpdateBlock(hSetting);

	if (fileflag)
		hSetting = hSetting | cSettingsFileFlag;

	return hSetting;
}
Esempio n. 23
0
void InsertHashTable(char *key, int value)
{
	int addr = Hash(key);
	while (vertex_hash_table[addr] != -1) addr = (addr + 1) % hash_table_size;
	vertex_hash_table[addr] = value;
}
void Graph_Ctor(World *inWorld, GraphDef *inGraphDef, Graph *graph, sc_msg_iter *msg,bool argtype)//true for normal args , false for setn type args
{
    //scprintf("->Graph_Ctor\n");

    // hit the memory allocator only once.
    char *memory = (char*)graph + sizeof(Graph);

    // allocate space for children
    int numUnits = inGraphDef->mNumUnitSpecs;
    graph->mNumUnits = numUnits;
    inWorld->mNumUnits += numUnits;
    inWorld->mNumGraphs ++;

    graph->mUnits = (Unit**)memory;
    memory += inGraphDef->mUnitsAllocSize;

    // set calc func
    graph->mNode.mCalcFunc = (NodeCalcFunc)&Graph_FirstCalc;

    // allocate wires
    graph->mNumWires = inGraphDef->mNumWires;
    graph->mWire = (Wire*)memory;
    memory += inGraphDef->mWiresAllocSize;

    graph->mNumCalcUnits = inGraphDef->mNumCalcUnits;
    graph->mCalcUnits = (Unit**)memory;
    memory += inGraphDef->mCalcUnitsAllocSize;

    // initialize controls
    int numControls = inGraphDef->mNumControls;
    graph->mNumControls = numControls;
    graph->mControls = (float*)memory;
    memory += inGraphDef->mControlAllocSize;

    graph->mMapControls = (float**)memory;
    memory += inGraphDef->mMapControlsAllocSize;

    graph->mControlRates = (int*)memory;
    memory += inGraphDef->mMapControlRatesAllocSize;

    {
        float*  graphControls = graph->mControls;
        float*  initialControlValues = inGraphDef->mInitialControlValues;
        float** graphMapControls = graph->mMapControls;
        /* add */
        int* graphControlRates = graph->mControlRates;
        for (int i=0; i<numControls; ++i, ++graphControls) {
            *graphControls = initialControlValues[i];
            graphMapControls[i] = graphControls;
            /* add */
            graphControlRates[i] = 0;  // init to 0 for now... control bus is 1, audio is 2
        }
    }

    // set controls
    //if argtype == true -> normal args as always
    //if argtype == false -> setn type args
    if(argtype) {
        while( msg->remain()>=8) {
            int i = 0;
            int loop = 0;
            if (msg->nextTag('i') == 's') {
                int32* name = msg->gets4();
                int32 hash = Hash(name);
                do {
                    switch (msg->nextTag('f') ) {
                    case  'f' :
                    case  'i' :
                    {
                        float32 value = msg->getf();
                        Graph_SetControl(graph, hash, name, i, value);
                        break;
                    }
                    case 's' :
                    {
                        const char* string = msg->gets();
                        if ( *string == 'c') {
                            int bus = sc_atoi(string+1);
                            Graph_MapControl(graph, hash, name, i, bus);
                        } else {
                            if (*string == 'a') {
                                int bus = sc_atoi(string+1);
                                Graph_MapAudioControl(graph, hash, name, i, bus);
                            }
                        }
                        break;
                    }
                    case ']':
                        msg->count++;
                        loop -= 1;
                        break;
                    case '[':
                        msg->count++;
                        loop += 1;
                        i -= 1;
                        break;
                    }
                    ++i;
                }
                while (loop);
            } else {
                int32 index = msg->geti();
                do {
                    switch (msg->nextTag('f') ) {
                    case  'f' :
                    case  'i' :
                    {
                        float32 value = msg->getf();
                        Graph_SetControl(graph, index + i, value);
                        break;
                    }
                    case 's' :
                    {
                        const char* string = msg->gets();
                        if ( *string == 'c') {
                            int bus = sc_atoi(string+1);
                            Graph_MapControl(graph, index + i, bus);
                        } else {
                            if (*string == 'a') {
                                int bus = sc_atoi(string+1);
                                Graph_MapAudioControl(graph, index + i, bus);
                            }
                        }
                        break;
                    }
                    case ']':
                        msg->count++;
                        loop -= 1;
                        break;
                    case '[':
                        msg->count++;
                        loop += 1;
                        i -= 1;
                        break;
                    }
                    ++i;
                }
                while (loop);
            }
        }

    }


    //{
//	    while( msg->remain()>=8) {
//		int i = 0;
//		int loop = 0;
//		if (msg->nextTag('i') == 's') {
//		    int32* name = msg->gets4();
//		    int32 hash = Hash(name);
//		    if (msg->nextTag('f') == '[' ) {
//			    msg->count++;
//			    loop = 1;
//		    }
//		    do {
//			if (msg->nextTag('f') == 's' ) {
//			    const char* string = msg->gets();
//			    if ( *string == 'c') {
//				int bus = sc_atoi(string+1);
//				Graph_MapControl(graph, hash, name, i, bus);
//			    }
//			} else {
//			    if (msg->nextTag('f') == ']' ) {
//				msg->count++;
//				loop = 0;
//			    } else {
//				float32 value = msg->getf();
//				Graph_SetControl(graph, hash, name, i, value);
//			    }
//			}
//			++i;
//		    }
//		    while (loop);
//		} else {
//		    int32 index = msg->geti();
//		    if (msg->nextTag('f') == '[' ) {
//			msg->count++;
//			loop = 1;
//		    }
//		    do {
//			if (msg->nextTag('f') == 's') {
//			    const char* string = msg->gets();
//			    if (*string == 'c') {
//				int bus = sc_atoi(string+1);
//				Graph_MapControl(graph, index + i, bus);
//			    }
//			} else {
//			    if (msg->nextTag('f') == ']' ) {
//				msg->count++;
//				loop = 0;
//			    } else {
//				float32 value = msg->getf();
//				Graph_SetControl(graph, index + i, value);
//			    }
//			}
//			++i;
//		    }
//		    while (loop);
//		}
//	    }
//
//	}
    else {

        while (msg->remain()) {
            if (msg->nextTag('i') == 's') {
                int32* name = msg->gets4();
                int32 hash = Hash(name);
                int32 n = msg->geti();
                for (int i=0; msg->remain() && i<n; ++i) {
                    if (msg->nextTag('f') == 's') {
                        const char* string = msg->gets();
                        if (*string == 'c') {
                            int bus = sc_atoi(string+1);
                            Graph_MapControl(graph, hash, name, i, bus);
                            //Node_MapControl(node, hash, name, i, bus);
                        } else {
                            if (*string == 'a') {
                                int bus = sc_atoi(string+1);
                                Graph_MapAudioControl(graph, hash, name, i, bus);
                            }
                        }
                    } else {
                        float32 value = msg->getf();
                        Graph_SetControl(graph, hash, name, i, value);
                        //Node_SetControl(node, hash, name, i, value);
                    }
                }
            } else {
                int32 index = msg->geti();
                int32 n = msg->geti();
                for (int i=0; msg->remain() && i<n; ++i) {
                    if (msg->nextTag('f') == 's') {
                        const char* string = msg->gets();
                        if (*string == 'c') {
                            int bus = sc_atoi(string+1);
                            Graph_MapControl(graph, index+i, bus);
                            //Node_MapControl(node, index+i, bus);
                        } else {
                            if (*string == 'a') {
                                int bus = sc_atoi(string+1);
                                Graph_MapAudioControl(graph, index + i, bus);
                            }
                        }
                    } else {
                        float32 value = msg->getf();
                        Graph_SetControl(graph, index+i, value);
                        //Node_SetControl(node, index+i, value);
                    }
                }
            }
        }
    }

    // set up scalar values
    Wire *graphWires = graph->mWire;
    int numConstants = inGraphDef->mNumConstants;
    {
        float *constants = inGraphDef->mConstants;
        Wire *wire = graphWires;
        for (int i=0; i<numConstants; ++i, ++wire) {
            wire->mFromUnit = 0;
            wire->mCalcRate = calc_ScalarRate;
            wire->mBuffer = &wire->mScalarValue;
            wire->mScalarValue = constants[i];
        }
    }

    graph->mSampleOffset = inWorld->mSampleOffset;
    graph->mSubsampleOffset = inWorld->mSubsampleOffset;
    graph->mRGen = inWorld->mRGen; // defaults to rgen zero.

    graph->mLocalAudioBusUnit = NULL;
    graph->mLocalControlBusUnit = NULL;

    graph->localBufNum = 0;
    graph->localMaxBufNum = 0; // this is set from synth

    // initialize units
    //scprintf("initialize units\n");
    Unit** calcUnits = graph->mCalcUnits;
    Unit** graphUnits = graph->mUnits;
    int calcCtr=0;

    float *bufspace = inWorld->hw->mWireBufSpace;
    int wireCtr = numConstants;
    UnitSpec *unitSpec = inGraphDef->mUnitSpecs;
    for (int i=0; i<numUnits; ++i, ++unitSpec) {
        // construct unit from spec
        Unit *unit = Unit_New(inWorld, unitSpec, memory);

        // set parent
        unit->mParent = graph;
        unit->mParentIndex = i;

        graphUnits[i] = unit;

        {
            // hook up unit inputs
            //scprintf("hook up unit inputs\n");
            InputSpec *inputSpec = unitSpec->mInputSpec;
            Wire** unitInput = unit->mInput;
            float** unitInBuf = unit->mInBuf;
            int numInputs = unitSpec->mNumInputs;
            for (int j=0; j<numInputs; ++j, ++inputSpec) {
                Wire *wire = graphWires + inputSpec->mWireIndex;
                unitInput[j] = wire;
                unitInBuf[j] = wire->mBuffer;
            }
        }

        {
            // hook up unit outputs
            //scprintf("hook up unit outputs\n");
            Wire** unitOutput = unit->mOutput;
            float** unitOutBuf = unit->mOutBuf;
            int numOutputs = unitSpec->mNumOutputs;
            Wire *wire = graphWires + wireCtr;
            wireCtr += numOutputs;
            int unitCalcRate = unit->mCalcRate;
            if (unitCalcRate == calc_FullRate) {
                OutputSpec *outputSpec = unitSpec->mOutputSpec;
                for (int j=0; j<numOutputs; ++j, ++wire, ++outputSpec) {
                    wire->mFromUnit = unit;
                    wire->mCalcRate = calc_FullRate;
                    wire->mBuffer = bufspace + outputSpec->mBufferIndex;
                    unitOutput[j] = wire;
                    unitOutBuf[j] = wire->mBuffer;
                }
                calcUnits[calcCtr++] = unit;
            } else {
                for (int j=0; j<numOutputs; ++j, ++wire) {
                    wire->mFromUnit = unit;
                    wire->mCalcRate = unitCalcRate;
                    wire->mBuffer = &wire->mScalarValue;
                    unitOutput[j] = wire;
                    unitOutBuf[j] = wire->mBuffer;
                }
                if (unitCalcRate == calc_BufRate) {
                    calcUnits[calcCtr++] = unit;
                }
            }
        }
    }

    inGraphDef->mRefCount ++ ;
}
void SignVerifyMessageDialog::on_signMessageButton_SM_clicked()
{
    /* Clear old signature to ensure users don't get confused on error with an old signature displayed */
    ui->signatureOut_SM->clear();

    CBitcoinAddress addr(ui->addressIn_SM->text().toStdString());
    if (!addr.IsValid())
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address is invalid.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }
    CKeyID keyID;
    if (!addr.GetKeyID(keyID))
    {
        ui->addressIn_SM->setValid(false);
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("The entered address does not refer to a key.") + QString(" ") + tr("Please check the address and try again."));
        return;
    }

    WalletModel::UnlockContext ctx(model->requestUnlock());
    if (!ctx.isValid())
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Wallet unlock was cancelled."));
        return;
    }

    CKey key;
    CKey tkey;
    bool fwalletFound=false;
    BOOST_FOREACH(const wallet_map::value_type& item, pWalletManager->GetWalletMap())
    {

      pwalletMain = pWalletManager->GetWallet(item.first.c_str()).get();

      if (!pwalletMain->GetKey(keyID, tkey))
          qDebug() << "Address Not Found For " + QString(pwalletMain->strWalletFile.c_str());
      else
      {
          if (!pwalletMain->GetKey(keyID, key))
          {
              ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
              ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
              return;
          }
          fwalletFound=true;
      }
    }
    if (!fwalletFound)
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(tr("Private key for the entered address is not available."));
        return;
    }

    CDataStream ss(SER_GETHASH, 0);
    ss << strMessageMagic;
    ss << ui->messageIn_SM->document()->toPlainText().toStdString();

    std::vector<unsigned char> vchSig;
    if (!key.SignCompact(Hash(ss.begin(), ss.end()), vchSig))
    {
        ui->statusLabel_SM->setStyleSheet("QLabel { color: red; }");
        ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signing failed.") + QString("</nobr>"));
        return;
    }

    ui->statusLabel_SM->setStyleSheet("QLabel { color: green; }");
    ui->statusLabel_SM->setText(QString("<nobr>") + tr("Message signed.") + QString("</nobr>"));

    ui->signatureOut_SM->setText(QString::fromStdString(EncodeBase64(&vchSig[0], vchSig.size())));
}
Esempio n. 26
0
weak Atom
MakeAtom(const char *string, unsigned len, int makeit)
{
    AtomListPtr	a;
    int		hash;
    int		h = 0;
    int		r;

    hash = Hash (string, len);
    if (hashTable)
    {
    	h = hash & hashMask;
	if (hashTable[h])
	{
	    if (hashTable[h]->hash == hash && hashTable[h]->len == len &&
	    	NameEqual (hashTable[h]->name, string, len))
	    {
	    	return hashTable[h]->atom;
	    }
	    r = (hash % rehash) | 1;
	    for (;;)
	    {
		h += r;
		if (h >= hashSize)
		    h -= hashSize;
		if (!hashTable[h])
		    break;
		if (hashTable[h]->hash == hash && hashTable[h]->len == len &&
		    NameEqual (hashTable[h]->name, string, len))
		{
		    return hashTable[h]->atom;
		}
	    }
    	}
    }
    if (!makeit)
	return None;
    a = malloc (sizeof (AtomListRec) + len + 1);
    if (a == NULL) {
	fprintf(stderr, "MakeAtom(): Error: Couldn't allocate AtomListRec"
		" (%ld)\n", (unsigned long)sizeof (AtomListRec) + len + 1);
	return None;
    }
    a->name = (char *) (a + 1);
    a->len = len;
    strncpy (a->name, string, len);
    a->name[len] = '\0';
    a->atom = ++lastAtom;
    a->hash = hash;
    if (hashUsed >= hashSize / 2)
    {
	ResizeHashTable ();
	h = hash & hashMask;
	if (hashTable[h])
	{
	    r = (hash % rehash) | 1;
	    do {
		h += r;
		if (h >= hashSize)
		    h -= hashSize;
	    } while (hashTable[h]);
	}
    }
    hashTable[h] = a;
    hashUsed++;
    if (reverseMapSize <= a->atom) {
	if (!ResizeReverseMap())
	    return None;
    }
    reverseMap[a->atom] = a;
    return a->atom;
}
Esempio n. 27
0
void PointerFreeHashGrid::ReHash(float currentPhotonRadius2) {
#else
void PointerFreeHashGrid::ReHash(float /*currentPhotonRadius2*/) {
#endif

	const unsigned int hitPointsCount = engine->hitPointTotal;
	const BBox &hpBBox = hitPointsbbox;

	// Calculate the size of the grid cell
#if defined USE_SPPMPA || defined USE_PPMPA
	float maxPhotonRadius2 = currentPhotonRadius2;
#else
	float maxPhotonRadius2 = 0.f;
	for (unsigned int i = 0; i < hitPointsCount; ++i) {
		HitPointStaticInfo *ihp = &workerHitPointsInfo[i];
		HitPoint *hp = &workerHitPoints[i];

		if (ihp->type == SURFACE)
		maxPhotonRadius2 = Max(maxPhotonRadius2, hp->accumPhotonRadius2);
	}

#endif
	const float cellSize = sqrtf(maxPhotonRadius2) * 2.f;
	//std::cerr << "Hash grid cell size: " << cellSize << std::endl;
	invCellSize = 1.f / cellSize;

	// TODO: add a tunable parameter for hashgrid size
	//hashGridSize = hitPointsCount;
	if (!hashGrid) {
		hashGrid = new std::list<uint>*[hashGridSize];

		for (unsigned int i = 0; i < hashGridSize; ++i)
			hashGrid[i] = NULL;
	} else {
		for (unsigned int i = 0; i < hashGridSize; ++i) {
			delete hashGrid[i];
			hashGrid[i] = NULL;
		}
	}

	//std::cerr << "Building hit points hash grid:" << std::endl;
	//std::cerr << "  0k/" << hitPointsCount / 1000 << "k" << std::endl;
	//unsigned int maxPathCount = 0;
	double lastPrintTime = WallClockTime();
	unsigned long long entryCount = 0;

	for (unsigned int i = 0; i < hitPointsCount; ++i) {

		if (WallClockTime() - lastPrintTime > 2.0) {
			std::cerr << "  " << i / 1000 << "k/" << hitPointsCount / 1000 << "k" << std::endl;
			lastPrintTime = WallClockTime();
		}

		//HitPointInfo *hp = engine->GetHitPointInfo(i);
		HitPointStaticInfo *hp = &workerHitPointsInfo[i];

		if (hp->type == SURFACE) {
#if defined USE_SPPMPA || defined USE_PPMPA

			const float photonRadius = sqrtf(currentPhotonRadius2);

#else
			HitPoint *hpp = &workerHitPoints[i];
			const float photonRadius = sqrtf(hpp->accumPhotonRadius2);

#endif
			const Vector rad(photonRadius, photonRadius, photonRadius);
			const Vector bMin = ((hp->position - rad) - hpBBox.pMin) * invCellSize;
			const Vector bMax = ((hp->position + rad) - hpBBox.pMin) * invCellSize;

			for (int iz = abs(int(bMin.z)); iz <= abs(int(bMax.z)); iz++) {
				for (int iy = abs(int(bMin.y)); iy <= abs(int(bMax.y)); iy++) {
					for (int ix = abs(int(bMin.x)); ix <= abs(int(bMax.x)); ix++) {

						int hv = Hash(ix, iy, iz);

						//if (hv == engine->hitPointTotal - 1)

						if (hashGrid[hv] == NULL)
							hashGrid[hv] = new std::list<uint>();

						hashGrid[hv]->push_front(i);
						++entryCount;

						/*// hashGrid[hv]->size() is very slow to execute
						 if (hashGrid[hv]->size() > maxPathCount)
						 maxPathCount = hashGrid[hv]->size();*/
					}
				}
			}
		}
	}

	hashGridEntryCount = entryCount;

	//std::cerr << "Max. hit points in a single hash grid entry: " << maxPathCount << std::endl;
	std::cerr << "Total hash grid entry: " << entryCount << std::endl;
	std::cerr << "Avg. hit points in a single hash grid entry: " << entryCount
			/ hashGridSize << std::endl;

	//printf("Sizeof %d\n", sizeof(HitPoint*));

	// HashGrid debug code
	/*for (unsigned int i = 0; i < hashGridSize; ++i) {
	 if (hashGrid[i]) {
	 if (hashGrid[i]->size() > 10) {
	 std::cerr << "HashGrid[" << i << "].size() = " <<hashGrid[i]->size() << std::endl;
	 }
	 }
	 }*/
}

void PointerFreeHashGrid::updateLookupTable() {

	if (hashGridLists)
		delete[] hashGridLists;
	hashGridLists = new uint[hashGridEntryCount];

	if (hashGridLenghts)
		delete[] hashGridLenghts;
	hashGridLenghts = new uint[engine->hitPointTotal];

	if (hashGridListsIndex)
		delete[] hashGridListsIndex;
	hashGridListsIndex = new uint[engine->hitPointTotal];

	uint listIndex = 0;
	for (unsigned int i = 0; i < engine->hitPointTotal; ++i) {

		std::list<uint> *hps = hashGrid[i];

		hashGridListsIndex[i] = listIndex;

		if (hps) {
			hashGridLenghts[i] = hps->size();
			std::list<uint>::iterator iter = hps->begin();
			while (iter != hps->end()) {
				hashGridLists[listIndex++] = *iter++;
			}
		} else {
			hashGridLenghts[i] = 0;
		}

	}

}
Esempio n. 28
0
static void ConfigureActionItem(const tinyxml2::XMLElement *element, std::vector<unsigned int> &buffer)
{
	switch (Hash(element->Value()))
	{
	case 0x3a224d98 /* "spawn" */:
		{
			Expression::Append(buffer, Expression::Spawn, Hash(element->Attribute("name")));
			if (const tinyxml2::XMLElement *param = element->FirstChildElement("offset"))
				Expression::Loader<__m128>::ConfigureRoot(param, buffer, sTransformNames, sTransformDefault);
			else
				Expression::Append(buffer, Expression::Read<__m128>, _mm_setzero_ps());
			if (const tinyxml2::XMLElement *param = element->FirstChildElement("velocity"))
				Expression::Loader<__m128>::ConfigureRoot(param, buffer, sTransformNames, sTransformDefault);
			else
				Expression::Append(buffer, Expression::Read<__m128>, _mm_setzero_ps());
		}
		break;

	case 0x93e05f71 /* "switch" */:
		{
			Expression::Append(buffer, Expression::Switch, Hash(element->Attribute("name")));
		}
		break;

	case 0xfd5e91a8 /* "addresource" */:
		{
			Expression::Append(buffer, Expression::AddResource, Hash(element->Attribute("name")));
			Expression::Loader<float>::ConfigureRoot(element, buffer, sScalarNames, sScalarDefault);
		}
		break;

	case 0xd99ba82a /* "repeat" */:
		{
			int count = 1;
			element->QueryIntAttribute("count", &count);

			Expression::Append(buffer, Expression::Repeat, count);

			buffer.push_back(0);
			int start = buffer.size();
			ConfigureAction(element, buffer);
			buffer[start-1] = buffer.size() - start;
		}
		break;

	case 0xddef486b /* "loop" */:
		{
			unsigned int name = Hash(element->Attribute("name"));
			float from = 0.0f;
			element->QueryFloatAttribute("from", &from);
			float to = 0.0f;
			element->QueryFloatAttribute("to", &to);
			float by = from < to ? 1.0f : -1.0f;
			element->QueryFloatAttribute("by", &by);

			if ((to - from) * by <= 0)
			{
				DebugPrint("loop name=\"%s\" from=\"%f\" to=\"%f\" by=\"%f\" would never terminate\n");
				break;
			}

			Expression::Append(buffer, Expression::Loop, name, from, to, by);

			buffer.push_back(0);
			int start = buffer.size();
			ConfigureAction(element, buffer);
			buffer[start-1] = buffer.size() - start;
		}
		break;
	}
}
Esempio n. 29
0
   TST_tpCondRet TBS_ValidarTabela( TBS_tppTabela pTabela )
   {

      unsigned inxHash ;

      tpLista * pElem ;

      #ifdef _DEBUG
         TST_ASSERT( pTabela != NULL ) ;
      #endif

      /* Validar existência de dados da cabeça */

         if ( pTabela->tamVtHash <= 1 )
         {
            return TST_NotificarFalha( "Tamanho incorreto do vetor de randomização." ) ;
         } /* if */

         if ( pTabela->pVtHash == NULL )
         {
            return TST_NotificarFalha( "Falta vetor de randomização." ) ;
         } /* if */

         if ( pTabela->ObterSimbolo == NULL )
         {
            return TST_NotificarFalha( "Falta função obter simbolo." ) ;
         } /* if */

      /* Validar listas de colisão */

         for ( inxHash = 0 ; inxHash < pTabela->tamVtHash ; inxHash ++ ) {

         /* Validar toda a lista de colisão */

            pElem = pTabela->pVtHash[ inxHash ] ;

            while ( pElem != NULL ) {

            /* Validar elemento da lista de colisão */

               if ( pElem->pDado == NULL )
               {
                  return TST_NotificarFalha( "Faltou dado em elemento de lista." ) ;
               } /* if */

               if ( Hash( pTabela->ObterSimbolo( pElem->pDado ) ,
                              pTabela->tamVtHash ) != inxHash )
               {
                  return TST_NotificarFalha( "Índice has de elemento está incorreto." ) ;
               } /* if */

               if ( pElem->pAnt != NULL )
               {
                  if ( pElem->pAnt->pProx != pElem )
                  {
                     return TST_NotificarFalha( "Erro de encadeamento à esquerda em elemento de lista." ) ;
                  } /* if */
               } else
               {
                  if ( pElem != pTabela->pVtHash[ inxHash ] )
                  {
                     return TST_NotificarFalha( "Erro de encadeamento origem em elemento de lista." ) ;
                  } /* if */
               } /* if */

               if ( pElem->pProx != NULL )
               {
                  if ( pElem->pProx->pAnt != pElem )
                  {
                     return TST_NotificarFalha( "Erro de encadeamento à direita em elemento de lista." ) ;
                  } /* if */
               } /* if */

               pElem = pElem->pProx ;

            } /* fim repete: Validar toda a lista de colisão */

         } /* fim repete: Validar listas de colisão */

      return TST_CondRetOK ;

   } /* Fim função: TBS  &Validar tabela de símbolos */
Esempio n. 30
0
void *search(void *unused) {
  // Various size constants for convenience
  const size_t prelen = strlen(PREFIX_STRING);
  const size_t sufflen = strlen(SUFFIX_STRING);
  const size_t suffstart = LEN - sufflen;

  // Buffer used to store candidate string, extra for null terminator.
  char str[LEN + 1];
  str[LEN] = 0;

  // Put in our hardcoded prefix/suffix strings
  strcpy(str, PREFIX_STRING);
  strcpy(str + suffstart, SUFFIX_STRING);

  // Track how many hashes we've tried, for throughput estimate.
  uint64_t count = 0;
  char counting = 1;

  // Thread-local best score achieved, used to avoid
  // unnecessary accesses to shared global_best in the common case.
  int best = INT_MAX;

  // Buffer for storing computed hash bytes
  char hash[128];

start:
  // Fill the middle of the string with random data
  // (not including prefix, suffix, or portion we'll exhaustively search)
  gen_rand(str + prelen, LEN - prelen - sufflen - SEARCH_CHARS);

  // Iteration index array
  // Indirection used to keep character set flexible.
  unsigned idx[SEARCH_CHARS];
  memset(idx, 0, sizeof(idx));

  // Initialize enumeration part of string to first letter in charset
  char *iterstr = str + suffstart - SEARCH_CHARS;
  memset(iterstr, CHARSET[0], SEARCH_CHARS);

  while (1) {
    // Try string in current form
    Hash(1024, (BitSequence *)str, LEN * 8, (BitSequence *)hash);

    // How'd we do?
    int d = hamming_dist(hash, GOAL_BITS, 128);

    // If this is the best we've seen, print it and update best.
    if (d < best) {
      best = d;

      lock();
      if (d < global_best) {
        global_best = d;
        printf("%d - '%s'\n", d, str);
        fflush(stdout);
      }
      unlock();
    }

    // Increment string index array, updating str as we go
    // aaaaaa
    // baaaaa
    // caaaaa
    // ...
    // abaaaa
    // bbaaaa
    // cbaaaa
    // ...
    // (etc)
    int cur = 0;
    while (++idx[cur] >= CHARSET_SIZE) {
      idx[cur] = 0;
      iterstr[cur] = CHARSET[idx[cur]];

      // Advance to next position.
      // If we've used all of our search characters,
      // time to start over with new random prefix.
      if (++cur == SEARCH_CHARS)
        goto start;
    }
    iterstr[cur] = CHARSET[idx[cur]];

    // Throughput calculation.
    // Once this thread hits a limit, increment global_done
    // and print throughput estimate if we're the last thread to do so.
    const uint64_t iters = 1 << 24; // ~16M
    if (counting && ++count == iters) {
      counting = 0;

      time_t end = time(NULL);
      int elapsed = end - global_start;

      lock();
      global_count += count;
      assert(global_count >= count && "counter overflow");
      if (++global_done == num_threads) {
        printf("\n*** Total throughput ~= %f hash/S\n\n",
               ((double)(global_count)) / elapsed);
      }
      unlock();
    }
  }
}