Exemple #1
0
        message(nocopy_t, boost::asio::mutable_buffer const& buffer, Deleter&& deleter)
        {
            using D = typename std::decay<Deleter>::type;

            const auto call_deleter = [](void *buf, void *hint) {
                std::unique_ptr<D> deleter(reinterpret_cast<D*>(hint));
                BOOST_ASSERT_MSG(deleter, "!deleter");
                (*deleter)(buf);
            };

            std::unique_ptr<D> d(new D(std::forward<Deleter>(deleter)));
            auto rc = zmq_msg_init_data(&msg_,
                                        boost::asio::buffer_cast<void*>(buffer),
                                        boost::asio::buffer_size(buffer),
                                        call_deleter, d.get());
            if (rc)
                throw boost::system::system_error(make_error_code());
            d.release();
        }
void WalletSerializer::deserialize(std::istream& stream, const std::string& password, std::string& cache) {
  cryptonote::BinaryInputStreamSerializer serializerEncrypted(stream);

  serializerEncrypted.beginObject("wallet");

  uint32_t version;
  serializerEncrypted(version, "version");

  crypto::chacha8_iv iv;
  serializerEncrypted(iv, "iv");

  std::string cipher;
  serializerEncrypted(cipher, "data");

  serializerEncrypted.endObject();

  std::string plain;
  decrypt(cipher, plain, iv, password);

  std::stringstream decryptedStream(plain);

  cryptonote::BinaryInputStreamSerializer serializer(decryptedStream);

  try
  {
    loadKeys(serializer);
    throwIfKeysMissmatch(account.get_keys().m_view_secret_key, account.get_keys().m_account_address.m_viewPublicKey);
    throwIfKeysMissmatch(account.get_keys().m_spend_secret_key, account.get_keys().m_account_address.m_spendPublicKey);
  }
  catch (std::exception&) {
    throw std::system_error(make_error_code(cryptonote::error::WRONG_PASSWORD));
  }

  bool detailsSaved;

  serializer(detailsSaved, "has_details");

  if (detailsSaved) {
    serializer(transactionsCache, "details");
  }

  serializer.binary(cache, "cache");
}
void AsyncMockStreamFactory::MockStream::read(asio::mutable_buffer buf,
                                              StreamHandler&& readHandler) {
    // Suspend execution before data is read.
    _defer(kBlockedBeforeRead,
           [this, buf, readHandler]() {
               stdx::unique_lock<stdx::mutex> lk(_mutex);
               int nToCopy = 0;

               // If we've set an error, return that instead of a read.
               if (!_error) {
                   auto nextRead = std::move(_readQueue.front());
                   _readQueue.pop();

                   auto beginDst = asio::buffer_cast<uint8_t*>(buf);
                   nToCopy = std::min(nextRead.size(), asio::buffer_size(buf));

                   auto endSrc = std::begin(nextRead);
                   std::advance(endSrc, nToCopy);

                   auto endDst = std::copy(std::begin(nextRead), endSrc, beginDst);
                   invariant((endDst - beginDst) == static_cast<std::ptrdiff_t>(nToCopy));
                   log() << "read " << nToCopy << " bytes, " << (nextRead.size() - nToCopy)
                         << " remaining in buffer";
               }

               auto handler = readHandler;

               // If we did not receive all the bytes, we should return an error
               if (static_cast<size_t>(nToCopy) < asio::buffer_size(buf)) {
                   handler = [readHandler](std::error_code ec, size_t len) {
                       // If we have an error here we've been canceled, and that takes precedence
                       if (ec)
                           return readHandler(ec, len);

                       // Call the original handler with an error
                       readHandler(make_error_code(ErrorCodes::InvalidLength), len);
                   };
               }

               checkCanceled(_io_service, &_state, std::move(handler), nToCopy, _error);
               _error.clear();
           });
}
void InProcessNode::getTransactionOutsGlobalIndices(const crypto::hash& transactionHash, std::vector<uint64_t>& outsGlobalIndices,
    const Callback& callback)
{
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(cryptonote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(&InProcessNode::getTransactionOutsGlobalIndicesAsync,
      this,
      std::cref(transactionHash),
      std::ref(outsGlobalIndices),
      callback
    )
  );
}
std::error_code InProcessNode::doQueryBlocks(std::list<crypto::hash>&& knownBlockIds, uint64_t timestamp,
    std::list<BlockCompleteEntry>& newBlocks, uint64_t& startHeight) {
  uint64_t currentHeight, fullOffset;
  std::list<cryptonote::BlockFullInfo> entries;

  if (!core.queryBlocks(knownBlockIds, timestamp, startHeight, currentHeight, fullOffset, entries)) {
    return make_error_code(cryptonote::error::INTERNAL_NODE_ERROR);
  }

  for (const auto& entry: entries) {
    BlockCompleteEntry bce;
    bce.blockHash = entry.block_id;
    bce.block = entry.block;
    std::copy(entry.txs.begin(), entry.txs.end(), std::back_inserter(bce.txs));

    newBlocks.push_back(std::move(bce));
  }

  return std::error_code();
}
int main()
{
    {
        std::string what_arg("io test message");
        std::ios_base::failure se(what_arg, make_error_code(std::errc::is_a_directory));
        assert(se.code() == std::make_error_code(std::errc::is_a_directory));
        std::string what_message(se.what());
        assert(what_message.find(what_arg) != std::string::npos);
        assert(what_message.find("Is a directory") != std::string::npos);
    }
    {
        std::string what_arg("io test message");
        std::ios_base::failure se(what_arg);
        assert(se.code() == std::make_error_code(std::io_errc::stream));
        std::string what_message(se.what());
        assert(what_message.find(what_arg) != std::string::npos);
        assert(what_message.find(std::iostream_category().message(static_cast<int>
            (std::io_errc::stream))) != std::string::npos);
    }
}
Exemple #7
0
void InProcessNode::getRandomOutsByAmounts(std::vector<uint64_t>&& amounts, uint64_t outsCount,
    std::vector<CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount>& result, const Callback& callback)
{
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(CryptoNote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(&InProcessNode::getRandomOutsByAmountsAsync,
      this,
      std::move(amounts),
      outsCount,
      std::ref(result),
      callback
    )
  );
}
Exemple #8
0
void InProcessNode::queryBlocks(std::vector<Crypto::Hash>&& knownBlockIds, uint64_t timestamp, std::vector<BlockShortEntry>& newBlocks,
  uint32_t& startHeight, const Callback& callback) {
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(CryptoNote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
          std::bind(&InProcessNode::queryBlocksLiteAsync,
                  this,
                  std::move(knownBlockIds),
                  timestamp,
                  std::ref(newBlocks),
                  std::ref(startHeight),
                  callback
          )
  );
}
void InProcessNode::getNewBlocks(std::list<crypto::hash>&& knownBlockIds, std::list<cryptonote::block_complete_entry>& newBlocks,
    uint64_t& startHeight, const Callback& callback)
{
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(cryptonote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(&InProcessNode::getNewBlocksAsync,
      this,
      std::move(knownBlockIds),
      std::ref(newBlocks),
      std::ref(startHeight),
      callback
    )
  );
}
void WalletSerializerV1::loadWalletV1Keys(CryptoNote::BinaryInputStreamSerializer& serializer) {
  CryptoNote::KeysStorage keys;

  try {
    keys.serialize(serializer, "keys");
  } catch (const std::runtime_error&) {
    throw std::system_error(make_error_code(CryptoNote::error::WRONG_PASSWORD));
  }

  m_viewPublicKey = keys.viewPublicKey;
  m_viewSecretKey = keys.viewSecretKey;

  WalletRecord wallet;
  wallet.spendPublicKey = keys.spendPublicKey;
  wallet.spendSecretKey = keys.spendSecretKey;
  wallet.actualBalance = 0;
  wallet.pendingBalance = 0;
  wallet.creationTimestamp = static_cast<time_t>(keys.creationTimestamp);

  m_walletsContainer.get<RandomAccessIndex>().push_back(wallet);
}
 virtual void Cancel() override
 {
     if (request_)
     {
         request_->Cancel();
     }
     else
     {
         auto self = this->shared_from_this();
         callback_io_service_->dispatch(
             [this, self]()
             {
                 // No http request yet.  Must create the response.
                 ResponseType response;
                 response.error_code = make_error_code(
                     mf::http::http_error::Cancelled );
                 response.error_string = "Cancelled";
                 completion_callback_(response);
             });
     }
 }
void StartPoll(const std::string & upload_key, FSM & fsm)
{
    if (upload_key.empty())
    {
        assert(!"Reached poll upload without upload key");
        fsm.ProcessEvent(
                event::Error{make_error_code(uploader::errc::LogicError),
                             "Filsize unavailable."});
        return;
    }

    auto fsmp = fsm.AsFrontShared();

    fsm.GetSessionMaintainer()->Call(
            mf::api::upload::poll_upload::Request(upload_key),
            [fsmp, upload_key](
                    const mf::api::upload::poll_upload::Response & response)
            {
                HandlePollResponse(upload_key, *fsmp, response);
            });
}
UploadManagerImpl::~UploadManagerImpl()
{
    mf::utils::unique_lock<mf::utils::mutex> lock(mutex_);

    disable_enqueue_ = true;

    std::set<StateMachinePointer> requests;
    std::swap(requests, requests_);

    // Unlock before calling external
    lock.unlock();

    for (auto & request : requests)
    {
        request->Disconnect();
        request->process_event(event::Error{
            make_error_code(mf::uploader::errc::Cancelled),
            "Cancelled due to shutdown."
            });
    }
}
Exemple #14
0
void InProcessNode::getPoolTransactions(uint64_t timestampBegin, uint64_t timestampEnd, uint32_t transactionsNumberLimit, std::vector<TransactionDetails>& transactions, uint64_t& transactionsNumberWithinTimestamps, const Callback& callback) {
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(CryptoNote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(
      &InProcessNode::getPoolTransactionsAsync,
      this,
      timestampBegin,
      timestampEnd,
      transactionsNumberLimit,
      std::ref(transactions),
      std::ref(transactionsNumberWithinTimestamps),
      callback
    )
  );
}
void INodeTrivialRefreshStub::doRelayTransaction(const cryptonote::Transaction& transaction, const Callback& callback)
{
  ContextCounterHolder counterHolder(m_asyncCounter);
  std::unique_lock<std::mutex> lock(m_multiWalletLock);

  if (m_nextTxError)
  {
    m_nextTxError = false;
    callback(make_error_code(cryptonote::error::INTERNAL_WALLET_ERROR));
    return;
  }

  if (m_nextTxToPool) {
    m_nextTxToPool = false;
    m_blockchainGenerator.putTxToPool(transaction);
    callback(std::error_code());
    return;
  }

  m_blockchainGenerator.addTxToBlockchain(transaction);
  callback(std::error_code());
}
Exemple #16
0
void InProcessNode::getPoolSymmetricDifference(std::vector<crypto::hash>&& knownPoolTxIds, crypto::hash knownBlockId, bool& isBcActual, std::vector<cryptonote::Transaction>& newTxs,
  std::vector<crypto::hash>& deletedTxIds, const Callback& callback) {

  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(cryptonote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(&InProcessNode::getPoolSymmetricDifferenceAsync,
      this,
      std::move(knownPoolTxIds),
      knownBlockId,
      std::ref(isBcActual),
      std::ref(newTxs),
      std::ref(deletedTxIds),
      callback
    )
  );
}
Exemple #17
0
int main()
{
    {
        std::packaged_task<double(int, char)> p(A(5));
        std::future<double> f = p.get_future();
        std::thread(func, std::move(p)).detach();
        try
        {
            double i = f.get();
            assert(false);
        }
        catch (const std::future_error& e)
        {
            assert(e.code() == make_error_code(std::future_errc::broken_promise));
        }
    }
    {
        std::packaged_task<double(int, char)> p(A(5));
        std::future<double> f = p.get_future();
        std::thread(func2, std::move(p)).detach();
        assert(f.get() == 105.0);
    }
}
Exemple #18
0
void demo_cancelled()
{
  std::cout << "[demo cancelled]" << std::endl;
  boost::asio::io_service io_service;

  // Use scope to force lifetime.
  {
    boost::asio::steady_timer timer(io_service);

    // Initiate an async_wait operation that will immediately expire.
    timer.expires_at(boost::asio::steady_timer::clock_type::now());
    timer.async_wait(
        [](const boost::system::error_code& error)
        {
          std::cout << "error: " << error.message() << std::endl;
          assert(error ==
                 make_error_code(boost::asio::error::operation_aborted));
        });
  } // Destroy the timer.

  // Run the handle_wait completion handler.
  io_service.run();
}
Exemple #19
0
	bool winsock2_streambuf::rw_error(int res, int err, error_code_type & err_code)
	{
		// error can be result of shutdown from interrupt
		auto state = m_state.load(std::memory_order_relaxed);
		if (state >= Interrupting)
		{
			err_code = std::make_error_code(std::errc::interrupted);
			return true;
		}

		// it was eof
		if (res >= 0)
		{
			err_code = make_error_code(sock_errc::eof);
			return true;
		}

		// when using nonblocking socket, EWOULDBLOCK mean repeat operation later,
		if (err == WSAEINTR || err == WSAEWOULDBLOCK) return false;

		err_code.assign(err, std::system_category());
		return true;
	}
Exemple #20
0
void Wallet::initAndGenerate(const std::string& password) {
  {
    std::unique_lock<std::mutex> stateLock(m_cacheMutex);

    if (m_state != NOT_INITIALIZED) {
      throw std::system_error(make_error_code(cryptonote::error::NOT_INITIALIZED));
    }

    m_node.addObserver(m_autoRefresher.get());

    m_account.generate();
    m_password = password;

    m_sender.init(m_account.get_keys());

    storeGenesisBlock();

    m_state = INITIALIZED;
  }

  m_observerManager.notify(&IWalletObserver::initCompleted, std::error_code());
  refresh();
}
int main()
{
    {
        typedef int T;
        T i = 3;
        std::promise<T> p;
        std::future<T> f = p.get_future();
        p.set_value(i);
        ++i;
        assert(f.get() == 3);
        --i;
        try
        {
            p.set_value(i);
            assert(false);
        }
        catch (const std::future_error& e)
        {
            assert(e.code() == make_error_code(std::future_errc::promise_already_satisfied));
        }
    }
    {
        typedef A T;
        T i;
        std::promise<T> p;
        std::future<T> f = p.get_future();
        try
        {
            p.set_value(i);
            assert(false);
        }
        catch (int j)
        {
            assert(j == 10);
        }
    }
}
Exemple #22
0
void InProcessNode::getTransactions(const std::vector<Crypto::Hash>& transactionHashes, std::vector<TransactionDetails>& transactions, const Callback& callback) {
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(CryptoNote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(
      static_cast<
        void(InProcessNode::*)(
          const std::vector<Crypto::Hash>&, 
          std::vector<TransactionDetails>&, 
          const Callback&
        )
      >(&InProcessNode::getTransactionsAsync),
      this,
      std::cref(transactionHashes),
      std::ref(transactions),
      callback
    )
  );
}
Exemple #23
0
void InProcessNode::getBlocks(const std::vector<uint32_t>& blockHeights, std::vector<std::vector<BlockDetails>>& blocks, const Callback& callback) {
  std::unique_lock<std::mutex> lock(mutex);
  if (state != INITIALIZED) {
    lock.unlock();
    callback(make_error_code(CryptoNote::error::NOT_INITIALIZED));
    return;
  }

  ioService.post(
    std::bind(
      static_cast<
        void(InProcessNode::*)(
        const std::vector<uint32_t>&,
          std::vector<std::vector<BlockDetails>>&, 
          const Callback&
        )
      >(&InProcessNode::getBlocksAsync),
      this,
      std::cref(blockHeights),
      std::ref(blocks),
      callback
    )
  );
}
Exemple #24
0
	bool bsdsock_streambuf::rw_error(int res, int err, error_code_type & err_code)
	{
		// error can be result of shutdown from interrupt
		auto state = m_state.load(std::memory_order_relaxed);
		if (state >= Interrupting) 
		{
			err_code = std::make_error_code(std::errc::interrupted);
			return true;
		}
		
		// it was eof
		if (res >= 0)
		{
			err_code = make_error_code(sock_errc::eof);
			return true;
		}
		
		// when using nonblocking socket, EAGAIN/EWOULDBLOCK mean repeat operation later,
		// also select allowed return EAGAIN instead of ENOMEM -> repeat either
		if (err == EAGAIN || err == EWOULDBLOCK || err == EINTR) return false;
		
		err_code.assign(err, std::generic_category());
		return true;
	}
Exemple #25
0
const client::impl& client::_get_impl() const {
    if (!_impl) {
        throw logic_error{make_error_code(error_code::k_invalid_client_object)};
    }
    return *_impl;
}
Exemple #26
0
 static error_code error() {
   return make_error_code(errc::invalid_argument);
 }
Exemple #27
0
invalid_groups_count_error::invalid_groups_count_error()
	: std::system_error(make_error_code(libmastermind_error::invalid_groups_count))
{}
Exemple #28
0
 std::vector<lcos::future<T> >
 wait_all(lcos::future<T> f0 , lcos::future<T> f1 , lcos::future<T> f2,
     error_code& ec = throws)
 {
     typedef std::vector<lcos::future<T> > result_type;
     lcos::future<result_type> f = when_all(
         f0 , f1 , f2);
     if (!f.valid()) {
         { if (&ec == &hpx::throws) { HPX_THROW_EXCEPTION( uninitialized_value, "lcos::wait_all", "lcos::when_all didn't return a valid future"); } else { ec = make_error_code(static_cast<hpx::error>( uninitialized_value), "lcos::when_all didn't return a valid future", "lcos::wait_all", "D:/Devel\\hpx\\hpx\\lcos\\wait_all.hpp", 435, (ec.category() == hpx::get_lightweight_hpx_category()) ? hpx::lightweight : hpx::plain); } };
         return result_type();
     }
     return f.get(ec);
 }
Exemple #29
0
 error_code(ErrorEnum e)
 {
   *this = make_error_code(e);
 }
Exemple #30
0
cache_is_expired_error::cache_is_expired_error()
	: std::system_error(make_error_code(libmastermind_error::cache_is_expired))
{}