本文整理汇总了C++中Hash函数的典型用法代码示例。如果您正苦于以下问题:C++ Hash函数的具体用法?C++ Hash怎么用?C++ Hash使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Hash函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: CollectDataFlow
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;
}
示例2: Write
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);
}
示例3: unordered_map
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) {}
示例4: Hash
int HashFunction::MakeAddress (string key, unsigned int depth){
unsigned int hash = Hash(key);
return MakeAddress(hash,depth);
}
示例5: vulnerability
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());
}
示例6: NiAdminThread
// 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);
}
示例7: ZHashValue
/*
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(); }
示例8: MyHashMap
/**
* 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) {
}
示例9: Hash
int TPZWillamWarnke::ClassId() const{
return Hash("TPZWillamWarnke") ^ WILLAMWARNKEPARENT::ClassId() << 1;
}
示例10: MyHashTable
/**
* 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);
}
示例11: hash
Hash hash(const Provider& provider)
{
auto tmp = simstd::make_unique<HashImpl>(provider);
return tmp->is_valid() ? Hash(simstd::move(tmp)) : Hash();
}
示例12: Process
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;
}
示例13: TCSP_LoadKeyByUUID_Internal
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);
}
//.........这里部分代码省略.........
示例14: GroupNodeDef_Init
void GroupNodeDef_Init()
{
str4cpy(gGroupNodeDef.mName, "group");
gGroupNodeDef.mHash = Hash(gGroupNodeDef.mName);
gGroupNodeDef.mAllocSize = sizeof(Group);
}
示例15: ThreadSendAlert
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++;
//.........这里部分代码省略.........