Пример #1
0
TER Transactor::payFee()
{
	STAmount saPaid = mTxn.getTransactionFee();

	// Only check fee is sufficient when the ledger is open.
	if (isSetBit(mParams, tapOPEN_LEDGER) && saPaid < mFeeDue)
	{
		cLog(lsINFO) << "applyTransaction: insufficient fee";

		return telINSUF_FEE_P;
	}

	if (saPaid.isNegative() || !saPaid.isNative())
		return temBAD_FEE;

	if (!saPaid) return tesSUCCESS;

	// Deduct the fee, so it's not available during the transaction.
	// Will only write the account back, if the transaction succeeds.
	if (mSourceBalance < saPaid)
	{
		cLog(lsINFO)
			<< boost::str(boost::format("applyTransaction: Delay: insufficient balance: balance=%s paid=%s")
			% mSourceBalance.getText()
			% saPaid.getText());

		return terINSUF_FEE_B;
	}

	mSourceBalance -= saPaid;
	mTxnAccount->setFieldAmount(sfBalance, mSourceBalance);

	return tesSUCCESS;
}
Пример #2
0
TER Transactor::checkSeq()
{
	uint32 t_seq = mTxn.getSequence();
	uint32 a_seq = mTxnAccount->getFieldU32(sfSequence);

	cLog(lsTRACE) << "Aseq=" << a_seq << ", Tseq=" << t_seq;

	if (t_seq != a_seq)
	{
		if (a_seq < t_seq)
		{
			cLog(lsINFO) << "applyTransaction: future sequence number";

			return terPRE_SEQ;
		}
		else
		{
			uint256 txID = mTxn.getTransactionID();
			if (mEngine->getLedger()->hasTransaction(txID))
				return tefALREADY;
		}

		cLog(lsWARNING) << "applyTransaction: past sequence number";

		return tefPAST_SEQ;
	}else
	{
		mTxnAccount->setFieldU32(sfSequence, t_seq + 1);
	}

	return tesSUCCESS;
}
Пример #3
0
// check stuff before you bother to lock the ledger
TER Transactor::preCheck()
{

	mTxnAccountID	= mTxn.getSourceAccount().getAccountID();
	if (!mTxnAccountID)
	{
		cLog(lsWARNING) << "applyTransaction: bad source id";

		return temBAD_SRC_ACCOUNT;
	}

	// Extract signing key
	// Transactions contain a signing key.  This allows us to trivially verify a transaction has at least been properly signed
	// without going to disk.  Each transaction also notes a source account id.  This is used to verify that the signing key is
	// associated with the account.
	// XXX This could be a lot cleaner to prevent unnecessary copying.
	mSigningPubKey	= RippleAddress::createAccountPublic(mTxn.getSigningPubKey());

	// Consistency: really signed.
	if ( !isSetBit(mParams, tapNO_CHECK_SIGN) && !mTxn.checkSign(mSigningPubKey))
	{
		cLog(lsWARNING) << "applyTransaction: Invalid transaction: bad signature";

		return temINVALID;
	}

	return tesSUCCESS;
}
Пример #4
0
bool HashedObjectStore::store(HashedObjectType type, uint32 index,
	const std::vector<unsigned char>& data, const uint256& hash)
{ // return: false = already in cache, true = added to cache
	if (!theApp->getHashNodeDB())
	{
		cLog(lsTRACE) << "HOS: no db";
		return true;
	}
	if (mCache.touch(hash))
	{
		cLog(lsTRACE) << "HOS: " << hash << " store: incache";
		return false;
	}
	assert(hash == Serializer::getSHA512Half(data));

	HashedObject::pointer object = boost::make_shared<HashedObject>(type, index, data, hash);
	if (!mCache.canonicalize(hash, object))
	{
//		cLog(lsTRACE) << "Queuing write for " << hash;
		boost::mutex::scoped_lock sl(mWriteMutex);
		mWriteSet.push_back(object);
		if (!mWritePending)
		{
			mWritePending = true;
			theApp->getJobQueue().addJob(jtWRITE, boost::bind(&HashedObjectStore::bulkWrite, this));
		}
	}
//	else
//		cLog(lsTRACE) << "HOS: already had " << hash;
	mNegativeCache.del(hash);
	return true;
}
Пример #5
0
TER Transactor::checkSig()
{
	// Consistency: Check signature
	// Verify the transaction's signing public key is the key authorized for signing.
	if (mHasAuthKey && mSigningPubKey.getAccountID() == mTxnAccount->getFieldAccount(sfRegularKey).getAccountID())
	{
		// Authorized to continue.
		nothing();
	}
	else if (mSigningPubKey.getAccountID() == mTxnAccountID)
	{
		// Authorized to continue.
		nothing();
	}
	else if (mHasAuthKey)
	{
		cLog(lsINFO) << "applyTransaction: Delay: Not authorized to use account.";

		return tefBAD_AUTH;
	}
	else
	{
		cLog(lsINFO) << "applyTransaction: Invalid: Not authorized to use account.";

		return temBAD_AUTH_MASTER;
	}

	return tesSUCCESS;
}
Пример #6
0
std::vector<unsigned char> RippleAddress::accountPrivateDecrypt(const RippleAddress& naPublicFrom, const std::vector<unsigned char>& vucCipherText) const
{
	CKey						ckPrivate;
	CKey						ckPublic;
	std::vector<unsigned char>	vucPlainText;

	if (!ckPublic.SetPubKey(naPublicFrom.getAccountPublic()))
	{
		// Bad public key.
		cLog(lsWARNING) << "accountPrivateDecrypt: Bad public key.";
	}
	else if (!ckPrivate.SetPrivateKeyU(getAccountPrivate()))
	{
		// Bad private key.
		cLog(lsWARNING) << "accountPrivateDecrypt: Bad private key.";
	}
	else
	{
		try {
			vucPlainText = ckPrivate.decryptECIES(ckPublic, vucCipherText);
		}
		catch (...)
		{
			nothing();
		}
	}

	return vucPlainText;
}
Пример #7
0
STPathSet* STPathSet::construct(SerializerIterator& s, SField::ref name)
{
	std::vector<STPath> paths;
	std::vector<STPathElement> path;

	do
	{
		int	iType	= s.get8();

		if (iType == STPathElement::typeEnd || iType == STPathElement::typeBoundary)
		{
			if (path.empty())
			{
				cLog(lsINFO) << "STPathSet: Empty path.";

				throw std::runtime_error("empty path");
			}

			paths.push_back(path);
			path.clear();

			if (iType == STPathElement::typeEnd)
			{
				return new STPathSet(name, paths);
			}
		}
		else if (iType & ~STPathElement::typeValidBits)
		{
			cLog(lsINFO) << "STPathSet: Bad path element: " << iType;

			throw std::runtime_error("bad path element");
		}
		else
		{
			const bool	bAccount	= !!(iType & STPathElement::typeAccount);
			const bool	bCurrency	= !!(iType & STPathElement::typeCurrency);
			const bool	bIssuer		= !!(iType & STPathElement::typeIssuer);

			uint160	uAccountID;
			uint160	uCurrency;
			uint160	uIssuerID;

			if (bAccount)
				uAccountID	= s.get160();

			if (bCurrency)
				uCurrency	= s.get160();

			if (bIssuer)
				uIssuerID	= s.get160();

			path.push_back(STPathElement(uAccountID, uCurrency, uIssuerID, bCurrency));
		}
	} while(1);
}
Пример #8
0
int main() {
  static const int SERVER_PORT = 7892;
  char in_buffer[1024];
  struct sockaddr_in serverAddr;
  struct sockaddr_storage serverStorage;
  socklen_t addr_size;
  serverLogger = createLogger(__FILE__, LOG_LEVEL);
  // set up socket, call to socket returns a file descriptor (fd)
  welcomeSocket = socket(AF_INET, SOCK_STREAM, 0);
  signal(SIGINT, intHandler);

  createSockaddr_in(&serverAddr, SERVER_PORT, "127.0.0.1");
  int bindStatus = bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));
  if (bindStatus != 0) {
    printf("bind error: %s\n", strerror(errno));
    cLog("bind error");
    exit(0);
  }

  do {
    memset(in_buffer, 0, 1024);
    // max 5 connections... however only prints "Error!" if hits the limit
    int listenWelcomeSocket = listen(welcomeSocket, 5);
    //if(listen(welcomeSocket, 5) == 0) {
    if(listenWelcomeSocket == 0) {
      cLog("Server Listening");
      printf("Server Listening\n");
      printf("welcomeSocket output: %d\n", listenWelcomeSocket);
     } else {
       printf("Error!\n");
     }

    // accept connection 
    addr_size = sizeof(serverStorage);
    int newSocket = accept(welcomeSocket, (struct sockaddr *) &serverAddr, &addr_size);
    printf("Accepted new socket: %d\n", newSocket);
    // receive data
    int recvBytes = recv(newSocket, in_buffer, 1024, 0);
    printf("Received: '%s' from client\n", in_buffer);
    printf("Received: %d bytes from client\n", recvBytes);

    handleRequest(newSocket, in_buffer, "Server");
    //int shutdownStatus = shutdown(newSocket, 0);
    int shutdownStatus = close(newSocket);
    printf("(server.c) Closed socket: %d, with status: %d\n", newSocket, shutdownStatus);
    usleep(50000);

  } while(true);
  int shutdownStatus = close(welcomeSocket);
  printf("(server.c) Closed socket: %d, with status: %d\n", welcomeSocket, shutdownStatus);

  return 0;
}
Пример #9
0
void
CalamaresApplication::initSettings()
{
    QFileInfo settingsFile;
    if ( CalamaresUtils::isAppDataDirOverridden() )
    {
        settingsFile = QFileInfo( CalamaresUtils::appDataDir().absoluteFilePath( "settings.conf" ) );
        if ( !settingsFile.exists() || !settingsFile.isReadable() )
        {
            cLog() << "FATAL ERROR: explicitly configured application data directory"
                   << CalamaresUtils::appDataDir().absolutePath()
                   << "does not contain a valid settings.conf file."
                   << "\nCowardly refusing to continue startup without settings.";
            ::exit( EXIT_FAILURE );
        }
    }
    else
    {
        QStringList settingsFileCandidatesByPriority;
        if ( isDebug() )
        {
            settingsFileCandidatesByPriority.append(
                QDir::currentPath() +
                QDir::separator() +
                "settings.conf" );
        }
        settingsFileCandidatesByPriority.append( CMAKE_INSTALL_FULL_SYSCONFDIR "/calamares/settings.conf" );
        settingsFileCandidatesByPriority.append( CalamaresUtils::appDataDir()
                                                    .absoluteFilePath( "settings.conf" ) );

        foreach ( const QString& path, settingsFileCandidatesByPriority )
        {
            QFileInfo pathFi( path );
            if ( pathFi.exists() && pathFi.isReadable() )
            {
                settingsFile = pathFi;
                break;
            }
        }

        if ( !settingsFile.exists() || !settingsFile.isReadable() )
        {
            cLog() << "FATAL ERROR: none of the expected configuration file paths ("
                   << settingsFileCandidatesByPriority.join( ", " )
                   << ") contain a valid settings.conf file."
                   << "\nCowardly refusing to continue startup without settings.";
            ::exit( EXIT_FAILURE );
        }
    }
Пример #10
0
void LedgerMaster::pushLedger(Ledger::ref newLedger)
{
	// Caller should already have properly assembled this ledger into "ready-to-close" form --
	// all candidate transactions must already be applied
	cLog(lsINFO) << "PushLedger: " << newLedger->getHash();
	boost::recursive_mutex::scoped_lock ml(mLock);
	if (!!mFinalizedLedger)
	{
		mFinalizedLedger->setClosed();
		cLog(lsTRACE) << "Finalizes: " << mFinalizedLedger->getHash();
	}
	mFinalizedLedger = mCurrentLedger;
	mCurrentLedger = newLedger;
	mEngine.setLedger(newLedger);
}
Пример #11
0
void WSDoor::startListening()
{
	// Generate a single SSL context for use by all connections.
    boost::shared_ptr<boost::asio::ssl::context>	mCtx;
	mCtx	= boost::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::sslv23);

	mCtx->set_options(
		boost::asio::ssl::context::default_workarounds
		| boost::asio::ssl::context::no_sslv2
		| boost::asio::ssl::context::single_dh_use);

	SSL_CTX_set_tmp_dh_callback(mCtx->native_handle(), handleTmpDh);

	// Construct a single handler for all requests.
	websocketpp::server_autotls::handler::ptr	handler(new WSServerHandler<websocketpp::server_autotls>(mCtx, mPublic));

	// Construct a websocket server.
	mSEndpoint		= new websocketpp::server_autotls(handler);

	// mEndpoint->alog().unset_level(websocketpp::log::alevel::ALL);
	// mEndpoint->elog().unset_level(websocketpp::log::elevel::ALL);

	// Call the main-event-loop of the websocket server.
	try
	{
		mSEndpoint->listen(
			boost::asio::ip::tcp::endpoint(
			boost::asio::ip::address().from_string(mIp), mPort));
	}
	catch (websocketpp::exception& e)
	{
		cLog(lsWARNING) << "websocketpp exception: " << e.what();
		while (1) // temporary workaround for websocketpp throwing exceptions on access/close races
		{ // https://github.com/zaphoyd/websocketpp/issues/98
			try
			{
				mSEndpoint->get_io_service().run();
				break;
			}
			catch (websocketpp::exception& e)
			{
				cLog(lsWARNING) << "websocketpp exception: " << e.what();
			}
		}
	}

	delete mSEndpoint;
}
Пример #12
0
Ledger::pointer LedgerMaster::closeLedger(bool recover)
{
	boost::recursive_mutex::scoped_lock sl(mLock);
	Ledger::pointer closingLedger = mCurrentLedger;

	if (recover)
	{
		int recovers = 0;
		for (CanonicalTXSet::iterator it = mHeldTransactions.begin(), end = mHeldTransactions.end(); it != end; ++it)
		{
			try
			{
				bool didApply;
				mEngine.applyTransaction(*it->second, tapOPEN_LEDGER, didApply);
				if (didApply)
					++recovers;
			}
			catch (...)
			{
				cLog(lsWARNING) << "Held transaction throws";
			}
		}
		tLog(recovers != 0, lsINFO) << "Recovered " << recovers << " held transactions";
		mHeldTransactions.reset(closingLedger->getHash());
	}

	mCurrentLedger = boost::make_shared<Ledger>(boost::ref(*closingLedger), true);
	mEngine.setLedger(mCurrentLedger);

	return closingLedger;
}
Пример #13
0
void intHandler(int handle_this) {
  keepRunning = 0;
  close(welcomeSocket);
  // TODO how to take in string(s) for formating? '...' arg? 
  cLog("closing socket");
  printf("\nclosing socket: %d\n", welcomeSocket);
  exit(0);
}
Пример #14
0
std::auto_ptr<SerializedType> STObject::makeDefaultObject(SerializedTypeID id, SField::ref name)
{
	assert((id == STI_NOTPRESENT) || (id == name.fieldType));

	switch(id)
	{
		case STI_NOTPRESENT:
			return std::auto_ptr<SerializedType>(new SerializedType(name));

		case STI_UINT8:
			return std::auto_ptr<SerializedType>(new STUInt8(name));

		case STI_UINT16:
			return std::auto_ptr<SerializedType>(new STUInt16(name));

		case STI_UINT32:
			return std::auto_ptr<SerializedType>(new STUInt32(name));

		case STI_UINT64:
			return std::auto_ptr<SerializedType>(new STUInt64(name));

		case STI_AMOUNT:
			return std::auto_ptr<SerializedType>(new STAmount(name));

		case STI_HASH128:
			return std::auto_ptr<SerializedType>(new STHash128(name));

		case STI_HASH160:
			return std::auto_ptr<SerializedType>(new STHash160(name));

		case STI_HASH256:
			return std::auto_ptr<SerializedType>(new STHash256(name));

		case STI_VECTOR256:
			return std::auto_ptr<SerializedType>(new STVector256(name));

		case STI_VL:
			return std::auto_ptr<SerializedType>(new STVariableLength(name));

		case STI_ACCOUNT:
			return std::auto_ptr<SerializedType>(new STAccount(name));

		case STI_PATHSET:
			return std::auto_ptr<SerializedType>(new STPathSet(name));

		case STI_OBJECT:
			return std::auto_ptr<SerializedType>(new STObject(name));

		case STI_ARRAY:
			return std::auto_ptr<SerializedType>(new STArray(name));

		default:
			cLog(lsFATAL) << "Object type: " << lexical_cast_i(id);
			assert(false);
			throw std::runtime_error("Unknown object type");
	}
}
Пример #15
0
bool LedgerMaster::acquireMissingLedger(Ledger::ref origLedger, const uint256& ledgerHash, uint32 ledgerSeq)
{ // return: false = already gave up recently
	if (mTooFast)
		return true;

	Ledger::pointer ledger = mLedgerHistory.getLedgerBySeq(ledgerSeq);
	if (ledger && (Ledger::getHashByIndex(ledgerSeq) == ledgerHash))
	{
		cLog(lsTRACE) << "Ledger hash found in database";
		mTooFast = true;
		theApp->getJobQueue().addJob(jtPUBOLDLEDGER, boost::bind(&LedgerMaster::asyncAccept, this, ledger));
		return true;
	}

	if (theApp->getMasterLedgerAcquire().isFailure(ledgerHash))
		return false;

	mMissingLedger = theApp->getMasterLedgerAcquire().findCreate(ledgerHash);
	if (mMissingLedger->isComplete())
	{
		Ledger::pointer lgr = mMissingLedger->getLedger();
		if (lgr && (lgr->getLedgerSeq() == ledgerSeq))
			missingAcquireComplete(mMissingLedger);
		mMissingLedger.reset();
		return true;
	}
	else if (mMissingLedger->isDone())
	{
		mMissingLedger.reset();
		return false;
	}
	mMissingSeq = ledgerSeq;
	if (mMissingLedger->setAccept())
	{
		if (!mMissingLedger->addOnComplete(boost::bind(&LedgerMaster::missingAcquireComplete, this, _1)))
			theApp->getIOService().post(boost::bind(&LedgerMaster::missingAcquireComplete, this, mMissingLedger));
	}

	int fetch = theConfig.getSize(siLedgerFetch);
	if (theApp->getMasterLedgerAcquire().getFetchCount() < fetch)
	{
		int count = 0;
		typedef std::pair<uint32, uint256> u_pair;

		std::vector<u_pair> vec = origLedger->getLedgerHashes();
		BOOST_REVERSE_FOREACH(const u_pair& it, vec)
		{
			if ((count < fetch) && (it.first < ledgerSeq) &&
				!mCompleteLedgers.hasValue(it.first) && !theApp->getMasterLedgerAcquire().find(it.second))
			{
				++count;
				theApp->getMasterLedgerAcquire().findCreate(it.second);
			}
		}
	}
Пример #16
0
Json::Value STUInt8::getJson(int) const
{
	if (getFName() == sfTransactionResult)
	{
		std::string token, human;
		if (transResultInfo(static_cast<TER>(value), token, human))
			return token;
		else
			cLog(lsWARNING) << "Unknown result code in metadata: " << value;
	}
	return value;
}
Пример #17
0
void
ViewManager::onInstallationFailed( const QString& message, const QString& details )
{
    cLog() << "Installation failed:";
    cLog() << "- message:" << message;
    cLog() << "- details:" << details;

    QMessageBox msgBox;
    msgBox.setIcon( QMessageBox::Critical );
    msgBox.setWindowTitle( tr("Error") );
    msgBox.setText( "<strong>" + tr( "Installation Failed" ) + "</strong>" );
    msgBox.setStandardButtons( QMessageBox::Close );

    QString text = "<p>" + message + "</p>";
    if ( !details.isEmpty() )
    {
        text += "<p>" + details + "</p>";
    }
    msgBox.setInformativeText( text );

    msgBox.exec();
    QApplication::quit();
}
Пример #18
0
WSDoor* WSDoor::createWSDoor(const std::string& strIp, const int iPort, bool bPublic)
{
	WSDoor*	wdpResult	= new WSDoor(strIp, iPort, bPublic);

	cLog(lsINFO) <<
		boost::str(boost::format("Websocket: %s: Listening: %s %d ")
			% (bPublic ? "Public" : "Private")
			% strIp
			% iPort);

	wdpResult->mThread	= new boost::thread(boost::bind(&WSDoor::startListening, wdpResult));

	return wdpResult;
}
Пример #19
0
void
Module::loadConfigurationFile( const QString& configFileName ) //throws YAML::Exception
{
    QStringList configFilesByPriority;

    if ( CalamaresUtils::isAppDataDirOverridden() )
    {
        configFilesByPriority.append(
            CalamaresUtils::appDataDir().absoluteFilePath(
                QString( "modules/%1" ).arg( configFileName ) ) );
    }
    else
    {
        if ( Settings::instance()->debugMode() )
        {
            configFilesByPriority.append(
                QDir( QDir::currentPath() ).absoluteFilePath(
                    QString( "src/modules/%1/%2" ).arg( m_name )
                                                  .arg( configFileName ) ) );
        }

        configFilesByPriority.append(
            QString( "/etc/calamares/modules/%1" ).arg( configFileName ) );
        configFilesByPriority.append(
            CalamaresUtils::appDataDir().absoluteFilePath(
                QString( "modules/%2" ).arg( configFileName ) ) );
    }

    foreach ( const QString& path, configFilesByPriority )
    {
        QFile configFile( path );
        if ( configFile.exists() && configFile.open( QFile::ReadOnly | QFile::Text ) )
        {
            QByteArray ba = configFile.readAll();

            YAML::Node doc = YAML::Load( ba.constData() );
            if ( !doc.IsMap() )
            {
                cLog() << Q_FUNC_INFO << "bad module configuration format"
                         << path;
                return;
            }

            m_configurationMap = CalamaresUtils::yamlMapToVariant( doc ).toMap();
            return;
        }
        else
            continue;
    }
Пример #20
0
uint32 RangeSet::prevMissing(uint32 v) const
{ // largest number not in the set that is less than the given number
	cLog(lsTRACE) << "prevMissing(" << v << ") " << toString();
	for (const_reverse_iterator it = rbegin(); it != rend(); ++it)
	{
		if ((upper(it) + 1) < v)
			return upper(it) + 1;
		if (lower(it) == 0)
			return RangeSetAbsent;
		if ((lower(it) - 1) < v)
			return lower(it) - 1;
	}
	if (v > 0)
		return v - 1;
	return RangeSetAbsent;
}
Пример #21
0
bool RippleAddress::accountPrivateVerify(const uint256& uHash, const std::vector<unsigned char>& vucSig) const
{
	CKey		ckPrivate;
	bool		bVerified;

	if (!ckPrivate.SetPrivateKeyU(getAccountPrivate()))
	{
		// Bad private key.
		cLog(lsWARNING) << "accountPrivateVerify: Bad private key.";
		bVerified	= false;
	}
	else
	{
		bVerified	= ckPrivate.Verify(uHash, vucSig);
	}

	return bVerified;
}
Пример #22
0
bool RippleAddress::accountPrivateSign(const uint256& uHash, std::vector<unsigned char>& vucSig) const
{
	CKey		ckPrivate;
	bool		bResult;

	if (!ckPrivate.SetPrivateKeyU(getAccountPrivate()))
	{
		// Bad private key.
		cLog(lsWARNING) << "accountPrivateSign: Bad private key.";
		bResult	= false;
	}
	else
	{
		bResult	= ckPrivate.Sign(uHash, vucSig);
		tLog(!bResult, lsWARNING) << "accountPrivateSign: Signing failed.";
	}

	return bResult;
}
Пример #23
0
QModelIndex
PartitionModel::parent( const QModelIndex& child ) const
{
    if ( !child.isValid() )
        return QModelIndex();
    Partition* partition = partitionForIndex( child );
    PartitionNode* parentNode = partition->parent();
    if ( parentNode == m_device->partitionTable() )
        return QModelIndex();

    int row = 0;
    for ( auto p : m_device->partitionTable()->children() )
    {
        if ( parentNode == p )
            return createIndex( row, 0, parentNode );
        ++row;
    }
    cLog() << "No parent found!";
    return QModelIndex();
}
Пример #24
0
TER Transactor::apply()
{
	TER		terResult	= tesSUCCESS;
	terResult=preCheck();
	if(terResult != tesSUCCESS) return(terResult);

	calculateFee();

	boost::recursive_mutex::scoped_lock sl(mEngine->getLedger()->mLock);

	mTxnAccount	= mEngine->entryCache(ltACCOUNT_ROOT, Ledger::getAccountRootIndex(mTxnAccountID));

	// Find source account
	// If are only forwarding, due to resource limitations, we might verifying only some transactions, this would be probabilistic.

	if (!mTxnAccount)
	{
		cLog(lsTRACE) << boost::str(boost::format("applyTransaction: Delay transaction: source account does not exist: %s") %
			mTxn.getSourceAccount().humanAccountID());

		return terNO_ACCOUNT;
	}
	else
	{
		mSourceBalance	= mTxnAccount->getFieldAmount(sfBalance);
		mHasAuthKey	= mTxnAccount->isFieldPresent(sfRegularKey);
	}

	terResult = checkSeq();
	if (terResult != tesSUCCESS) return(terResult);

	terResult = payFee();
	if (terResult != tesSUCCESS) return(terResult);

	terResult = checkSig();
	if (terResult != tesSUCCESS) return(terResult);

	mEngine->entryModify(mTxnAccount);

	return doApply();
}
Пример #25
0
void LedgerMaster::pushLedger(Ledger::ref newLCL, Ledger::ref newOL, bool fromConsensus)
{
	assert(newLCL->isClosed() && newLCL->isAccepted());
	assert(!newOL->isClosed() && !newOL->isAccepted());

	if (newLCL->isAccepted())
	{
		assert(newLCL->isClosed());
		assert(newLCL->isImmutable());
		mLedgerHistory.addAcceptedLedger(newLCL, fromConsensus);
		cLog(lsINFO) << "StashAccepted: " << newLCL->getHash();
	}

	{
		boost::recursive_mutex::scoped_lock ml(mLock);
		mFinalizedLedger = newLCL;
		mCurrentLedger = newOL;
		mEngine.setLedger(newOL);
	}
	checkAccept(newLCL->getHash(), newLCL->getLedgerSeq());
}
Пример #26
0
Json::Value rpcError(int iError, Json::Value jvResult)
{
	static struct {
		int			iError;
		const char*	pToken;
		const char*	pMessage;
	} errorInfoA[] = {
		{ rpcACT_EXISTS,			"actExists",		"Account already exists."								},
		{ rpcACT_MALFORMED,			"actMalformed",		"Account malformed."									},
		{ rpcACT_NOT_FOUND,			"actNotFound",		"Account not found."									},
		{ rpcBAD_BLOB,				"badBlob",			"Blob must be a non-empty hex string."					},
		{ rpcBAD_SEED,				"badSeed",			"Disallowed seed."										},
		{ rpcBAD_SYNTAX,			"badSyntax",		"Syntax error."											},
		{ rpcCOMMAND_MISSING,		"commandMissing",	"Missing command entry."								},
		{ rpcDST_ACT_MALFORMED,		"dstActMalformed",	"Destination account is malformed."						},
		{ rpcDST_ACT_MISSING,		"dstActMissing",	"Destination account does not exists."					},
		{ rpcDST_AMT_MALFORMED,		"dstAmtMalformed",	"Destination amount/currency/issuer is malformed."		},
		{ rpcFORBIDDEN,				"forbidden",		"Bad credentials."										},
		{ rpcFAIL_GEN_DECRPYT,		"failGenDecrypt",	"Failed to decrypt generator."							},
		{ rpcGETS_ACT_MALFORMED,	"getsActMalformed",	"Gets account malformed."								},
		{ rpcGETS_AMT_MALFORMED,	"getsAmtMalformed",	"Gets amount malformed."								},
		{ rpcHOST_IP_MALFORMED,		"hostIpMalformed",	"Host IP is malformed."									},
		{ rpcINSUF_FUNDS,			"insufFunds",		"Insufficient funds."									},
		{ rpcINTERNAL,				"internal",			"Internal error."										},
		{ rpcINVALID_PARAMS,		"invalidParams",	"Invalid parameters."									},
		{ rpcJSON_RPC,				"json_rpc",			"JSON-RPC transport error."								},
		{ rpcLGR_IDXS_INVALID,		"lgrIdxsInvalid",	"Ledger indexes invalid."								},
		{ rpcLGR_IDX_MALFORMED,		"lgrIdxMalformed",	"Ledger index malformed."								},
		{ rpcLGR_NOT_FOUND,			"lgrNotFound",		"Ledger not found."										},
		{ rpcNICKNAME_MALFORMED,	"nicknameMalformed","Nickname is malformed."								},
		{ rpcNICKNAME_MISSING,		"nicknameMissing",	"Nickname does not exist."								},
		{ rpcNICKNAME_PERM,			"nicknamePerm",		"Account does not control nickname."					},
		{ rpcNOT_IMPL,				"notImpl",			"Not implemented."										},
		{ rpcNO_ACCOUNT,			"noAccount",		"No such account."										},
		{ rpcNO_CLOSED,				"noClosed",			"Closed ledger is unavailable."							},
		{ rpcNO_CURRENT,			"noCurrent",		"Current ledger is unavailable."						},
		{ rpcNO_EVENTS,				"noEvents",			"Current transport does not support events."			},
		{ rpcNO_GEN_DECRPYT,		"noGenDectypt",		"Password failed to decrypt master public generator."	},
		{ rpcNO_NETWORK,			"noNetwork",		"Network not available."								},
		{ rpcNO_PATH,				"noPath",			"Unable to find a ripple path."							},
		{ rpcNO_PERMISSION,			"noPermission",		"You don't have permission for this command."			},
		{ rpcNOT_STANDALONE,		"notStandAlone",	"Operation valid in debug mode only."					},
		{ rpcNOT_SUPPORTED,			"notSupported",		"Operation not supported."								},
		{ rpcPASSWD_CHANGED,		"passwdChanged",	"Wrong key, password changed."							},
		{ rpcPAYS_ACT_MALFORMED,	"paysActMalformed",	"Pays account malformed."								},
		{ rpcPAYS_AMT_MALFORMED,	"paysAmtMalformed",	"Pays amount malformed."								},
		{ rpcPORT_MALFORMED,		"portMalformed",	"Port is malformed."									},
		{ rpcPUBLIC_MALFORMED,		"publicMalformed",	"Public key is malformed."								},
		{ rpcQUALITY_MALFORMED,		"qualityMalformed",	"Quality malformed."									},
		{ rpcSRC_ACT_MALFORMED,		"srcActMalformed",	"Source account is malformed."							},
		{ rpcSRC_ACT_MISSING,		"srcActMissing",	"Source account not provided."							},
		{ rpcSRC_ACT_NOT_FOUND,		"srcActNotFound",	"Source amount not found."								},
		{ rpcSRC_AMT_MALFORMED,		"srcAmtMalformed",	"Source amount/currency/issuer is malformed."			},
		{ rpcSRC_CUR_MALFORMED,		"srcCurMalformed",	"Source currency is malformed."							},
		{ rpcSRC_ISR_MALFORMED,		"srcIsrMalformed",	"Source issuer is malformed."							},
		{ rpcSRC_UNCLAIMED,			"srcUnclaimed",		"Source account is not claimed."						},
		{ rpcTXN_NOT_FOUND,			"txnNotFound",		"Transaction not found."								},
		{ rpcUNKNOWN_COMMAND,		"unknownCmd",		"Unknown method."										},
		{ rpcWRONG_SEED,			"wrongSeed",		"The regular key does not point as the master key."		},
	};

	int		i;

	for (i=NUMBER(errorInfoA); i-- && errorInfoA[i].iError != iError;)
		;

	jvResult["error"]			= i >= 0 ? errorInfoA[i].pToken : lexical_cast_i(iError);
	jvResult["error_message"]	= i >= 0 ? errorInfoA[i].pMessage : lexical_cast_i(iError);
	jvResult["error_code"]		= iError;

	if (i >= 0)
	{
		cLog(lsDEBUG) << "rpcError: "
			<< errorInfoA[i].pToken << ": " << errorInfoA[i].pMessage << std::endl;
	}

	return jvResult;
}
Пример #27
0
Module*
Module::fromDescriptor( const QVariantMap& moduleDescriptor,
                        const QString& instanceId,
                        const QString& configFileName,
                        const QString& moduleDirectory )
{
    Module* m = nullptr;

    QString typeString = moduleDescriptor.value( "type" ).toString();
    QString intfString = moduleDescriptor.value( "interface" ).toString();

    if ( typeString.isEmpty() ||
         intfString.isEmpty() )
    {
        cLog() << Q_FUNC_INFO << "bad module descriptor format"
               << instanceId;
        return nullptr;
    }
    if ( typeString == "view" && intfString == "qtplugin" )
    {
        m = new ViewModule();
    }
    else if ( typeString == "job" )
    {
        if ( intfString == "process" )
        {
            m = new ProcessJobModule();
        }
#ifdef WITH_PYTHON
        else if ( intfString == "python" )
        {
            m = new PythonJobModule();
        }
#endif
    }
    if ( !m )
    {
        cLog() << Q_FUNC_INFO << "bad module type or interface string"
               << instanceId << typeString << intfString;
        return nullptr;
    }

    QDir moduleDir( moduleDirectory );
    if ( moduleDir.exists() && moduleDir.isReadable() )
        m->m_directory = moduleDir.absolutePath();
    else
    {
        cLog() << Q_FUNC_INFO << "bad module directory"
               << instanceId;
        return nullptr;
    }

    m->m_instanceId = instanceId;

    m->initFrom( moduleDescriptor );
    try
    {
        m->loadConfigurationFile( configFileName );
    }
    catch ( YAML::Exception& e )
    {
        cDebug() << "WARNING: YAML parser error " << e.what();
        delete m;
        return nullptr;
    }
    return m;
}
Пример #28
0
void HashedObjectStore::bulkWrite()
{
	while (1)
	{
		std::vector< boost::shared_ptr<HashedObject> > set;
		set.reserve(128);

		{
			boost::mutex::scoped_lock sl(mWriteMutex);
			mWriteSet.swap(set);
			assert(mWriteSet.empty());
			++mWriteGeneration;
			mWriteCondition.notify_all();
			if (set.empty())
			{
				mWritePending = false;
				return;
			}
		}
//		cLog(lsTRACE) << "HOS: writing " << set.size();

#ifndef NO_SQLITE3_PREPARE

	{
		Database* db = theApp->getHashNodeDB()->getDB();
		ScopedLock sl(theApp->getHashNodeDB()->getDBLock());
		static SqliteStatement pSt(db->getSqliteDB(),
			"INSERT OR IGNORE INTO CommittedObjects "
				"(Hash,ObjType,LedgerIndex,Object) VALUES (?, ?, ?, ?);");

		db->executeSQL("BEGIN TRANSACTION;");

		BOOST_FOREACH(const boost::shared_ptr<HashedObject>& it, set)
		{
			const char* type;

			switch (it->getType())
			{
				case hotLEDGER:				type = "L"; break;
				case hotTRANSACTION:		type = "T"; break;
				case hotACCOUNT_NODE:		type = "A"; break;
				case hotTRANSACTION_NODE:	type = "N"; break;
				default:					type = "U";
			}

			pSt.reset();
			pSt.bind(1, it->getHash().GetHex());
			pSt.bind(2, type);
			pSt.bind(3, it->getIndex());
			pSt.bindStatic(4, it->getData());
			int ret = pSt.step();
			if (!pSt.isDone(ret))
			{
				cLog(lsFATAL) << "Error saving hashed object " << ret;
				assert(false);
			}
		}

		db->executeSQL("END TRANSACTION;");
	}

#else

		static boost::format
			fAdd("INSERT OR IGNORE INTO CommittedObjects "
				"(Hash,ObjType,LedgerIndex,Object) VALUES ('%s','%c','%u',%s);");

		Database* db = theApp->getHashNodeDB()->getDB();
		{
			ScopedLock sl(theApp->getHashNodeDB()->getDBLock());

			db->executeSQL("BEGIN TRANSACTION;");

			BOOST_FOREACH(const boost::shared_ptr<HashedObject>& it, set)
			{
				char type;

				switch (it->getType())
				{
					case hotLEDGER:				type = 'L'; break;
					case hotTRANSACTION:		type = 'T'; break;
					case hotACCOUNT_NODE:		type = 'A'; break;
					case hotTRANSACTION_NODE:	type = 'N'; break;
					default:					type = 'U';
				}
				db->executeSQL(boost::str(fAdd % it->getHash().GetHex() % type % it->getIndex() % sqlEscape(it->getData())));
			}

			db->executeSQL("END TRANSACTION;");
		}
#endif

	}
Пример #29
0
int main() {
  static const int SERVER_PORT = 7892;
  int clientSocket;
  int num_to_decrement;
  char in_buffer[1024], temp_in_buffer[1024], out_buffer[1024];
  struct sockaddr_in serverAddr;
  socklen_t addr_size;
  char *message_format = "%s:%d";
  char message[1024];
  char* key = "decrement";
  char* value = "50";
  clientLogger = createLogger(__FILE__, LOG_LEVEL);
  //char* log_msg = malloc(sizeof(char) * 128);

  do {
    //memset(in_buffer, '\0', 1024);
    //memset(temp_in_buffer, '\0', 1024);
    // set up data to send
    num_to_decrement = atoi(value);
    sprintf(message, message_format, key, num_to_decrement);

    // set up socket
    clientSocket = socket(AF_INET, SOCK_STREAM, 0);

    createSockaddr_in(&serverAddr, SERVER_PORT, "127.0.0.1");
    printf("%s\n", "before connecting to socket");
    cLog("before connecting to socket");

    // Connect to socket
    addr_size = sizeof(serverAddr);
    if(connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size) < 0) {
      error("Error connecting\n");
    }
    cLog("after connecting to socket");
    printf("%s\n", "after connecting to socket");

    strcpy(out_buffer, message);
    int sentBytes = send(clientSocket, out_buffer, sizeof(out_buffer), 0);
    printf("sent %d bytes from %s\n", sentBytes, "client");
    //sprintf(log_msg, "sent %d bytes from %s\n", sentBytes, "client");
    //cLog(log_msg);
    if (sentBytes == -1) {
      error("");
      printf("error: %s\n", strerror(errno));
      cLog("failed to send");
    } else {
      cLog("succeeded in sending");
    }

    printf("(client) just sent: %s\n", out_buffer);
    //sprintf(message_format, key, num_to_decrement);
    //sprintf(log_msg, message_format, key, num_to_decrement);
    //cLog(log_msg);
    //printf("\n");

    // read from host
    recv(clientSocket, in_buffer, 1024, 0);
    if (!strcmp(in_buffer, "decrement:80")) {
      printf("special");
    }

    strncpy(temp_in_buffer, in_buffer, 1024);

    cLog("received data from sever");
    printf("Data received from server: '%s'\n", in_buffer);
    //sprintf(log_msg, "Data received from server: '%s'\n", in_buffer);
    //cLog(log_msg);
    printf("temp data: '%s'\n", temp_in_buffer);
    //sprintf(log_msg, "temp data: '%s'\n", temp_in_buffer);
    //cLog(log_msg);

    handleRequest(clientSocket, in_buffer, "client");
    setKeyValue(&key, &value, temp_in_buffer);

    //printf("(client.c): key: %s, value: %s\n", key, value);
    int shutdownStatus = close(clientSocket);
    //sprintf(log_msg, "(client.c) Closed socket: %d, with status: %d\n", clientSocket, shutdownStatus);
    //cLog(log_msg);
    usleep(50000);
  } while(true);
  

  return 0;
}
Пример #30
0
bool
MoveFileSystemJob::copyBlocks( Report& report, CopyTargetDevice& target, CopySourceDevice& source )
{
    /** @todo copyBlocks() assumes that source.sectorSize() == target.sectorSize(). */

    if ( source.sectorSize() != target.sectorSize() )
    {
        report.line() << tr( "The logical sector sizes in the source and target for copying are not the same. This is currently unsupported." );
        return false;
    }

    bool rval = true;
    const qint64 blockSize = 16065 * 8; // number of sectors per block to copy
    const qint64 blocksToCopy = source.length() / blockSize;

    qint64 readOffset = source.firstSector();
    qint64 writeOffset = target.firstSector();
    qint32 copyDir = 1;

    if ( target.firstSector() > source.firstSector() )
    {
        readOffset = source.firstSector() + source.length() - blockSize;
        writeOffset = target.firstSector() + source.length() - blockSize;
        copyDir = -1;
    }

    qint64 blocksCopied = 0;

    void* buffer = malloc( blockSize * source.sectorSize() );
    int percent = 0;

    while ( blocksCopied < blocksToCopy )
    {
        rval = source.readSectors( buffer, readOffset + blockSize * blocksCopied * copyDir, blockSize );
        if ( !rval )
            break;

        rval = target.writeSectors( buffer, writeOffset + blockSize * blocksCopied * copyDir, blockSize );
        if ( !rval )
            break;

        if ( ++blocksCopied * 100 / blocksToCopy != percent )
        {
            percent = blocksCopied * 100 / blocksToCopy;
            progress( qreal( percent ) / 100. );
        }
    }

    const qint64 lastBlock = source.length() % blockSize;

    // copy the remainder
    if ( rval && lastBlock > 0 )
    {
        if ( lastBlock >= blockSize )
            cLog() << "warning: lastBlock: " << lastBlock << ", blockSize: " << blockSize;

        Q_ASSERT( lastBlock < blockSize );

        const qint64 lastBlockReadOffset = copyDir > 0 ? readOffset + blockSize * blocksCopied : source.firstSector();
        const qint64 lastBlockWriteOffset = copyDir > 0 ? writeOffset + blockSize * blocksCopied : target.firstSector();

        rval = source.readSectors( buffer, lastBlockReadOffset, lastBlock );

        if ( rval )
            rval = target.writeSectors( buffer, lastBlockWriteOffset, lastBlock );

        if ( rval )
            emit progress( 1.0 );
    }

    free( buffer );

    return rval;
}