Пример #1
0
Status
Login::repoFind(JsonPtr &result, const std::string &type, bool create)
{
    result = JsonPtr();

    // Try 1: Use what we have:
    repoFindLocal(result, type).log(); // Failure is fine
    if (result) return Status();

    // Try 2: Sync with the server:
    ABC_CHECK(update());
    repoFindLocal(result, type).log(); // Failure is fine
    if (result) return Status();

    // Try 3: Make a new repo:
    if (create)
    {
        // Make the keys:
        DataChunk dataKey;
        DataChunk syncKey;
        ABC_CHECK(randomData(dataKey, DATA_KEY_LENGTH));
        ABC_CHECK(randomData(syncKey, SYNC_KEY_LENGTH));
        AccountRepoJson repoJson;
        ABC_CHECK(repoJson.syncKeySet(base64Encode(syncKey)));
        ABC_CHECK(repoJson.dataKeySet(base64Encode(dataKey_)));

        // Make the metadata:
        DataChunk id;
        ABC_CHECK(randomData(id, keyIdLength));
        KeyJson keyJson;
        ABC_CHECK(keyJson.idSet(base64Encode(id)));
        ABC_CHECK(keyJson.typeSet(type));
        ABC_CHECK(keyJson.keysSet(repoJson));

        // Encrypt the metadata:
        JsonBox keyBox;
        ABC_CHECK(keyBox.encrypt(keyJson.encode(), dataKey_));

        // Push the wallet to the server:
        AuthJson authJson;
        ABC_CHECK(authJson.loginSet(*this));
        ABC_CHECK(loginServerKeyAdd(authJson, keyBox, base16Encode(syncKey)));

        // Save to disk:
        LoginStashJson stashJson;
        ABC_CHECK(stashJson.load(paths.stashPath()));
        if (!stashJson.keyBoxes().ok())
            ABC_CHECK(stashJson.keyBoxesSet(JsonArray()));
        ABC_CHECK(stashJson.keyBoxes().append(keyBox));
        ABC_CHECK(stashJson.save(paths.stashPath()));

        result = repoJson;
        return Status();
    }

    return ABC_ERROR(ABC_CC_AccountDoesNotExist, "No such repo");
}
Пример #2
0
static void issueRequest(client c) {
    int op = config.optab[random() % 100];
    long key, hashkey;
    unsigned long datalen;

    config.issued_requests++;
    if (config.issued_requests == config.num_requests) config.done = 1;

    c->start = microseconds();
    if (config.longtail) {
        key = longtailprng(0,config.keyspace-1,config.longtail_order);
        hashkey = longtailprng(0,config.hashkeyspace-1,config.longtail_order);
    } else {
        key = random() % config.keyspace;
        hashkey = random() % config.hashkeyspace;
    }

    c->keyid = key;
    c->reqtype = op;

    if (op == REDIS_IDLE) {
        /* Idle */
    } else if (op == REDIS_SET) {
        datalen = randomData(key);
        redisAsyncCommand(c->context,handleReply,NULL,"SET string:%ld %b",key,config.databuf,datalen);
    } else if (op == REDIS_GET) {
        redisAsyncCommand(c->context,handleReply,NULL,"GET string:%ld",key);
    } else if (op == REDIS_DEL) {
        redisAsyncCommand(c->context,handleReply,NULL,"DEL string:%ld list:%ld hash:%ld",key,key,key);
    } else if (op == REDIS_LPUSH) {
        datalen = randomData(key);
        redisAsyncCommand(c->context,handleReply,NULL,"LPUSH list:%ld %b",key,config.databuf,datalen);
    } else if (op == REDIS_LPOP) {
        redisAsyncCommand(c->context,handleReply,NULL,"LPOP list:%ld",key);
    } else if (op == REDIS_HSET) {
        datalen = randomData(key);
        redisAsyncCommand(c->context,handleReply,NULL,"HSET hash:%ld key:%ld %b",key,hashkey,config.databuf,datalen);
    } else if (op == REDIS_HGET) {
        redisAsyncCommand(c->context,handleReply,NULL,"HGET hash:%ld key:%ld",key,hashkey);
    } else if (op == REDIS_HGETALL) {
        redisAsyncCommand(c->context,handleReply,NULL,"HGETALL hash:%ld",key);
    } else if (op == REDIS_SWAPIN) {
        /* Only accepts a single argument, so for now only works with string keys. */
        redisAsyncCommand(c->context,handleReply,NULL,"DEBUG SWAPIN string:%ld",key);
    } else {
        assert(NULL);
    }
}
Пример #3
0
Status
Login::rootKeyUpgrade()
{
    // Create a BIP39 mnemonic, and use it to derive the rootKey:
    DataChunk entropy;
    ABC_CHECK(randomData(entropy, 256/8));
    auto mnemonic = bc::create_mnemonic(entropy, bc::language::en);
    auto rootKeyRaw = bc::decode_mnemonic(mnemonic);
    rootKey_ = DataChunk(rootKeyRaw.begin(), rootKeyRaw.end());

    // Pack the keys into various boxes:
    JsonBox rootKeyBox;
    ABC_CHECK(rootKeyBox.encrypt(rootKey_, dataKey_));
    JsonBox mnemonicBox, dataKeyBox;
    auto infoKey = bc::hmac_sha256_hash(rootKey_, DataSlice(infoKeyHmacKey));
    ABC_CHECK(mnemonicBox.encrypt(bc::join(mnemonic), infoKey));
    ABC_CHECK(dataKeyBox.encrypt(dataKey_, infoKey));

    // Upgrade the account on the server:
    ABC_CHECK(loginServerAccountUpgrade(*this,
                                        rootKeyBox, mnemonicBox, dataKeyBox));
    ABC_CHECK(rootKeyBox.save(paths.rootKeyPath()));

    return Status();
}
Пример #4
0
nsresult
GenerateRandomName(nsCString& aOutSalt, uint32_t aLength)
{
  nsresult rv;
  nsCOMPtr<nsIRandomGenerator> rg =
    do_GetService("@mozilla.org/security/random-generator;1", &rv);
  if (NS_FAILED(rv)) return rv;

  // For each three bytes of random data we will get four bytes of ASCII.
  const uint32_t requiredBytesLength =
    static_cast<uint32_t>((aLength + 3) / 4 * 3);

  uint8_t* buffer;
  rv = rg->GenerateRandomBytes(requiredBytesLength, &buffer);
  if (NS_FAILED(rv)) return rv;

  nsAutoCString temp;
  nsDependentCSubstring randomData(reinterpret_cast<const char*>(buffer),
                                   requiredBytesLength);
  rv = Base64Encode(randomData, temp);
  free(buffer);
  buffer = nullptr;
  if (NS_FAILED (rv)) return rv;

  aOutSalt = temp;
  return NS_OK;
}
Пример #5
0
Status
Login::createNew(std::shared_ptr<Login> &result,
                 LoginStore &store, const char *password)
{
    DataChunk dataKey;
    ABC_CHECK(randomData(dataKey, DATA_KEY_LENGTH));
    std::shared_ptr<Login> out(new Login(store, dataKey));
    ABC_CHECK(out->createNew(password));

    result = std::move(out);
    return Status();
}
Пример #6
0
Status
Wallet::createNew(const std::string &name, int currency)
{
    // Set up the keys:
    ABC_CHECK(randomData(bitcoinKey_, BITCOIN_SEED_LENGTH));
    bitcoinKeyBackup_ = bitcoinKey_;
    ABC_CHECK(randomData(dataKey_, DATA_KEY_LENGTH));
    DataChunk syncKey;
    ABC_CHECK(randomData(syncKey, SYNC_KEY_LENGTH));
    syncKey_ = base16Encode(syncKey);

    // Create the sync directory:
    ABC_CHECK(fileEnsureDir(gContext->paths.walletsDir()));
    ABC_CHECK(fileEnsureDir(dir()));
    ABC_CHECK(fileEnsureDir(syncDir()));
    ABC_CHECK(syncMakeRepo(syncDir()));

    // Populate the sync directory:
    ABC_CHECK(currencySet(currency));
    ABC_CHECK(nameSet(name));
    ABC_CHECK(addresses.load());

    // Push the wallet to the server:
    bool dirty = false;
    ABC_CHECK(loginServerWalletCreate(account.login, syncKey_));
    ABC_CHECK(syncRepo(syncDir(), syncKey_, dirty));
    ABC_CHECK(loginServerWalletActivate(account.login, syncKey_));

    // If everything worked, add the wallet to the account:
    WalletJson json;
    ABC_CHECK(json.bitcoinKeySet(base16Encode(bitcoinKey_)));
    ABC_CHECK(json.dataKeySet(base16Encode(dataKey_)));
    ABC_CHECK(json.syncKeySet(syncKey_));
    ABC_CHECK(account.wallets.insert(id_, json));
    ABC_CHECK(account.sync(dirty));

    return Status();
}
Пример #7
0
/*
 * Version 4 UUIDs use a scheme relying only on random numbers.
 * This algorithm sets the version number (4 bits) as well as two reserved bits.
 * All other bits (the remaining 122 bits) are set using a random or pseudorandom data source.
 * Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx where x is any hexadecimal
 * digit and y is one of 8, 9, A, or B (e.g., F47AC10B-58CC-4372-A567-0E02B2E3D479).
 */
Status
randomUuid(std::string &result)
{
    DataChunk data;
    ABC_CHECK(randomData(data, UUID_BYTE_COUNT));

    // put in the version
    // To put in the version, take the 7th byte and perform an and operation using 0x0f, followed by an or operation with 0x40.
    data[6] = (data[6] & 0xf) | 0x40;

    // 9th byte significant nibble is one of 8, 9, A, or B
    data[8] = (data[8] | 0x80) & 0xbf;

    char out[UUID_STR_LENGTH + 1];
    sprintf(out,
            "%02X%02X%02X%02X-%02X%02X-%02X%02X-%02X%02X-%02X%02X%02X%02X%02X%02X",
            data[0], data[1], data[2], data[3], data[4], data[5], data[6], data[7],
            data[8], data[9], data[10], data[11], data[12], data[13], data[14], data[15]);

    result = out;
    return Status();
}
Пример #8
0
nsresult
GenerateRandomPathName(nsCString& aOutSalt, uint32_t aLength)
{
  nsresult rv;
  nsCOMPtr<nsIRandomGenerator> rg =
    do_GetService("@mozilla.org/security/random-generator;1", &rv);
  if (NS_FAILED(rv)) return rv;

  // For each three bytes of random data we will get four bytes of
  // ASCII. Request a bit more to be safe and truncate to the length
  // we want at the end.
  const uint32_t requiredBytesLength =
    static_cast<uint32_t>((aLength + 1) / 4 * 3);

  uint8_t* buffer;
  rv = rg->GenerateRandomBytes(requiredBytesLength, &buffer);
  if (NS_FAILED(rv)) return rv;

  nsAutoCString temp;
  nsDependentCSubstring randomData(reinterpret_cast<const char*>(buffer),
                                   requiredBytesLength);
  rv = Base64Encode(randomData, temp);
  NS_Free(buffer);
  buffer = nullptr;
  if (NS_FAILED (rv)) return rv;

  temp.Truncate(aLength);

  // Base64 characters are alphanumeric (a-zA-Z0-9) and '+' and '/', so we need
  // to replace illegal characters -- notably '/'
  temp.ReplaceChar(FILE_PATH_SEPARATOR FILE_ILLEGAL_CHARACTERS, '_');

  aOutSalt = temp;

  return NS_OK;
}
Пример #9
0
RefPtr<CryptoKeyHMAC> CryptoKeyHMAC::generate(size_t lengthBits, CryptoAlgorithmIdentifier hash, bool extractable, CryptoKeyUsageBitmap usages)
{
    if (!lengthBits) {
        switch (hash) {
        case CryptoAlgorithmIdentifier::SHA_1:
        case CryptoAlgorithmIdentifier::SHA_224:
        case CryptoAlgorithmIdentifier::SHA_256:
            lengthBits = 512;
            break;
        case CryptoAlgorithmIdentifier::SHA_384:
        case CryptoAlgorithmIdentifier::SHA_512:
            lengthBits = 1024;
            break;
        default:
            return nullptr;
        }
    }
    // CommonHMAC only supports key length that is a multiple of 8. Therefore, here we are a little bit different
    // from the spec as of 11 December 2014: https://www.w3.org/TR/WebCryptoAPI/#hmac-operations
    if (lengthBits % 8)
        return nullptr;

    return adoptRef(new CryptoKeyHMAC(randomData(lengthBits / 8), hash, extractable, usages));
}
Пример #10
0
Status
hbitsCreate(std::string &result, std::string &addressOut)
{
    while (true)
    {
        libbitcoin::data_chunk cand(21);
        ABC_CHECK(randomData(cand, cand.size()));
        std::string minikey = libbitcoin::encode_base58(cand);
        minikey.insert(0, "a");
        if (30 == minikey.size() &&
                0x00 == bc::sha256_hash(bc::to_data_chunk(minikey + "!"))[0])
        {
            bc::ec_secret secret;
            hbitsDecode(secret, minikey);
            bc::ec_point pubkey = bc::secret_to_public_key(secret, true);
            bc::payment_address address;
            address.set(pubkeyVersion(), bc::bitcoin_short_hash(pubkey));

            result = minikey;
            addressOut = address.encoded();
            return Status();
        }
    }
}
Пример #11
0
PassRefPtr<CryptoKeyAES> CryptoKeyAES::generate(CryptoAlgorithmIdentifier algorithm, size_t lengthBits, bool extractable, CryptoKeyUsage usages)
{
    if (lengthBits % 8)
        return nullptr;
    return adoptRef(new CryptoKeyAES(algorithm, randomData(lengthBits / 8), extractable, usages));
}
Пример #12
0
void InsertTrackTableL()
	{	
	HBufC* randomDataBuf = HBufC::NewLC(KTestBlobSize);
	TPtr randomData(randomDataBuf->Des());
	FillRandomData(randomData);
	
	RDbView view;
	TInt err = view.Prepare(TheDatabase, _L("select * from TRACKS"), view.EInsertOnly);
	TEST2(err, KErrNone);
	TheRowSet = view;	
	
	CDbColSet* colSet = TheRowSet.ColSetL();
	const TInt KIdIdx = colSet->ColNo(KId);
	const TInt KLastNameIdx = colSet->ColNo(KLastName);
	const TInt KFirstNameIdx = colSet->ColNo(KFirstName);
	const TInt KTitleIdx = colSet->ColNo(KTitle);
	const TInt KDownloadSiteIdx = colSet->ColNo(KDownloadSite);
	const TInt KBandNameIdx = colSet->ColNo(KBandName);
	const TInt KOriginIdx = colSet->ColNo(KOrigin);
	const TInt KAutoStartIdx = colSet->ColNo(KAutoStart);
	const TInt KInitVolumeIdx = colSet->ColNo(KInitVolume);
	const TInt KMarkedToPlayIdx = colSet->ColNo(KMarked2Play);
	const TInt KCategoryIdIdx = colSet->ColNo(KCategoryId);
	//const TInt KMusicFileIdx = colSet->ColNo(KMusicFile);
	delete colSet;
	colSet = NULL;

	err = TheDatabase.Begin();
	TEST2(err, KErrNone);
	
	for (TInt ii=1;ii<=KTrackRecordCount;++ii)
		{
		TheRowSet.InsertL();
		TheRowSet.SetColL(KIdIdx, ii);
		TheRowSet.SetColL(KLastNameIdx, _L("Dummy"));
		TheRowSet.SetColL(KFirstNameIdx,_L("Dummy"));
		TheRowSet.SetColL(KTitleIdx,_L("Dummy"));
		TheRowSet.SetColL(KDownloadSiteIdx,_L("Dummy"));
		TheRowSet.SetColL(KBandNameIdx,_L("Dummy"));
		TheRowSet.SetColL(KOriginIdx,_L("Dummy"));
		TheRowSet.SetColL(KAutoStartIdx,(ii%2));
		TheRowSet.SetColL(KInitVolumeIdx,(ii%2));
		TheRowSet.SetColL(KMarkedToPlayIdx,(ii%2));
		TheRowSet.SetColL(KCategoryIdIdx,(ii%KCategoryRecordCount));

		//RDbColWriteStream musicfile;
		//musicfile.OpenLC(TheRowSet, KMusicFileIdx);
		//musicfile.WriteL(randomData,KTestBlobSize);
		//musicfile.CommitL();
		//CleanupStack::PopAndDestroy(&musicfile);

		TheRowSet.PutL();
		}

	err = TheDatabase.Commit();
	TEST2(err, KErrNone);

	//err = TheDatabase.Compact();
	//TEST2(err, KErrNone);

	TheRowSet.Close();	

	////////////////////////////////////////////////////////////////////////////////////////////////

	err = view.Prepare(TheDatabase, _L("select * from TRACKS2"), view.EInsertOnly);
	TEST2(err, KErrNone);
	TheRowSet = view;	
	
	colSet = TheRowSet.ColSetL();
	const TInt KIdIdx2 = colSet->ColNo(KId);
	const TInt KMusicFileIdx2 = colSet->ColNo(KMusicFile);
	delete colSet;

	err = TheDatabase.Begin();
	TEST2(err, KErrNone);

	for (TInt ii=1;ii<=KTrackRecordCount;++ii)
		{
		TheRowSet.InsertL();
		TheRowSet.SetColL(KIdIdx2, ii);
		
		RDbColWriteStream musicfile;
		musicfile.OpenLC(TheRowSet, KMusicFileIdx2);
		musicfile.WriteL(randomData,KTestBlobSize);
		musicfile.CommitL();
		CleanupStack::PopAndDestroy(&musicfile);
		
		TheRowSet.PutL();
		}

	err = TheDatabase.Commit();
	TEST2(err, KErrNone);

	//err = TheDatabase.Compact();
	//TEST2(err, KErrNone);

	TheRowSet.Close();	

	CleanupStack::PopAndDestroy(randomDataBuf);
	}
Пример #13
0
void TestLocalSocket::runTest(uchar dataAmnt, uchar pkgAmnt, uchar fdAmnt)
{
	quint64					sendCount					=	0;
	quint64					sendCountPackage	=	0;
	quint64					sendCountData			=	0;
	quint64					sendCountFD				=	0;
	quint64					sendBytes					=	0;
	
	// Runtime for peer in seconds
	int							runTime	=	15;	// In seconds
	QElapsedTimer		time;
	
	// Log timer
	QElapsedTimer		logTimer;
	const	int				logInterval	=	200;	// In msec
	logTimer.start();
	
	printf("\tRunning %d seconds\n", runTime);
	
	time.start();
	while(m_localSocket && time.elapsed() < runTime * 1000)
	{
		QVERIFY2(m_localSocket->isOpen(), qPrintable(QStringLiteral("LocalSocket not open! (" + m_localSocket->errorString() + ")")));
		
		QChar				command;
		uchar				action;
		QFile			*	file	=	0;
		QString			filename;
		
		Variant			data(randomData(&action, dataAmnt, pkgAmnt, fdAmnt, &file));
		
		// data can be invalid if we only test file descriptors as they have an limit
		if(dataAmnt == 0 && pkgAmnt == 0 && !data.isValid())
			break;
		
		// randomData returned invalid data -> Error already printed
		QVERIFY(data.isValid());
		
		// Handle filename
		if(file != 0)
		{
			filename	=	QFileInfo(*file).absoluteFilePath();
			m_openFiles[filename]	=	file;
		}
		
		// 		if(!m_peer->m_socket->isOpen() && !m_peer->m_socket->bytesAvailable())
		// 		{
			// 			returnLock.lockForWrite();
			// 			failureReason		=	"Socket closed";
			// 			failureReceived	=	true;
			// 			returnLock.unlock();
			// 		}
			// 		qDebug("Open: %s", m_peer->m_socket->isOpen() ? "true" : "false");
			
			switch(action)
			{
				// Send data
				case 0:
				{
					QByteArray		dataAr(data.toByteArray());
					QByteArray		hash(QCryptographicHash::hash(dataAr, QCryptographicHash::Md5));
					command	=	'd';
					
					// 				qDebug("Sending data with size %d", dataAr.size());
					
					QVERIFY2(m_peer->writeControlData(QString(command).toLatin1() + hash.toHex() + "\n"), "Could not write data to peer!");
					
					// size
					quint32	size	=	qToBigEndian<quint32>(dataAr.size());
					// 				qDebug("Size written: %d", data.size());
					dataAr.prepend((const char*)&size, sizeof(size));
					
					// 				static quint64	totalWrittenTest	=	0;
					// 				totalWrittenTest	+=	data.size();
					// 				qDebug("total-written (test): %llu", totalWrittenTest);
					
					qint64	written	=	0;
					QElapsedTimer	timer;
					timer.start();
					
					while(m_localSocket && m_localSocket->isOpen() && written < dataAr.size() && timer.elapsed() < 30000)
					{
						qint64	tmp	=	m_localSocket->write(dataAr.constData() + written, dataAr.size() - written);
						
// 						if(tmp < 0)
// 							qDebug("tmp < 0! open: %s", m_localSocket->isOpen() ? "true" : "false");
						QVERIFY2(tmp >= 0, qPrintable(QStringLiteral("Could not write all data to peer! (" + m_localSocket->errorString() + ")")));
						
						written	+=	tmp;
// 						QCoreApplication::processEvents();
						m_localSocket->waitForBytesWritten(3000);
					}
					
					// For debugging
					
					// 				printf("\t=== Data written ===\n");
					// 				for(int i = 0; i < data.size(); i++)
					// 					printf("\t%02X", data.constData()[i]);
					// 				printf("\t\n====================\n");
					
					QVERIFY2(written == dataAr.size(), "Could not write all data to peer!");
					
					sendCountData++;
					sendBytes	+=	dataAr.size() - sizeof(size);
					
					dataAr.clear();
					
					// 				qDebug("Sent data!");
				}break;
				
				// Send package
				case 1:
				{
					QByteArray		dataAr(data.toByteArray());
					QByteArray		hash(QCryptographicHash::hash(dataAr, QCryptographicHash::Md5));
					command	=	'p';
					
					QVERIFY2(m_peer->writeControlData(QString(command).toLatin1() + hash.toHex() + "\n"), "Could not write data to peer!");
					
					bool result = m_localSocket->writePackage(dataAr);
					
					while(!result && m_localSocket->isOpen())
					{
						m_localSocket->waitForPackageWritten(30000);
						result = m_localSocket->writePackage(dataAr);
					}
						
					QVERIFY2(result, "Could not write package!");
					
					sendCountPackage++;
					sendBytes	+=	dataAr.size();
					
					dataAr.clear();
					
					// 				qDebug("Sent package!");
				}break;
				
				// Send file descriptor
				case 2:
				{
					QByteArray		dataAr(filename.toLatin1());
					
					command	=	's';
					
					QVERIFY2(m_peer->writeControlData(QString(command).toLatin1() + dataAr.toHex() + "\n"), "Could not write data to peer!");
					QVERIFY2(m_localSocket->writeSocketDescriptor(data.toSocketDescriptor()), "Could not write socket descriptor!");
					
					sendCountFD++;
					
					// 				qDebug("Sent socket descriptor!");
				}break;
			}
			
			QCoreApplication::processEvents();
			
			// 		qDebug("Sent data!");
			
			sendCount++;
			
			if(logTimer.elapsed() >= logInterval)
			{
				Logger::log("Written commands (TestLocalSocket)", sendCount);
				logTimer.restart();
			}
			
			QStringList	failures(m_peer->failureMessages());
			QVERIFY2(failures.isEmpty(), qPrintable(QStringLiteral("Received failures:\n\t- %1").arg(failures.join("\n\t- "))));
	}
	
	Logger::log("Written commands (TestLocalSocket)", sendCount, "wB", "Waiting for bytes to be written");
	
	printf("\tSent %llu actions (%llu data portions, %llu packages, %llu file descriptors)\n", sendCount, sendCountData, sendCountPackage, sendCountFD);
	
	quint64			sendBytesFormatted	=	sendBytes;
	QStringList	formatter;
	formatter	<< "b" << "KB" << "MB" << "GB" << "TB" << "PB";
	int	idx	=	0;
	while(sendBytesFormatted > 1024*10)
	{
		sendBytesFormatted	/=	1024;
		idx++;
	}
	printf("\tSent %llu bytes (%llu %s)\n", sendBytes, sendBytesFormatted, qPrintable(formatter[idx]));
	
	printf("\tWaiting for results (This could take a while)\n");
	
	while(m_localSocket && m_localSocket->isOpen() && m_localSocket->bytesToWrite())
	{
		QCoreApplication::processEvents();
		m_localSocket->waitForBytesWritten(10000);
	}
	
	// Send close command
	// 	qDebug("Sending close command!");
	Logger::log("Written commands (TestLocalSocket)", sendCount, "sC", "Sent close command");
	QVERIFY2(m_peer->writeControlData(QStringLiteral("c\n").toLatin1()), "Could not write data to peer!");
	
	QCoreApplication::processEvents();
	
	if(!m_peer->waitForTotalSuccessCount(sendCount, 20000))
	{
		QStringList	failures(m_peer->failureMessages());
		QVERIFY2(failures.isEmpty(), qPrintable(QStringLiteral("Received failures:\n\t- %1").arg(failures.join("\n\t- "))));
		
		if(m_peer->totalSuccessCount() != sendCount)
			Logger::log("Written commands (TestLocalSocket)", sendCount, "f", "Failed to wait for all return commands");
		
		QVERIFY2(m_peer->totalSuccessCount() == sendCount, qPrintable(QStringLiteral("Invalid return count. Expected: %1; Got: %2").arg(sendCount).arg(m_peer->totalSuccessCount())));
	}
	
	// Check signal socketDescriptorWritten()
	QList<quintptr>	neededFdSignals;
	foreach(QFile * file, m_openFiles.values())
		neededFdSignals.append((quintptr)file->handle());
	
	QCoreApplication::processEvents();
	
	QList<quintptr>	emittedFdSignals(m_peer->fileDescriptorSignals());
	
	for(int i = 0; i < emittedFdSignals.count(); i++)
		QVERIFY2(neededFdSignals.removeOne(emittedFdSignals[i]), qPrintable(QStringLiteral("Invalid socketDescriptorWritten() signal")));
	
	QVERIFY2(neededFdSignals.isEmpty(), qPrintable(QStringLiteral("Missing socketDescriptorWritten() signals: %1").arg(neededFdSignals.count())));
	
	
	Logger::log("Written commands (TestLocalSocket)", sendCount, "d", "Done");
}
Пример #14
0
Status
Login::createNew(const char *password)
{
    LoginPackage loginPackage;
    JsonSnrp snrp;

    // Set up care package:
    CarePackage carePackage;
    ABC_CHECK(snrp.create());
    ABC_CHECK(carePackage.passwordKeySnrpSet(snrp));

    // Set up syncKey:
    DataChunk syncKey;
    JsonBox syncKeyBox;
    ABC_CHECK(randomData(syncKey, SYNC_KEY_LENGTH));
    ABC_CHECK(syncKeyBox.encrypt(syncKey, dataKey_));
    ABC_CHECK(loginPackage.syncKeyBoxSet(syncKeyBox));

    // Set up passwordAuth (LP1):
    if (password)
    {
        std::string LP = store.username() + password;

        // Generate passwordAuth:
        ABC_CHECK(usernameSnrp().hash(passwordAuth_, LP));

        // We have a password, so use it to encrypt dataKey:
        DataChunk passwordKey;
        JsonBox passwordBox;
        ABC_CHECK(carePackage.passwordKeySnrp().hash(passwordKey, LP));
        ABC_CHECK(passwordBox.encrypt(dataKey_, passwordKey));
        ABC_CHECK(loginPackage.passwordBoxSet(passwordBox));
    }
    else
    {
        // Generate passwordAuth:
        ABC_CHECK(randomData(passwordAuth_, scryptDefaultSize));
    }
    JsonBox passwordAuthBox;
    ABC_CHECK(passwordAuthBox.encrypt(passwordAuth_, dataKey_));
    ABC_CHECK(loginPackage.passwordAuthBoxSet(passwordAuthBox));

    // Create the account and repo on server:
    ABC_CHECK(loginServerCreate(store, passwordAuth_,
                                carePackage, loginPackage, base16Encode(syncKey)));

    // Set up the on-disk login:
    ABC_CHECK(store.paths(paths, true));
    ABC_CHECK(carePackage.save(paths.carePackagePath()));
    ABC_CHECK(loginPackage.save(paths.loginPackagePath()));
    ABC_CHECK(rootKeyUpgrade());

    // Save the bare minimum needed to access the Airbitz account:
    LoginStashJson stashJson;
    ABC_CHECK(stashJson.loginIdSet(base64Encode(store.userId())));
    ABC_CHECK(stashJson.syncKeyBoxSet(syncKeyBox));
    stashJson.save(paths.stashPath());

    // Latch the account:
    ABC_CHECK(loginServerActivate(*this));

    return Status();
}
Пример #15
0
Status
Login::makeEdgeLogin(JsonPtr &result, const std::string &appId,
                     const std::string &pin)
{
    result = JsonPtr();

    // Try 1: Use what we have:
    makeEdgeLoginLocal(result, appId).log(); // Failure is fine
    if (result) return Status();

    // Try 2: Sync with the server:
    ABC_CHECK(update());
    makeEdgeLoginLocal(result, appId).log(); // Failure is fine
    if (result) return Status();

    // Try 3: Make a new login:
    {
        DataChunk loginKey;
        ABC_CHECK(randomData(loginKey, DATA_KEY_LENGTH));
        JsonBox parentBox;
        ABC_CHECK(parentBox.encrypt(loginKey, dataKey_));

        // Make the access credentials:
        DataChunk loginId;
        DataChunk loginAuth;
        ABC_CHECK(randomData(loginId, scryptDefaultSize));
        ABC_CHECK(randomData(loginAuth, scryptDefaultSize));
        JsonBox loginAuthBox;
        ABC_CHECK(loginAuthBox.encrypt(loginAuth, loginKey));

        // Set up the outgoing Login object:
        LoginReplyJson server;
        ABC_CHECK(server.appIdSet(appId));
        ABC_CHECK(server.loginIdSet(base64Encode(loginId)));
        ABC_CHECK(server.loginAuthBoxSet(loginAuthBox));
        ABC_CHECK(server.parentBoxSet(parentBox));
        LoginStashJson stash = server.clone();
        ABC_CHECK(server.set("loginAuth", base64Encode(loginAuth)));

        // Set up the PIN, if we have one:
        if (pin.size())
        {
            DataChunk pin2Key;
            ABC_CHECK(randomData(pin2Key, 32));
            const auto pin2Id = hmacSha256(store.username(), pin2Key);
            const auto pin2Auth = hmacSha256(pin, pin2Key);

            // Create pin2Box:
            JsonBox pin2Box;
            ABC_CHECK(pin2Box.encrypt(loginKey, pin2Key));

            // Create pin2KeyBox:
            JsonBox pin2KeyBox;
            ABC_CHECK(pin2KeyBox.encrypt(pin2Key, loginKey));

            // Set up the server login:
            ABC_CHECK(server.set("pin2Id", base64Encode(pin2Id)));
            ABC_CHECK(server.set("pin2Auth", base64Encode(pin2Auth)));
            ABC_CHECK(server.pin2BoxSet(pin2Box));
            ABC_CHECK(server.pin2KeyBoxSet(pin2KeyBox));
            ABC_CHECK(stash.pin2KeySet(base64Encode(pin2Key)));
        }

        // Write to server:
        AuthJson authJson;
        ABC_CHECK(authJson.loginSet(*this));
        ABC_CHECK(loginServerCreateChildLogin(authJson, server));

        // Save to disk:
        LoginStashJson stashJson;
        ABC_CHECK(stashJson.load(paths.stashPath()));
        if (!stashJson.children().ok())
            ABC_CHECK(stashJson.childrenSet(JsonArray()));
        ABC_CHECK(stashJson.children().append(stash));
        ABC_CHECK(stashJson.save(paths.stashPath()));
    }

    ABC_CHECK(makeEdgeLoginLocal(result, appId).log());
    if (!result)
        return ABC_ERROR(ABC_CC_Error, "Empty edge login after creation.");
    return Status();
}
Пример #16
0
int main(int argc,char* argv[])
{
	randSeed();
	if(argc!=2){
		return -1;
	}
//variable declaration
	int i=0;
	struct avlTree* myAvlT = createAvlTree();
	struct tree* myBst = createTree();
	clock_t start1,end1;
	clock_t start2,end2;
	float diff1=0.0,diff2=0.0;
	struct data *d,*d1;

//Insert
	for(i=0; i<(atoi(argv[1])*1000000); i++)
	{
		d = randomData();
		d1 = createData(d->v1,d->v2);
			/*inserting same data struct in both trees for
			better comparision of performances*/
	//avl insert
		start1 = getTime();
		insertAvl(myAvlT,d);
		end1 = getTime();
		diff1 += timeDiff(start1,end1);
			/*while inserting in avl clock of bst 
			will pause and vice versa */
	//bst insert
		start2 = getTime();
		insertBst(myBst,d1);
		end2 = getTime();
		diff2 += timeDiff(start2,end2);		
	}
	//printf("AVL insertion TIME:");
        printf("%f\n",diff1);
	//printf("BST insertion TIME:");
        printf("%f\n",diff2);

//Search
	diff1=0.0;
	diff2=0.0;
	for(i=0;i<(atoi(argv[1]) * 1000000);i++) 
	{
	//AVL Search
		d = randomData();
		d1 = createData(d->v1,d->v2);	
			/*searching same data struct in both trees for
			better comparision of performances*/

		start1 = getTime();
		searchAvl(myAvlT,d);
		end1 = getTime();
		diff1 += timeDiff(start1,end1);
			/*while searching in avl clock of bst 
			will pause and vice versa */
		free(d);
	//BST Search
        	start2 = getTime();
	        searchBst(myBst,d1);
       		end2 = getTime();
		diff2 += timeDiff(start2,end2);		
		free(d1);

	}	

	//printf("AVL search TIME:");
	printf("%f\n",diff1);
	//printf("BST search TIME:");
        printf("%f\n",diff2);

	cleanBST(myBst);
	cleanAvl(myAvlT);
	return 0;
}
Пример #17
0
Status
ScryptSnrp::create()
{
    // Set up default values:
    ABC_CHECK(randomData(salt, SCRYPT_DEFAULT_SALT_LENGTH));
    n = SCRYPT_DEFAULT_CLIENT_N;
    r = SCRYPT_DEFAULT_CLIENT_R;
    p = SCRYPT_DEFAULT_CLIENT_P;

    // Benchmark the CPU:
    DataChunk temp;
    struct timeval timerStart;
    struct timeval timerEnd;
    gettimeofday(&timerStart, nullptr);
    ABC_CHECK(hash(temp, salt));
    gettimeofday(&timerEnd, nullptr);

    // Find the time in microseconds:
    int totalTime = 1000000 * (timerEnd.tv_sec - timerStart.tv_sec);
    totalTime += timerEnd.tv_usec;
    totalTime -= timerStart.tv_usec;
    int diffShift = 0;

    ABC_DebugLevel(1, "Scrypt target:%d timing:%d", SCRYPT_TARGET_USECONDS,
                   totalTime);

    if (totalTime >= SCRYPT_TARGET_USECONDS)
    {
        ABC_DebugLevel(1, "Scrypt timing: Slow device");
        // Very slow device.
        // Do nothing, use default scrypt settings which are lowest we'll go
    }
    else if (totalTime >= SCRYPT_TARGET_USECONDS / SCRYPT_MAX_CLIENT_R)
    {
        // Medium speed device.
        // Scale R between 1 to 8 assuming linear effect on hashing time.
        // Don't touch N.
        ABC_DebugLevel(1, "Scrypt timing: Medium device");
        r = SCRYPT_TARGET_USECONDS / totalTime;
    }
    else if (totalTime > 0)
    {
        // Very fast device.
        r = SCRYPT_MAX_CLIENT_R;

        // Need to adjust scryptN to make scrypt even stronger:
        unsigned int numShifts = (SCRYPT_TARGET_USECONDS / SCRYPT_MAX_CLIENT_R) /
                                 totalTime;
        numShifts--;

        if (SCRYPT_MAX_CLIENT_N_SHIFT < numShifts + SCRYPT_DEFAULT_CLIENT_N_SHIFT)
        {
            diffShift = numShifts + SCRYPT_DEFAULT_CLIENT_N_SHIFT -
                        SCRYPT_MAX_CLIENT_N_SHIFT;
            n = (1 << SCRYPT_MAX_CLIENT_N_SHIFT);
        }
        else
        {
            n = (1 << (numShifts + SCRYPT_DEFAULT_CLIENT_N_SHIFT));
        }

        ABC_DebugLevel(1, "Scrypt timing: Fast device diffShift:%d n:%d", diffShift, n);
    }

    if (diffShift)
    {
        int addP = diffShift;
        ABC_DebugLevel(1, "Scrypt timing: Fast device addP:%d", addP);
        p += addP;
    }

    ABC_DebugLevel(1, "NRp = %d %d %d", n, r, p);

    return Status();
}