QString MTContactHandler::GetContactName(int nContactID)
{
    QMutexLocker locker(&m_Mutex);

    QString str_select = QString("SELECT `contact_display_name` FROM `contact` WHERE `contact_id`='%1' LIMIT 0,1").arg(nContactID);

    int nRows = DBHandler::getInstance()->querySize(str_select);

    for(int ii=0; ii < nRows; ii++)
    {
        //Extract data
        QString contact_name = DBHandler::getInstance()->queryString(str_select, 0, ii);

        if (!contact_name.isEmpty())
        {
//          qDebug() << QString("About to decode name: %1").arg(contact_name);

            //Decode base64.
            OTASCIIArmor ascName;
            ascName.Set(contact_name.toStdString().c_str());
            OTString strName(ascName);
            contact_name = QString(strName.Get());
        }
        //---------------------------------------------------
        return contact_name; // In practice there should only be one row.
    }

    return ""; // Didn't find anyone.
}
Пример #2
0
// This version base64-DECODES the ascii-armored string passed in,
// and then sets the decoded plaintext string onto this object.
String::String(const OTASCIIArmor& strValue)
    : length_(0)
    , position_(0)
    , data_(nullptr)
{
    //    Initialize();

    if (strValue.Exists()) strValue.GetString(*this);
}
Пример #3
0
// static
bool OTKeyring::KWallet_RetrieveSecret(const OTString& strUser,
                                       OTPassword& thePassword,
                                       const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    KWallet::Wallet* pWallet = OTKeyring::OpenKWallet();

    if (nullptr != pWallet) {
        const QString qstrKey(strUser.Get());
        QString qstrPwd;

        // Get the password
        //
        if (pWallet->readPassword(qstrKey, qstrPwd) == 0) {
            const std::string str_password =
                qstrPwd.toStdString(); // todo security: notice str_password
                                       // isn't zero'd here.

            OTString strData(str_password);
            OTASCIIArmor ascData;

            const bool bLoaded =
                strData.Exists() && ascData.LoadFromString(strData);
            strData.zeroMemory();

            if (!bLoaded)
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "from KWallet contents.\n";
            else {
                OTData thePayload(ascData);
                ascData.zeroMemory();
                if (thePayload.IsEmpty())
                    otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                             "OTData from OTASCIIArmor from "
                                             "KWallet contents.\n";
                else {
                    thePassword.setMemory(thePayload.GetPayloadPointer(),
                                          thePayload.GetSize());
                    thePayload.zeroMemory(); // for security.
                    return true;
                }
            }
        }
        else
            otErr << __FUNCITON__
                  << ": Failed trying to retrieve secret from KWallet.\n";
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otWarn << "OTKeyring::KWallet_RetrieveSecret: No secret found.\n";

    return false;
}
Пример #4
0
int OTPurse::ProcessXMLNode(irr::io::IrrXMLReader*& xml)
{
    if (!strcmp("purse", xml->getNodeName()))
    {
        OTString strServerID, strUserID, strAssetID, strTotalValue;


        m_strVersion	= xml->getAttributeValue("version");
        strUserID		= xml->getAttributeValue("userID");
        strServerID		= xml->getAttributeValue("serverID");
        strAssetID		= xml->getAttributeValue("assetTypeID");
        strTotalValue	= xml->getAttributeValue("totalValue");

        m_AssetID.SetString(strAssetID);
        m_UserID.SetString(strUserID);
        m_ServerID.SetString(strServerID);

        m_lTotalValue = 0;

        if (strTotalValue.Exists() && (atol(strTotalValue.Get()) > 0))
            m_lTotalValue = atol(strTotalValue.Get());

        OTLog::vOutput(4, "Loaded purse...\n ServerID: %s\n UserID: %s\n Asset ID: %s\n----------\n", strServerID.Get(),
                       strUserID.Get(), strAssetID.Get());

        return 1;
    }

    else if (!strcmp("token", xml->getNodeName()))
    {
        OTASCIIArmor * pArmor = new OTASCIIArmor;

        OT_ASSERT(NULL != pArmor);

        if (!LoadEncodedTextField(xml, *pArmor) || !pArmor->Exists())
        {
            OTLog::Error("Error in OTPurse::ProcessXMLNode: token field without value.\n");

            delete pArmor;
            pArmor = NULL;

            return (-1); // error condition
        }
        else
        {
            m_dequeTokens.push_front(pArmor);
        }

        return 1;
    }

    return 0;
}
Пример #5
0
void OTSubkey::UpdateContents()
{
    m_xmlUnsigned.Release();

    Tag tag("keyCredential");

    // a hash of the nymIDSource
    tag.add_attribute("nymID", GetNymID().Get());
    // Hash of the master credential that signed this subcredential.
    tag.add_attribute("masterID", GetMasterCredID().Get());

    if (GetNymIDSource().Exists()) {
        OTASCIIArmor ascSource;
        // A nym should always verify through its own
        // source. (Whatever that may be.)
        ascSource.SetString(GetNymIDSource());
        tag.add_tag("nymIDSource", ascSource.Get());
    }
    // MASTER-SIGNED INFO
    if (OTSubcredential::credMasterSigned == m_StoreAs ||
        OTSubcredential::credPrivateInfo == m_StoreAs) {
        UpdatePublicContentsToTag(tag);
    }
    // PUBLIC INFO (signed by subkey, contains master signed info.)
    if (OTSubcredential::credPublicInfo == m_StoreAs ||
        OTSubcredential::credPrivateInfo == m_StoreAs) {
        // GetMasterSigned() returns the contract
        // containing the master-signed contents
        // from the above block.
        OTASCIIArmor ascMasterSigned(GetMasterSigned());

        // Contains all the public info, signed by the master key.
        // Packaged up here inside a final, subkey-signed credential.
        tag.add_tag("masterSigned", ascMasterSigned.Get());
    }
    // PRIVATE INFO
    //
    // If we're saving the private credential info...
    if (OTSubcredential::credPrivateInfo == m_StoreAs) {
        UpdatePublicCredentialToTag(tag);
        UpdatePrivateContentsToTag(tag);
    }

    // <=== SET IT BACK TO DEFAULT BEHAVIOR. Any other state
    // processes ONCE, and then goes back to this again.
    m_StoreAs = OTSubcredential::credPrivateInfo;

    std::string str_result;
    tag.output(str_result);

    m_xmlUnsigned.Concatenate("%s", str_result.c_str());
}
Пример #6
0
// SignContract will call this function at the right time.
void OTLedger::UpdateContents() // Before transmission or serialization, this is where the ledger saves its contents 
{
	// Notice I use the PURPORTED Account ID and Server ID to create the output. That's because
	// I don't want to inadvertantly substitute the real ID for a bad one and then sign it.
	// So if there's a bad one in there when I read it, THAT's the one that I write as well!
	OTString strType, strLedgerAcctID(GetPurportedAccountID()), strLedgerAcctServerID(GetPurportedServerID()),
		strUserID(GetUserID());
	
	switch (m_Type) {
		case OTLedger::message:
			strType.Set("message");
			break;
		case OTLedger::inbox:
			strType.Set("inbox");
			break;
		case OTLedger::outbox:
			strType.Set("outbox");
			break;
		default:
			strType.Set("error-unknown");
			break;
	}
	
	// I release this because I'm about to repopulate it.
	m_xmlUnsigned.Release();
	
	//	m_xmlUnsigned.Concatenate("<?xml version=\"%s\"?>\n\n", "1.0");		
	
	m_xmlUnsigned.Concatenate("<accountLedger version=\"%s\"\n type=\"%s\"\n accountID=\"%s\"\n userID=\"%s\"\n"
							  "serverID=\"%s\" >\n\n", m_strVersion.Get(), strType.Get(), 
							  strLedgerAcctID.Get(), strUserID.Get(), strLedgerAcctServerID.Get());		
	
	// loop through the transactions and print them out here.
	OTTransaction * pTransaction = NULL;
	
	for (mapOfTransactions::iterator ii = m_mapTransactions.begin(); 
		 ii != m_mapTransactions.end(); ++ii)
	{
		if ((pTransaction = (*ii).second)) // if pointer not null
		{
			OTString strTransaction;
			pTransaction->SaveContract(strTransaction);
			
			OTASCIIArmor ascTransaction;
			ascTransaction.SetString(strTransaction, true); // linebreaks = true
			
			m_xmlUnsigned.Concatenate("<transaction>\n%s</transaction>\n\n", ascTransaction.Get());
		}
	}
	
	m_xmlUnsigned.Concatenate("</accountLedger>\n");				
}
Пример #7
0
void OTSubkey::UpdateContents()
{
	m_xmlUnsigned.Release();
    
	m_xmlUnsigned.Concatenate("<keyCredential nymID=\"%s\"\n" // a hash of the nymIDSource
							  " masterCredentialID=\"%s\" >\n\n", // Hash of the master credential that signed this subcredential.
							  this->GetNymID().Get(), this->GetMasterCredID().Get());
    
    if (this->GetNymIDSource().Exists())
    {
        OTASCIIArmor ascSource;
        ascSource.SetString(this->GetNymIDSource()); // A nym should always verify through its own source. (Whatever that may be.)
        m_xmlUnsigned.Concatenate("<nymIDSource>\n%s</nymIDSource>\n\n", ascSource.Get());
    }
    // --------------------------------------------
    // MASTER-SIGNED INFO
    //
    if ((OTSubcredential::credMasterSigned == m_StoreAs) || // MASTER-SIGNED INFO
        (OTSubcredential::credPrivateInfo  == m_StoreAs))
    {
        // --------------------------------------------
        this->UpdateMasterPublicToString(m_xmlUnsigned);
        // --------------------------------------------
        this->UpdatePublicContentsToString(m_xmlUnsigned);
    }
    // --------------------------------------------
    // PUBLIC INFO
    //
    if ((OTSubcredential::credPublicInfo  == m_StoreAs)  || // PUBLIC INFO (signed by subkey, contains master signed info.)
        (OTSubcredential::credPrivateInfo == m_StoreAs))
    {
        OTASCIIArmor ascMasterSigned(this->GetMasterSigned()); // GetMasterSigned() returns the contract containing the master-signed contents from the above block.
        m_xmlUnsigned.Concatenate("<masterSigned>\n%s</masterSigned>\n\n", // Contains all the public info, signed by the master key.
                                  ascMasterSigned.Get());                  // Packaged up here inside a final, subkey-signed credential.
    }
	// -------------------------------------------------
    // PRIVATE INFO
    //
    // If we're saving the private credential info...
    // 
    if (OTSubcredential::credPrivateInfo == m_StoreAs)  // PRIVATE INFO
    {
        this->UpdatePublicCredentialToString(m_xmlUnsigned);
        // -------------------------------------
        this->UpdatePrivateContentsToString(m_xmlUnsigned);
    }
	// -------------------------------------------------	
	m_xmlUnsigned.Concatenate("</keyCredential>\n");
    // --------------------------------------------
    m_StoreAs = OTSubcredential::credPrivateInfo;  // <=== SET IT BACK TO DEFAULT BEHAVIOR. Any other state processes ONCE, and then goes back to this again.
}
Пример #8
0
void OTClause::Serialize(Tag& parent) const
{
    OTASCIIArmor ascCode;

    if (m_strCode.GetLength() > 2)
        ascCode.SetString(m_strCode);
    else
        otErr << "Empty script code in OTClause::Serialize()\n";

    TagPtr pTag(new Tag("clause", ascCode.Get()));

    pTag->add_attribute("name", m_strName.Get());

    parent.add_tag(pTag);
}
Пример #9
0
bool OTToken::GetPrototoken(OTASCIIArmor & ascPrototoken, int nTokenIndex)
{

	// out of bounds. For a count 10 element array, index 10 is out of bounds.
	// thus if attempted index is equal or larger to the count, out of bounds.
	if (nTokenIndex >= m_nTokenCount)
	{
		return false;
	}
//	OTLog::vError("DEBUG OTToken::GetPrototoken. nTokenIndex is %d. m_nTokenCount is %d\n------------------------\n",
//			nTokenIndex, m_nTokenCount);
	
	// loop through the items that make up this transaction and print them out here, base64-encoded, of course.
	OTASCIIArmor * pPrototoken = NULL;
	
	for (mapOfPrototokens::iterator ii = m_mapPublic.begin(); ii != m_mapPublic.end(); ++ii)
	{
		pPrototoken = (*ii).second;
		
		OT_ASSERT(NULL != pPrototoken);
		
		const bool bSuccess = (nTokenIndex == (*ii).first);
		
//		OTLog::vError("DEBUG OTToken::GetPrototoken ABOUT TO ENTER, index: %d\n", nTokenIndex);
		
		if (bSuccess)
		{
			ascPrototoken.Set(*pPrototoken);
//			OTLog::vError("DEBUG OTToken::GetPrototoken INNER SANCTUM\n PROTOKEN:"
//						"\n-----------%s-----------\n", ascPrototoken.Get());
			return true;
		}
	}
	return false;	
}
bool OTServerContract::SaveContractWallet(OTString & strContents) const
{
	const OTString strID(m_ID);
	OTASCIIArmor   ascName;
	
	if (m_strName.Exists()) // name is in the clear in memory, and base64 in storage.
	{
		ascName.SetString(m_strName, false); // linebreaks == false
	}
	strContents.Concatenate("<notaryProvider name=\"%s\"\n"
							" serverID=\"%s\" />\n\n",
							m_strName.Exists() ? ascName.Get() : "",
							strID.Get());
	
	return true;
}
Пример #11
0
bool OTToken::GetPrivatePrototoken(OTASCIIArmor & ascPrototoken, int nTokenIndex)
{
	// out of bounds. For a count 10 element array, index 10 is out of bounds.
	// thus if attempted index is equal or larger to the count, out of bounds.
	if (nTokenIndex >= m_nTokenCount)
	{
		return false;
	}
	
	// loop through the items that make up this transaction and print them out here, base64-encoded, of course.
	OTASCIIArmor * pPrototoken = NULL;
	
	for (mapOfPrototokens::iterator ii = m_mapPrivate.begin(); ii != m_mapPrivate.end(); ++ii)
	{
		pPrototoken = (*ii).second;
		
		OT_ASSERT(NULL != pPrototoken);
		
		const bool bSuccess = (nTokenIndex == (*ii).first);
		
		if (bSuccess)
		{
			ascPrototoken.Set(*pPrototoken);
			return true;
		}
	}
	return false;	
}
Пример #12
0
void OTMasterkey::UpdateContents()
{
    m_xmlUnsigned.Release();

    Tag tag("masterCredential");

    // a hash of the nymIDSource
    tag.add_attribute("nymID", GetNymID().Get());

    if (GetNymIDSource().Exists()) {
        OTASCIIArmor ascSource;
        ascSource.SetString(GetNymIDSource()); // A nym should always
                                               // verify through its own
                                               // source. (Whatever that
                                               // may be.)
        tag.add_tag("nymIDSource", ascSource.Get());
    }

    // PUBLIC INFO
    //
    //  if (OTSubcredential::credPublicInfo == m_StoreAs)   // PUBLIC INFO
    // (Always save this in every state.)
    {
        UpdatePublicContentsToTag(tag);
    }

    // PRIVATE INFO
    //
    // If we're saving the private credential info...
    //
    if (OTSubcredential::credPrivateInfo == m_StoreAs) // PRIVATE INFO
    {
        UpdatePublicCredentialToTag(tag);
        UpdatePrivateContentsToTag(tag);
    }
    // -------------------------------------------------
    std::string str_result;
    tag.output(str_result);

    m_xmlUnsigned.Concatenate("%s", str_result.c_str());

    m_StoreAs = OTSubcredential::credPrivateInfo; // <=== SET IT BACK TO DEFAULT
                                                  // BEHAVIOR. Any other state
                                                  // processes ONCE, and then
                                                  // goes back to this again.
}
Пример #13
0
// static
bool OTKeyring::FlatFile_RetrieveSecret(const String& strUser,
                                        OTPassword& thePassword,
                                        const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());
    const std::string str_pw_folder(OTKeyring::FlatFile_GetPasswordFolder());
    if (!str_pw_folder.empty()) {
        String strExactPath;
        strExactPath.Format("%s%s%s", str_pw_folder.c_str(),
                            Log::PathSeparator(), strUser.Get());
        const std::string str_ExactPath(strExactPath.Get());

        // Get the password
        //
        OTASCIIArmor ascData;

        if (!ascData.LoadFromExactPath(str_ExactPath))
            otErr << "OTKeyring::FlatFile_RetrieveSecret: "
                  << "Failed trying to decode secret from flat file contents."
                  << "\n";
        else {
            OTData thePayload(ascData);
            ascData.zeroMemory();
            if (thePayload.IsEmpty())
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "OTData from OTASCIIArmor from "
                                         "flat file contents.\n";
            else {
                thePassword.setMemory(thePayload.GetPointer(),
                                      thePayload.GetSize());
                thePayload.zeroMemory(); // for security.
                return true;
            }
        }
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otWarn << __FUNCTION__ << ": Unable to retrieve any derived key, since "
                              "password_folder not provided in config file.\n";

    return false;
}
Пример #14
0
// Envelope retrieved from payload.
bool OTPayload::GetEnvelope(OTEnvelope & theEnvelope) const
{
	// validate checksum
	uint32_t lSize = GetSize();
	uint32_t lIndex = lSize-2; // the index to where the NULL terminator SHOULD be if they
						  // sent us a base64-encoded string, containing an encrypted message. (which we expect...)

	// (lSize-1 would be the location of the checksum at the end.)
	if (0 == lSize)
		return false;

	if (IsChecksumValid((OT_BYTE*)GetPointer(), (uint32_t)lSize))
	{
		// We add the null-terminator ourselves at this point, for security reasons,
		// since we will process the data, soon after this function, as a string.
		((OT_BYTE *)GetPointer())[lIndex] = 0;

		theEnvelope.m_dataContents.Release();

		OTASCIIArmor theArmor;
		// Why is this safe, where I cast the Payload data pointer as
		// a char * and tell the data object to set itself from that?
		// Because (1) I just validated the checksum, and
		// (2) There place where the NULL should be, I set to 0, by hand,
		// just above 2 lines. So when this set operation occurs, the
		// farthest it will go is to that 0.
		theArmor.Set((const char *)GetPointer());

		// Todo NOTE: If I ever want to process bookends here instead of assuming they aren't there,
		// IT'S VERY EASY!! All I have to do is call theArmor.LoadFromString instead of theArmor.Set.

		// Now the ascii-armored string that was sent across is decoded back to binary into the
		// Envelope object.
		theEnvelope.SetAsciiArmoredData(theArmor);
		return true;
	}
	else
    {
		OTLog::Error("Invalid Checksum in OTPayload::GetEnvelope\n");
		return false;
	}
}
Пример #15
0
OTCachedKey::OTCachedKey(const OTASCIIArmor & ascCachedKey) :
    m_pThread(NULL),
    m_nTimeoutSeconds(OTCachedKey::It()->GetTimeoutSeconds()),
    m_pMasterPassword(NULL), // This is created in GetMasterPassword, and destroyed by a timer thread sometime soon after. 
    m_bUse_System_Keyring(OTCachedKey::It()->IsUsingSystemKeyring()), // this master key instance will decide to use the system keyring based on what the global master key instance is set to do. (So we get the same settings from config file, etc.)
    m_pSymmetricKey(NULL),   // OTServer OR OTWallet owns this key, and sets this pointer. It's the encrypted form of s_pMasterPassword.
    m_bPaused(false)
{
    OT_ASSERT(ascCachedKey.Exists());
    this->SetCachedKey(ascCachedKey);
}
Пример #16
0
bool AssetContract::SaveContractWallet(Tag& parent) const
{
    const String strID(m_ID);

    // Name is in the clear in memory,
    // and base64 in storage.
    OTASCIIArmor ascName;
    if (m_strName.Exists()) {
        ascName.SetString(m_strName, false); // linebreaks == false
    }

    TagPtr pTag(new Tag("assetType"));

    pTag->add_attribute("name", m_strName.Exists() ? ascName.Get() : "");
    pTag->add_attribute("instrumentDefinitionID", strID.Get());

    parent.add_tag(pTag);

    return true;
}
Пример #17
0
// The contact ID (unlike all the other IDs) is an int instead of a string.
// Therefore we just convert it to a string and return it in a map in the same
// format as all the others.
// (FYI.)
//
bool MTContactHandler::GetContacts(mapIDName & theMap)
{
    QMutexLocker locker(&m_Mutex);

    QString str_select = QString("SELECT * FROM contact");

    bool bFoundAny = false;
    int  nRows     = DBHandler::getInstance()->querySize(str_select);

    for(int ii=0; ii < nRows; ii++)
    {
        int     contact_id   = DBHandler::getInstance()->queryInt   (str_select, 0, ii);
        QString contact_name = DBHandler::getInstance()->queryString(str_select, 1, ii);

        if (contact_id > 0)
        {
            bFoundAny = true;

            QString str_contact_id;
            str_contact_id = QString("%1").arg(contact_id);

            if (!contact_name.isEmpty())
            {
//                qDebug() << QString("About to decode name: %1").arg(contact_name);

                //Decode base64.
                OTASCIIArmor ascName;
                ascName.Set(contact_name.toStdString().c_str());
                OTString strName(ascName);
                contact_name = QString(strName.Get());
            }
            // --------------------------------------------------
            // At this point we have the contact ID (in string form) *and* the contact name.
            // So we can add them to our map...
            theMap.insert(str_contact_id, contact_name);
        }
    }
    // ---------------------------------------------------------------------
    return bFoundAny;
}
Пример #18
0
// Envelope copied into payload to prepare for sending.
bool OTPayload::SetEnvelope(const OTEnvelope & theEnvelope)
{
	OTASCIIArmor theArmor;
	
	if (theEnvelope.GetAsciiArmoredData(theArmor))
	{
		uint32_t lSize = theArmor.GetLength()+1; //+1 for the null terminater
		
		if (theArmor.GetLength())
		{
			SetPayloadSize(lSize + 1); // +1 for the checksum byte.
			
			// Copy it in.
			memcpy((void *)GetPointer(), theArmor.Get(), lSize);
			
			// Add the checksum, success.
			AppendChecksum( (OT_BYTE*)GetPointer(), lSize );
			return true;
		}
	}
	return false;
}
Пример #19
0
bool MTContactHandler::GetNyms(mapIDName & theMap, int nFilterByContact) //resume
{
    QMutexLocker locker(&m_Mutex);

    QString str_select = QString("SELECT * FROM `nym` WHERE `contact_id`='%1'").arg(nFilterByContact);
//  QString str_select = QString("SELECT * FROM `nym` WHERE `contact_id`='%1' LIMIT 0,1").arg(nFilterByContact);

    bool bFoundAny = false;
    int  nRows     = DBHandler::getInstance()->querySize(str_select);

    for (int ii=0; ii < nRows; ii++)
    {
        QString nym_id   = DBHandler::getInstance()->queryString(str_select, 0, ii);
        QString nym_name = DBHandler::getInstance()->queryString(str_select, 2, ii);

        if (!nym_id.isEmpty())
        {
            bFoundAny = true;

            if (!nym_name.isEmpty())
            {
//              qDebug() << QString("About to decode name: %1").arg(nym_name);
                //Decode base64.
                OTASCIIArmor ascName;
                ascName.Set(nym_name.toStdString().c_str());
                OTString strName(ascName);
                nym_name = QString(strName.Get());
            }
            // ----------------------------
            // At this point we have the nym ID *and* the nym name.
            // So we can add them to our map...
            theMap.insert(nym_id, nym_name);
        }
    }
    // ---------------------------------------------------------------------
    return bFoundAny;
}
Пример #20
0
void OTMasterkey::UpdateContents() 
{
	m_xmlUnsigned.Release();
    
	m_xmlUnsigned.Concatenate("<masterCredential nymID=\"%s\" >\n\n", // a hash of the nymIDSource
							  this->GetNymID().Get());
    
    if (this->GetNymIDSource().Exists())
    {
        OTASCIIArmor ascSource;
        ascSource.SetString(this->GetNymIDSource()); // A nym should always verify through its own source. (Whatever that may be.)
        m_xmlUnsigned.Concatenate("<nymIDSource>\n%s</nymIDSource>\n\n", ascSource.Get());
    }
    // --------------------------------------------
    // PUBLIC INFO
    //
//  if (OTSubcredential::credPublicInfo == m_StoreAs)   // PUBLIC INFO  (Always save this in every state.)
    {        
        this->UpdatePublicContentsToString(m_xmlUnsigned);
    }
	// -------------------------------------------------
    // PRIVATE INFO
    //
    // If we're saving the private credential info...
    // 
    if (OTSubcredential::credPrivateInfo == m_StoreAs)   // PRIVATE INFO
    {
        this->UpdatePublicCredentialToString(m_xmlUnsigned);
        // -------------------------------------
        this->UpdatePrivateContentsToString(m_xmlUnsigned);
    }
	// -------------------------------------------------	
	m_xmlUnsigned.Concatenate("</masterCredential>\n");
    // --------------------------------------------
    m_StoreAs = OTSubcredential::credPrivateInfo;  // <=== SET IT BACK TO DEFAULT BEHAVIOR. Any other state processes ONCE, and then goes back to this again.
}
Пример #21
0
bool OTEnvelope::SetFromBookendedString(const OTString & strArmorWithBookends, // input
                                              bool       bEscaped/*=false*/)
{
    OTASCIIArmor theArmoredText;
    const bool   bLoaded = theArmoredText.LoadFromString(const_cast<OTString &>(strArmorWithBookends), bEscaped); //std::string str_override="-----BEGIN");
    
    if (bLoaded)
    {
        // This function will base64 DECODE theArmoredText's string contents
        // and return them as binary in m_dataContents
        const bool bGotData = theArmoredText.GetData(m_dataContents, true); // bLineBreaks = true

        if (!bGotData)
            OTLog::vError("%s: Failed while calling: "
                          "theArmoredText.GetData\n", __FUNCTION__);
        else
            return true;
    }
    else
        OTLog::vError("%s: Failed while calling: "
                      "theArmoredText.LoadFromString\n", __FUNCTION__);
    // -----------------------------
    return false;
}
Пример #22
0
// Let's say you don't know if the input string is raw base64, or if it has bookends
// on it like -----BEGIN BLAH BLAH ...
// And if it DOES have Bookends, you don't know if they are escaped:  - -----BEGIN ...
// Let's say you just want an easy function that will figure that crap out, and load the
// contents up properly into an OTASCIIArmor object. (That's what this function will do.)
//
// str_bookend is a default.
// So you could make it more specific like, -----BEGIN ENCRYPTED KEY (or whatever.)
//
//static
bool OTASCIIArmor::LoadFromString(OTASCIIArmor & ascArmor, const OTString & strInput, const std::string str_bookend/*="-----BEGIN"*/)
{
    // -----------------------------------------------------
    if (strInput.Contains(str_bookend)) // YES there are bookends around this.
    {
        const std::string str_escaped("- " + str_bookend);
        // -----------------------------------
        const bool bEscaped = strInput.Contains(str_escaped);
        // -----------------------------------        
        OTString strLoadFrom(strInput);
        
        if (!ascArmor.LoadFromString(strLoadFrom, bEscaped)) // removes the bookends so we have JUST the coded part.
        {
//          OTLog::vError("%s: Failure loading string into OTASCIIArmor object:\n\n%s\n\n",
//                        __FUNCTION__, strInput.Get());
            return false;
        }
    }
    else
        ascArmor.Set(strInput.Get());
	// -------------------------------------------------    
    
    return true;
}
Пример #23
0
bool OTEnvelope::GetAsBookendedString(OTString & strArmorWithBookends, // output (if successful.)
                                      bool       bEscaped/*=false*/) const
{
    OTASCIIArmor theArmoredText;
    // This function will base64 ENCODE m_dataContents, and then
    // Set() that as the string contents on theArmoredText.
	const bool   bSetData = theArmoredText.SetData(m_dataContents, true);//bLineBreaks=true (by default anyway.)
    
    if (bSetData)
    {
        const bool bWritten = theArmoredText.WriteArmoredString(strArmorWithBookends, "ENVELOPE", // todo hardcoded
                                                                bEscaped);
        if (!bWritten)
            OTLog::vError("%s: Failed while calling: "
                          "theArmoredText.WriteArmoredString\n", __FUNCTION__);
        else
            return true;
    }
    else
        OTLog::vError("%s: Failed while calling: "
                      "theArmoredText.SetData(m_dataContents, true)\n", __FUNCTION__);
    
    return false;
}
Пример #24
0
// Called by OTServer or OTWallet, or whatever instantiates those.
//
void OTCachedKey::SetCachedKey(const OTASCIIArmor & ascCachedKey)
{
    tthread::lock_guard<tthread::mutex> lock(m_Mutex); // Multiple threads can't get inside here at the same time.    

    OT_ASSERT(ascCachedKey.Exists());    
    // ----------------------------------------
    
    if (NULL != m_pSymmetricKey)
    {
        OTLog::Error("OTCachedKey::SetCachedKey: Warning: This was already set. (Re-setting.)\n");
        delete m_pSymmetricKey;
        m_pSymmetricKey = NULL;
    }
    // -----------------------------------------
    m_pSymmetricKey = new OTSymmetricKey;
    OT_ASSERT(NULL != m_pSymmetricKey);
    // ----------------------------------
    
    //const bool bSerialized = 
    m_pSymmetricKey->SerializeFrom(ascCachedKey);
}
Пример #25
0
// static
bool OTKeyring::Gnome_RetrieveSecret(const OTString& strUser,
                                     OTPassword& thePassword,
                                     const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    GnomeKeyringResult theResult = GNOME_KEYRING_RESULT_IO_ERROR;
    gchar* gchar_p_password = nullptr;

    // if the password exists in the keyring, set it in
    // thePassword (output argument.)
    //
    int32_t nCount = -1;
    int64_t lSleep = 1;

    while ((GNOME_KEYRING_RESULT_OK != theResult)) {
        ++nCount; // 0 on first iteration.

        theResult = gnome_keyring_find_password_sync(
            GNOME_KEYRING_NETWORK_PASSWORD, &gchar_p_password, "user",
            strUser.Get(), "protocol", "opentxs", // todo: hardcoding.
            nullptr);

        if (GNOME_KEYRING_RESULT_OK == theResult) break;

        if (nCount > 2) // todo hardcoding.
            break;      // we try a few times -- not infinite times!

        OTString strGnomeError(gnome_keyring_result_to_message(theResult));

        //        OTString strGnomeError;
        //        switch (theResult) {
        //            case GNOME_KEYRING_RESULT_OK: strGnomeError
        // = "GNOME_KEYRING_RESULT_OK"; break;
        //            case GNOME_KEYRING_RESULT_DENIED: strGnomeError
        // = "GNOME_KEYRING_RESULT_DENIED"; break;
        //            case GNOME_KEYRING_RESULT_NO_KEYRING_DAEMON: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_KEYRING_DAEMON"; break;
        //            case GNOME_KEYRING_RESULT_ALREADY_UNLOCKED: strGnomeError
        // = "GNOME_KEYRING_RESULT_ALREADY_UNLOCKED"; break;
        //            case GNOME_KEYRING_RESULT_NO_SUCH_KEYRING: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_SUCH_KEYRING"; break;
        //            case GNOME_KEYRING_RESULT_BAD_ARGUMENTS: strGnomeError
        // = "GNOME_KEYRING_RESULT_BAD_ARGUMENTS"; break;
        //            case GNOME_KEYRING_RESULT_IO_ERROR: strGnomeError
        // = "GNOME_KEYRING_RESULT_IO_ERROR"; break;
        //            case GNOME_KEYRING_RESULT_CANCELLED: strGnomeError
        // = "GNOME_KEYRING_RESULT_CANCELLED"; break;
        //            case GNOME_KEYRING_RESULT_KEYRING_ALREADY_EXISTS:
        // strGnomeError = "GNOME_KEYRING_RESULT_KEYRING_ALREADY_EXISTS"; break;
        //            case GNOME_KEYRING_RESULT_NO_MATCH: strGnomeError
        // = "GNOME_KEYRING_RESULT_NO_MATCH"; break;
        //
        //            default:
        //                strGnomeError = "Unknown! Very strange!";
        //                break;
        //        }

        otErr << __FUNCTION__ << ": gnome_keyring_find_password_sync returned "
              << strGnomeError.Get() << '\n';
        otErr << "Remedy: Sleeping for " << lSleep
              << " seconds and then retrying (attempt " << (nCount + 2) << '\n';
        // on first iteration, nCount is 0, and this will say "attempt 2" aka
        // "second attempt," which is correct.

        sleep(lSleep);
        lSleep *= 2; // double it each time
    }

    if ((theResult == GNOME_KEYRING_RESULT_OK) &&
        (nullptr != gchar_p_password)) {
        size_t sizePassword =
            OTString::safe_strlen(gchar_p_password, MAX_STRING_LENGTH);

        if (sizePassword > 0) {
            OTString strData(gchar_p_password, sizePassword);

            gnome_keyring_free_password(gchar_p_password);
            gchar_p_password = nullptr;

            OTASCIIArmor ascData;
            const bool bLoaded =
                strData.Exists() && ascData.LoadFromString(strData);
            strData.zeroMemory();

            if (!bLoaded)
                otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                         "from Gnome Keyring contents:\n\n"
                      << strData.Get() << "\n\n";
            else {
                OTData thePayload(ascData);
                ascData.zeroMemory();
                if (thePayload.IsEmpty())
                    otErr << __FUNCTION__ << ": Failed trying to decode secret "
                                             "OTData from OTASCIIArmor "
                          << "from Gnome Keyring contents:\n\n" << strData.Get()
                          << "\n\n";
                else {
                    thePassword.setMemory(thePayload.GetPayloadPointer(),
                                          thePayload.GetSize());
                    thePayload.zeroMemory(); // for security.
                    return true;
                }
                return false;
            }
        }
    }

    // Not an error: what if it just hasn't been set there yet?
    //
    otOut << "OTKeyring::Gnome_RetrieveSecret: "
          << "No secret found: gnome_keyring_find_password_sync: "
          << gnome_keyring_result_to_message(theResult) << '\n';

    return false;
}
Пример #26
0
// static
bool OTKeyring::Windows_RetrieveSecret(const OTString& strUser,
                                       OTPassword& thePassword,
                                       const std::string& str_display)
{
    OT_ASSERT(strUser.Exists());

    OTString strFoldername("win32_data"); // todo hardcoding.
    OTASCIIArmor ascFileContents;
    bool bLoaded = (strFoldername.Exists() &&
                    ascFileContents.LoadFromFile(strFoldername, strUser) &&
                    ascFileContents.Exists());
    if (!bLoaded) {
        otWarn << "%s: No cached ciphertext of master key loaded during "
                  "attempted retrieval. "
                  "(However, once one is available, it WILL be cached using "
                  "DPAPI.) \n";
        return false;
    }
    // Below this point, we know for sure the ciphertext of the master
    // key loaded, and exists.
    //
    const OTData theCipherblob(ascFileContents);
    //
    if (theCipherblob.IsEmpty()) {
        otErr << __FUNCTION__ << ": Error: OTData is empty after decoding "
                                 "OTASCIIArmor (that wasn't empty.)\n";
    }
    else {
        DATA_BLOB input;
        input.pbData = const_cast<BYTE*>(
            reinterpret_cast<const BYTE*>(theCipherblob.GetPayloadPointer()));
        input.cbData = static_cast<DWORD>(theCipherblob.GetSize());

        //      CRYPTPROTECT_PROMPTSTRUCT PromptStruct;
        //      ZeroMemory(&PromptStruct, sizeof(PromptStruct));
        //      PromptStruct.cbSize = sizeof(PromptStruct);
        //      PromptStruct.dwPromptFlags = CRYPTPROTECT_PROMPT_ON_PROTECT;
        //      PromptStruct.szPrompt = L"This is a user prompt.";

        //      LPWSTR pDescrOut = nullptr;

        DATA_BLOB output;
        BOOL result = CryptUnprotectData(&input, nullptr, // &pDescrOut
                                         nullptr,         // optional entropy
                                         nullptr,         // reserved
                                         nullptr,         //&PromptStruct
                                         0, &output);
        if (!result) {
            otErr << __FUNCTION__
                  << ": Error: Output of Win32 CryptUnprotectData was empty.\n";
        }
        else {
            thePassword.setMemory(reinterpret_cast<void*>(output.pbData),
                                  static_cast<uint32_t>(output.cbData));
            SecureZeroMemory(output.pbData, output.cbData);
            LocalFree(output.pbData);
            //          LocalFree(pDescrOut);
            return true;
        }
    }

    return false;
}
Пример #27
0
// Loops through ALL markets, and calls pMarket->GetNym_OfferList(NYM_ID, *pOfferList) for each.
// Returns a list of all the offers that a specific Nym has on all the markets.
//
bool OTCron::GetNym_OfferList(OTASCIIArmor & ascOutput, const OTIdentifier & NYM_ID, int & nOfferCount)
{
    nOfferCount = 0; // Outputs the number of offers on this nym.
    
    // ---------------------------
    
	OTDB::OfferListNym * pOfferList  = dynamic_cast<OTDB::OfferListNym*>(OTDB::CreateObject(OTDB::STORED_OBJ_OFFER_LIST_NYM));
	OTCleanup<OTDB::OfferListNym> theListAngel(*pOfferList);
	
	// -----------------------------------------------------------
	
	for (mapOfMarkets::iterator ii = m_mapMarkets.begin(); ii != m_mapMarkets.end(); ++ii)
	{
		OTMarket * pMarket = (*ii).second;
		
		OT_ASSERT(NULL != pMarket);
		
        int nNymOfferCount = 0;
        
		if (false == pMarket->GetNym_OfferList(NYM_ID, *pOfferList, nNymOfferCount)) // appends to *pOfferList, each iteration.
		{
				// may wish to add a log later. Anyway, keep iterationg and appending, then send back whatever we have.
		}
        else // Success!
            nOfferCount += nNymOfferCount;
	}		
	
	// -------------------------------------------------------------
	
	// Now pack the list into strOutput...
    if (nOfferCount == 0)
        return true; // Success, but 0 offers being returned. (List is empty.)
    
    else if (nOfferCount > 0)
    {
        OTDB::Storage * pStorage = OTDB::GetDefaultStorage();
        OT_ASSERT(NULL != pStorage);
        
        OTDB::OTPacker * pPacker = pStorage->GetPacker(); // No need to check for failure, since this already ASSERTS. No need to cleanup either.
        
        // -----------------------------
        
        OTDB::PackedBuffer * pBuffer = pPacker->Pack(*pOfferList); // Now we PACK our nym's offer list.
        
        if (NULL == pBuffer)
        {
            OTLog::Error("Failed packing pOfferList in OTCron::GetNym_OfferList. \n");
            return false;
        }
        
        OTCleanup<OTDB::PackedBuffer> theBufferAngel(*pBuffer); // make sure memory is cleaned up.
        
        // --------------------------------------------------------	
        
        // Now we need to translate pBuffer into strOutput.
        
        const uint8_t* pUint = static_cast<const uint8_t*>(pBuffer->GetData());
        const size_t theSize = pBuffer->GetSize();
        
        if ((NULL != pUint) || (theSize < 2))
        {
            OTData theData(pUint, theSize);
            
            // This function will base64 ENCODE theData,
            // and then Set() that as the string contents.
            ascOutput.SetData(theData);
            
            return true;
        }
        else 
            OTLog::Error("Null returned, or bad size, while getting buffer data in OTCron::GetNym_OfferList.\n");
	}
    
    else
        OTLog::vError("Error: Less-than-zero nOfferCount in OTCron::GetNym_OfferList: %d.\n", nOfferCount); 
    
	return false;	
}
Пример #28
0
OTData::OTData(const OTASCIIArmor &theSource) : m_pData(NULL), m_lPosition(0), m_lSize(0)
{	
	if (theSource.Exists())
		theSource.GetData(*this); // ***********
}
Пример #29
0
bool OTCron::GetMarketList (OTASCIIArmor & ascOutput, int & nMarketCount)
{
    nMarketCount        = 0; // This parameter is set to zero here, and incremented in the loop below.
    
    // ------------------------
	OTMarket * pMarket  = NULL;

	OTDB::MarketList * pMarketList  = dynamic_cast<OTDB::MarketList*>(OTDB::CreateObject(OTDB::STORED_OBJ_MARKET_LIST));
	OTCleanup<OTDB::MarketList> theListAngel(*pMarketList);

	// -----------------------------------------------------------
	    
	for (mapOfMarkets::iterator ii = m_mapMarkets.begin(); ii != m_mapMarkets.end(); ++ii)
	{
		pMarket = (*ii).second;
		
		OT_ASSERT(NULL != pMarket);
		
		OTDB::MarketData * pMarketData  = dynamic_cast<OTDB::MarketData *>(OTDB::CreateObject(OTDB::STORED_OBJ_MARKET_DATA));
		OTCleanup<OTDB::MarketData> theDataAngel(*pMarketData);
		
		// --------------------------------------------
		const OTIdentifier	MARKET_ID(*pMarket);
		const OTString		str_MARKET_ID(MARKET_ID);
		const OTString		str_ServerID(pMarket->GetServerID());
		const OTString		str_ASSET_ID(pMarket->GetAssetID());
		const OTString		str_CURRENCY_ID(pMarket->GetCurrencyID());
		
		pMarketData->server_id			= str_ServerID.Get();
		pMarketData->market_id			= str_MARKET_ID.Get();
		pMarketData->asset_type_id		= str_ASSET_ID.Get();
		pMarketData->currency_type_id	= str_CURRENCY_ID.Get();
		// --------------------------------------------		
		const long & lScale	= pMarket->GetScale();
		
		pMarketData->scale				= to_string<long>(lScale);
		
		// --------------------------------------------
		
		const uint64_t theCurrentBid	= pMarket->GetHighestBidPrice();
		const uint64_t theCurrentAsk	= pMarket->GetLowestAskPrice();
		
		pMarketData->current_bid		= to_string<uint64_t>(theCurrentBid);
		pMarketData->current_ask		= to_string<uint64_t>(theCurrentAsk);
		
		// ---------------------------------------------
		
		const long &	lLastSalePrice			= pMarket->GetLastSalePrice();
		const long &	lTotalAvailableAssets	= pMarket->GetTotalAvailableAssets();
		
		pMarketData->total_assets		= to_string<long>(lTotalAvailableAssets);
		pMarketData->last_sale_price	= to_string<long>(lLastSalePrice);

		// ---------------------------------------------
		
		const mapOfOffers::size_type theBidCount = pMarket->GetBidCount();
		const mapOfOffers::size_type theAskCount = pMarket->GetAskCount();
		
		pMarketData->number_bids		= to_string<mapOfOffers::size_type>(theBidCount);
		pMarketData->number_asks		= to_string<mapOfOffers::size_type>(theAskCount);

		// ---------------------------------------------
		// In the past 24 hours.
		// (I'm not collecting this data yet, (maybe never), so these values aren't set at all.)
		//
//		pMarketData->volume_trades		= ???;
//		pMarketData->volume_assets		= ???;
//		pMarketData->volume_currency	= ???;
//		
//		pMarketData->recent_highest_bid	= ???;
//		pMarketData->recent_lowest_ask	= ???;
		// ---------------------------------------------

		// *pMarketData is CLONED at this time (I'm still responsible to delete.)
		// That's also why I add it here, below: So the data is set right before the cloning occurs.
		//
		pMarketList->AddMarketData(*pMarketData);
        nMarketCount++;
	}		
	
	// -------------------------------------------------------------
	
	// Now pack the list into strOutput...
    if (nMarketCount == 0)
        return true; // Success, but the list contains 0 markets.
    
	else if (nMarketCount > 0)
    {
        OTDB::Storage * pStorage = OTDB::GetDefaultStorage();
        OT_ASSERT(NULL != pStorage);
        
        OTDB::OTPacker * pPacker = pStorage->GetPacker(); // No need to check for failure, since this already ASSERTS. No need to cleanup either.
            
        // -----------------------------
        
        OTDB::PackedBuffer * pBuffer = pPacker->Pack(*pMarketList); // Now we PACK our market list.
        
        if (NULL == pBuffer)
        {
            OTLog::Error("Failed packing pMarketList in OTCron::GetMarketList. \n");
            return false;
        }
        
        OTCleanup<OTDB::PackedBuffer> theBufferAngel(*pBuffer); // make sure memory is cleaned up.
        
        // --------------------------------------------------------	
        
        // Now we need to translate pBuffer into strOutput.
        
        const uint8_t* pUint = static_cast<const uint8_t*>(pBuffer->GetData());
        const size_t theSize = pBuffer->GetSize();
        
        if ((theSize > 0) && (NULL != pUint))
        {
            OTData theData(pUint, theSize);

            // This function will base64 ENCODE theData,
            // and then Set() that as the string contents.
            ascOutput.SetData(theData);
//            bool bSuccessSetData = false;
//            bSuccessSetData = ascOutput.SetData(theData);

            return true;
        }
        else 
            OTLog::Error("OTCron::GetMarketList: 0 size, or null return value, while getting raw data from packed buffer.\n");
	}
    
    else
        OTLog::vError("OTCron::GetMarketList: nMarketCount is less than zero: %d.\n", nMarketCount);      
        
	return false;
}
Пример #30
0
bool OTSocket_ZMQ_4::Send(const OTASCIIArmor & ascEnvelope)
{
    if (!m_bInitialized) { OT_FAIL; }

    if (0 >= ascEnvelope.GetLength())  { OTLog::vError("%s: Error: %s is zero length!\n", __FUNCTION__, "ascEnvelope");	OT_FAIL; }
    m_ascLastMsgSent.Set(ascEnvelope); // In case we need to re-send.

    if (!m_HasContext) { OT_FAIL; }
    if (NULL == m_pzmq->context_zmq)  { OTLog::vError("%s: Error: %s must exist to Send!\n", __FUNCTION__, "m_pzmq->context_zmq");	OT_FAIL; }

    if (!m_bConnected && !m_bListening) return false;
    if (m_bConnected && m_bListening) return false;
    if (NULL == m_pzmq->socket_zmq) { OTLog::vError("%s: Error: %s must exist to Send!\n", __FUNCTION__, "m_pzmq->socket_zmq");	OT_FAIL; }


    // -----------------------------------	
    const int64_t lLatencySendMilliSec = m_lLatencySendMs;

    zmq::message_t zmq_message(ascEnvelope.GetLength());
    memcpy((void*)zmq_message.data(), ascEnvelope.Get(), ascEnvelope.GetLength());

    bool bSuccessSending = false;

    if (m_bIsBlocking)
    {
        try {
            bSuccessSending = m_pzmq->socket_zmq->send(zmq_message); // Blocking.
        }
        catch (std::exception& e) {
            OTLog::vError("%s: Exception Caught: %s \n", __FUNCTION__, e.what());
            OT_FAIL;
        }
    }
    else // not blocking
    {
        int32_t		nSendTries = m_nLatencySendNoTries;
        int64_t	lDoubling = lLatencySendMilliSec;
        bool	bKeepTrying = true;

        while (bKeepTrying && (nSendTries > 0))
        {
            zmq::pollitem_t items[] = {
                { (*m_pzmq->socket_zmq), 0, ZMQ_POLLOUT, 0 }
            };

            int nPoll = 0;
            try {
                nPoll = zmq::poll(&items[0], 1, static_cast<long>(lDoubling));	// ZMQ_POLLOUT, 1 item, timeout (milliseconds)	
            }
            catch (std::exception& e) {
                OTLog::vError("%s: Exception Caught: %s \n", __FUNCTION__, e.what());
                OT_FAIL;
            }

            lDoubling *= 2;

            if (items[0].revents & ZMQ_POLLOUT)
            {
                try {
                    bSuccessSending = m_pzmq->socket_zmq->send(zmq_message, ZMQ_NOBLOCK); // <=========== SEND ===============
                }
                catch (std::exception& e) {
                    OTLog::vError("%s: Exception Caught: %s \n", __FUNCTION__, e.what());
                    OT_FAIL;
                }

                OTLog::SleepMilliseconds(1);

                if (!bSuccessSending)
                {
                    if (false == HandleSendingError())
                        bKeepTrying = false;
                }
                else
                    break; // (Success -- we're done in this loop.)
            }
            else if ((-1) == nPoll) // error.
            {
                if (false == HandlePollingError())
                    bKeepTrying = false;
            }

            --nSendTries;
        }
    }
    /*
    Normally, we try to send...
    If the send fails, we wait X ms and then try again (Y times).

    BUT -- what if the failure was an errno==EAGAIN ?
    In that case, it's not a REAL failure, but rather, a "failure right now, try again in a sec."
    */
    // ***********************************

    if (bSuccessSending)
        OTLog::SleepMilliseconds(m_lLatencyDelayAfter > 0 ? m_lLatencyDelayAfter : 1);

    return bSuccessSending;
}