Ejemplo n.º 1
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;	
}
Ejemplo n.º 2
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;	
}
Ejemplo n.º 3
0
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.
}
Ejemplo n.º 4
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 String& strInput,
                                  std::string str_bookend)
{

    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);

        String strLoadFrom(strInput);

        if (!ascArmor.LoadFromString(strLoadFrom, bEscaped)) // removes the
                                                             // bookends so we
                                                             // have JUST the
                                                             // coded part.
        {
            //          otErr << "%s: Failure loading string into OTASCIIArmor
            // object:\n\n%s\n\n",
            //                        __FUNCTION__, strInput.Get());
            return false;
        }
    }
    else
        ascArmor.Set(strInput.Get());

    return true;
}
Ejemplo n.º 5
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;
	}
}
Ejemplo n.º 6
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;
}
Ejemplo n.º 7
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;
}
Ejemplo n.º 8
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;
}
Ejemplo n.º 9
0
 inline	void SetSpendable(const OTASCIIArmor & theArmor) {
     m_ascSpendable.Set(theArmor);
 }
Ejemplo n.º 10
0
int OTSignedFile::ProcessXMLNode(irr::io::IrrXMLReader*& xml)
{
	int nReturnVal = 0;
	
	// Here we call the parent class first.
	// If the node is found there, or there is some error,
	// then we just return either way.  But if it comes back
	// as '0', then nothing happened, and we'll continue executing.
	//
	// -- Note you can choose not to call the parent if
	// you don't want to use any of those xml tags.
	// As I do below, in the case of OTAccount.
	//if (nReturnVal = OTContract::ProcessXMLNode(xml))
	//	return nReturnVal;
	
	if (!strcmp("signedFile", xml->getNodeName())) 
	{		
		m_strVersion			= xml->getAttributeValue("version");	
		
		m_strPurportedLocalDir	= xml->getAttributeValue("localDir");					
		m_strPurportedFilename	= xml->getAttributeValue("filename");					
		
		// ---------------------
				
		nReturnVal = 1;
	}
	
	else if (!strcmp("filePayload", xml->getNodeName())) 
	{
		// go to the next node and read the text.
		xml->read();
		
		if (EXN_TEXT == xml->getNodeType())
		{
			OTString strNodeData = xml->getNodeData();
			
			// Sometimes the XML reads up the data with a prepended newline.
			// This screws up my own objects which expect a consistent in/out
			// So I'm checking here for that prepended newline, and removing it.
			char cNewline;
			if (strNodeData.At(0, cNewline))
			{
				OTASCIIArmor ascNodeData;
				
				if ('\n' == cNewline)
				{
					ascNodeData.Set(strNodeData.Get() + 1);
					ascNodeData.GetString(m_strSignedFilePayload, true); // linebreaks = true
				}
				else
				{
					ascNodeData.Set(strNodeData.Get());
					ascNodeData.GetString(m_strSignedFilePayload, true); // linebreaks = true
				}
			}
		}
		else {
			fprintf(stderr, "Error in OTSignedFile::ProcessXMLNode: filePayload field without value.\n");
			return (-1); // error condition
		}
		
		return 1;
	}
	
	return nReturnVal;	
}
Ejemplo n.º 11
0
bool MainFile::CreateMainFile(const std::string& strContract,
                              const std::string& strNotaryID,
                              const std::string& strCert,
                              const std::string& strNymID,
                              const std::string& strCachedKey)
{
    if (!OTDB::StorePlainString(strContract, "contracts", strNotaryID)) {
        Log::Error("Failed trying to store the server contract.\n");
        return false;
    }

    if (!strCert.empty() &&
        !OTDB::StorePlainString(strCert, "certs", strNymID)) {
        Log::Error(
            "Failed trying to store the server Nym's public/private cert.\n");
        return false;
    }

    const char* szBlankFile = // todo hardcoding.
        "<notaryServer version=\"2.0\"\n"
        " notaryID=\"%s\"\n"
        " serverNymID=\"%s\"\n"
        " transactionNum=\"%ld\" >\n"
        "\n"
        "<cachedKey>\n"
        "%s</cachedKey>\n"
        "\n"
        "<accountList type=\"voucher\" count=\"0\" >\n"
        "\n"
        "</accountList>\n"
        "\n"
        "</notaryServer>\n\n";

    int64_t lTransNum = 5; // a starting point, for the new server.

    String strNotaryFile;
    strNotaryFile.Format(szBlankFile, strNotaryID.c_str(), strNymID.c_str(),
                         lTransNum, strCachedKey.c_str());

    std::string str_Notary(strNotaryFile.Get());

    if (!OTDB::StorePlainString(str_Notary, ".",
                                "notaryServer.xml")) // todo hardcoding.
    {
        Log::Error("Failed trying to store the new notaryServer.xml file.\n");
        return false;
    }
    OTASCIIArmor ascCachedKey;
    ascCachedKey.Set(strCachedKey.c_str());
    OTCachedKey::It()->SetCachedKey(ascCachedKey);

    if (!OTCachedKey::It()->HasHashCheck()) {
        OTPassword tempPassword;
        tempPassword.zeroMemory();
        std::shared_ptr<OTCachedKey> sharedPtr(OTCachedKey::It());
        sharedPtr->GetMasterPassword(
            sharedPtr, tempPassword,
            "We do not have a check hash yet for this password, "
            "please enter your password",
            true);
        if (!SaveMainFile()) {
            OT_FAIL;
        }
    }
    // At this point, the contract is saved, the cert is saved, and the
    // notaryServer.xml file
    // is saved. All we have left is the Nymfile, which we'll create.

    const String strServerNymID(strNymID.c_str());

    server_->m_nymServer.SetIdentifier(strServerNymID);

    if (!server_->m_nymServer.LoadCredentials(true)) {
        Log::vOutput(0, "%s: Error loading server credentials, or "
                        "certificate and private key.\n",
                     __FUNCTION__);
    }
    else if (!server_->m_nymServer.VerifyPseudonym()) {
        Log::vOutput(0, "%s: Error verifying server nym. Are you sure you "
                        "have the right ID?\n",
                     __FUNCTION__);
    }
    else if (!server_->m_nymServer.SaveSignedNymfile(server_->m_nymServer)) {
        Log::vOutput(0, "%s: Error saving new nymfile for server nym.\n",
                     __FUNCTION__);
    }
    else {
        Log::vOutput(0, "%s: OKAY, we have apparently created the new "
                        "server.\n"
                        "Let's try to load up your new server contract...\n",
                     __FUNCTION__);
        return true;
    }

    return false;
}
Ejemplo n.º 12
0
// LoadContract will call this function at the right time.
// return -1 if error, 0 if nothing, and 1 if the node was processed.
int OTLedger::ProcessXMLNode(irr::io::IrrXMLReader*& xml)
{	
	OTString strKeyName;
	OTString strKeyValue;
	
	OTString strTransaction;
	OTASCIIArmor ascTransaction;
	
	if (!strcmp("accountLedger", xml->getNodeName()))
	{	
		OTString strType, strLedgerAcctID, strLedgerAcctServerID, strUserID;
		
		strType = xml->getAttributeValue("type");
		
		if (strType.Compare("message"))
			m_Type = OTLedger::message;
		else if (strType.Compare("inbox"))
			m_Type = OTLedger::inbox;
		else if (strType.Compare("outbox"))
			m_Type = OTLedger::outbox;
		else if (strType.Compare("nymbox"))
			m_Type = OTLedger::nymbox;
		else
			m_Type = OTLedger::error_state;
	
		m_strVersion			= xml->getAttributeValue("version");	
		strLedgerAcctID			= xml->getAttributeValue("accountID"); 
		strLedgerAcctServerID	= xml->getAttributeValue("serverID");
		strUserID				= xml->getAttributeValue("userID");
		
		OTIdentifier ACCOUNT_ID(strLedgerAcctID), SERVER_ID(strLedgerAcctServerID), USER_ID(strUserID);
		
		SetPurportedAccountID(ACCOUNT_ID);
		SetPurportedServerID(SERVER_ID);
		SetUserID(USER_ID);
		
		OTLog::vOutput(2, "Loaded account ledger of type \"%s\", version: %s\n",
//				"accountID:\n%s\n userID:\n%s\n serverID:\n%s\n----------\n", 
				strType.Get(),
				m_strVersion.Get()
//				strLedgerAcctID.Get(), strUserID.Get(), strLedgerAcctServerID.Get()
				);
			
		// Since we just loaded this stuff, let's verify it.
		// We may have to remove this verification here and do it outside this call.
		// But for now...
		if (VerifyContractID())
			return 1;
		else {
			return -1;
		}

	}
	else if (!strcmp("transaction", xml->getNodeName()))
	{
		// go to the next node and read the text.
		xml->read();
		
		if (EXN_TEXT == xml->getNodeType())
		{
			// the ledger contains a series of transactions.
			// Each transaction is initially stored as an OTASCIIArmor string.
			ascTransaction.Set(xml->getNodeData());		// Put the ascii-armored node data into the ascii-armor object
			ascTransaction.GetString(strTransaction);	// Decode that into strTransaction, so we can load the transaction object from that string.
			OTTransaction * pTransaction = new OTTransaction(GetUserID(), GetPurportedAccountID(), GetPurportedServerID());
			
			// If we're able to successfully base64-decode the string and load it up as
			// a transaction, then let's add it to the ledger's list of transactions
			if (pTransaction && pTransaction->LoadContractFromString(strTransaction)
				&& pTransaction->VerifyContractID())
				// I responsible here to call pTransaction->VerifyContract() since
				// I am loading it here and adding it to the ledger. (So I do.)
			{
				m_mapTransactions[pTransaction->GetTransactionNum()] = pTransaction;
//				OTLog::Output(5, "Loaded transaction and adding to m_mapTransactions in OTLedger\n");
			}
			else {
				OTLog::Error("ERROR: loading transaction in OTLedger::ProcessXMLNode\n");
				if (pTransaction)
				{
					delete pTransaction;
					pTransaction = NULL;
				}
				return (-1);
			}

		}
		else {
			OTLog::Error("Error in OTLedger::ProcessXMLNode: transaction without value.\n");
			return (-1); // error condition
		}
		
		return 1;
	}
	
	return 0;
}
Ejemplo n.º 13
0
bool MTContactHandler::GetAccounts(mapIDName & theMap, QString filterByNym, QString filterByServer, QString filterByAsset)
{
    QMutexLocker locker(&m_Mutex);
    // -------------------------
    mapIDName parameters;
    // -------------------------
    if (!filterByNym.isEmpty())
        parameters.insert("nym_id", filterByNym);
    // -------------------------
    if (!filterByServer.isEmpty())
        parameters.insert("server_id", filterByServer);
    // -------------------------
    if (!filterByAsset.isEmpty())
        parameters.insert("asset_id", filterByAsset);
    // -------------------------
    // Construct the WHERE clause.
    //
    QString strParams;

    int nIteration = 0;
    while (!parameters.empty())
    {
        nIteration++; // 1 on first iteration.
        // ----------------------------------
        mapIDName::iterator the_beginning = parameters.begin();

        if (parameters.end() == the_beginning)
            break; // Done.
        // ----------------------------------
        QString strKey   = the_beginning.key();
        QString strValue = the_beginning.value();
        // ----------------------------------
        if (1 == nIteration) // first iteration
        {
            strParams = QString(" WHERE `%1`='%2'").arg(strKey).arg(strValue);
        }
        else // subsequent iterations.
        {
            strParams += QString(" AND `%1`='%2'").arg(strKey).arg(strValue);
        }
        // ----------------------------------
        parameters.remove(strKey);
    } // while
    // ---------------------------------
    // Construct the SELECT statement and append the WHERE clause.
    //
    QString str_select = QString("SELECT * FROM `nym_account`");

    if (!strParams.isEmpty())
        str_select += strParams;
    // ---------------------------------
    bool bFoundAccounts = false;
    int  nRows = DBHandler::getInstance()->querySize(str_select);

    for(int ii=0; ii < nRows; ii++)
    {
        QString account_id     = DBHandler::getInstance()->queryString(str_select, 0, ii);
        QString account_nym_id = DBHandler::getInstance()->queryString(str_select, 2, ii);
        QString display_name   = DBHandler::getInstance()->queryString(str_select, 4, ii);

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

            //Decode base64.
            OTASCIIArmor ascName;
            ascName.Set(display_name.toStdString().c_str());
            OTString strName(ascName);
            display_name = QString(strName.Get());
        }
        //---------------------------------------------------
        if (!account_id.isEmpty()) // Account ID is present.
        {
            if (display_name.isEmpty()) // Display name isn't.
            {
                // Look up the display name for the contact who owns the Nym who owns the Acct.
                //
                if (!account_nym_id.isEmpty())
                {
                    int nContactID = this->FindContactIDByNymID(account_nym_id);

                    if (nContactID > 0)
                    {
                        display_name = this->GetContactName(nContactID);
                    }
                }
            }
            // ----------------------
            if (display_name.isEmpty()) // Display name isn't.
            {
                display_name = account_id;
            }
            // ----------------------
            bFoundAccounts = true;

            theMap.insert(account_id, display_name);
        }
    } // for
    // ---------------------------------
    return bFoundAccounts;
}