Commit Graph

46 Commits

Author SHA1 Message Date
Jason Rhinelander 42a7e83c33 Replace epee http rpc server with uWebSockets
This replaces the NIH epee http server which does not work all that well
with an external C++ library called uWebSockets.  Fundamentally this
gives the following advantages:

- Much less code to maintain
- Just one thread for handling HTTP connections versus epee's pool of
threads
- Uses existing LokiMQ job server and existing thread pool for handling
the actual tasks; they are processed/scheduled in the same "rpc" or
"admin" queues as lokimq rpc calls.  One notable benefit is that "admin"
rpc commands get their own queue (and thus cannot be delayed by long rpc
commands).  Currently the lokimq threads and the http rpc thread pool
and the p2p thread pool and the job queue thread pool and the dns lookup
thread pool and... are *all* different thread pools; this is a step
towards consolidating them.
- Very little mutex contention (which has been a major problem with epee
RPC in the past): there is one mutex (inside uWebSockets) for putting
responses back into the thread managing the connection; everything
internally gets handled through (lock-free) lokimq inproc sockets.
- Faster RPC performance on average, and much better worst case
performance.  Epee's http interface seems to have some race condition
that ocassionally stalls a request (even a very simple one) for a dozen
or more seconds for no good reason.
- Long polling gets redone here to no longer need threads; instead we
just store the request and respond when the thread pool, or else in a
timer (that runs once/second) for timing out long polls.

---

The basic idea of how this works from a high level:

We launch a single thread to handle HTTP RPC requests and response data.
This uWebSockets thread is essentially running an event loop: it never
actually handles any logic; it only serves to shuttle data that arrives
in a request to some other thread, and then, at some later point, to
send some reply back to that waiting connection.  Everything is
asynchronous and non-blocking here: the basic uWebSockets event loop
just operates as things arrive, passes it off immediately, and goes back
to waiting for the next thing to arrive.

The basic flow is like this:

    0. uWS thread -- listens on localhost:22023
    1. uWS thread -- incoming request on localhost:22023
    2. uWS thread -- fires callback, which injects the task into the LokiMQ job queue
    3. LMQ main loop -- schedules it as an RPC job
    4. LMQ rpc thread -- Some LokiMQ thread runs it, gets the result
    5. LMQ rpc thread -- Result gets queued up for the uWS thread
    6. uWS thread -- takes the request and starts sending it
       (asynchronously) back to the requestor.

In more detail:

uWebSockets has registered has registered handlers for non-jsonrpc
requests (legacy JSON or binary).  If the port is restricted then admin
commands get mapped to a "Access denied" response handler, otherwise
public commands (and admin commands on an unrestricted port) go to the
rpc command handler.

POST requests to /json_rpc have their own handler; this is a little
different than the above because it has to parse the request before it
can determine whether it is allowed or not, but once this is done it
continues roughly the same as legacy/binary requests.

uWebSockets then listens on the given IP/port for new incoming requests,
and starts listening for requests in a thread (we own this thread).
When a request arrives, it fires the event handler for that request.
(This may happen multiple times, if the client is sending a bunch of
data in a POST request).  Once we have the full request, we then queue
the job in LokiMQ, putting it in the "rpc" or "admin" command
categories.  (The one practical different here is that "admin" is
configured to be allowed to start up its own thread if all other threads
are busy, while "rpc" commands are prioritized along with everything
else.)  LokiMQ then schedules this, along with native LokiMQ "rpc." or
"admin." requests.

When a LMQ worker thread becomes available, the RPC command gets called
in it and runs.  Whatever output it produces (or error message, if it
throws) then gets wrapped up in jsonrpc boilerplate (if necessary), and
delivered to the uWebSockets thread to be sent in reply to that request.

uWebSockets picks up the data and sends whatever it can without
blocking, then buffers whatever it couldn't send to be sent again in a
later event loop iteration once the requestor can accept more data.
(This part is outside lokid; we only have to give uWS the data and let
it worry about delivery).

---

PR specifics:

Things removed from this PR:

1. ssl settings; with this PR the HTTP RPC interface is plain-text.  The
previous default generated a self-signed certificate for the server on
startup and then the client accepted any certificate.  This is actually
*worse* than unencrypted because it is entirely MITM-readable and yet
might make people think that their RPC communication is encrypted, and
setting up actual certificates is difficult enough that I think most
people don't bother.

uWebSockets *does* support HTTPS, and we could glue the existing options
into it, but I'm not convinced it's worthwhile: it works much better to
put HTTPS in a front-end proxy holding the certificate that proxies
requests to the backend (which can then listen in restricted mode on
some localhost port).  One reason this is better is that it is much
easier to reload and/or restart such a front-end server, while
certificate updates with lokid require a full restart.  Another reason
is that you get an error page instead of a timeout if something is wrong
with the backend.  Finally we also save having to generate a temporary
certificate on *every* lokid invocation.

2. HTTP Digest authentication.  Digest authentication is obsolete (and
was already obsolete when it got added to Monero).  HTTP-Digest was
originally an attempt to provide a password authentication mechanism
that does not leak the password in transit, but still required that the
server know the password.  It only has marginal value against replay
attacks, and is made entirely obsolete by sending traffic over HTTPS
instead.  No client out there supports Digest but *not* Basic auth, and
so given the limited usefulness it seems pointless to support more than
Basic auth for HTTP RPC login.

What's worse is that epee's HTTP Digest authentication is a terrible
implementation: it uses boost::spirit -- a recursive descent parser
meant for building complex language grammars -- just to parse a single
HTTP header for Digest auth.  This is a big load of crap that should
never have been accepted upstream, and that we should get rid of (even
if we wanted to support Digest auth it takes less than 100 lines of code
to do it when *not* using a recursive descent parser).
2020-08-07 17:14:02 -03:00
Jason Rhinelander 718a9496fb Replace boost chrono & posix_time with stl chrono 2020-07-02 12:52:13 -03:00
Jason Rhinelander 9c5c1dac50 Replace boost::regex with std::regex 2020-07-02 12:52:12 -03:00
Doyle e98e787d88 Merge commit '082730b6e569e155988df5c5b376c45fba56b396' into MergeUpstream3 2020-05-21 12:00:20 +10:00
Jason Rhinelander 0e3f173c7f RPC overhaul
High-level details:

This redesigns the RPC layer to make it much easier to work with,
decouples it from an embedded HTTP server, and gets the vast majority of
the RPC serialization and dispatch code out of a very commonly included
header.

There is unfortunately rather a lot of interconnected code here that
cannot be easily separated out into separate commits.  The full details
of what happens here are as follows:

Major details:
- All of the RPC code is now in a `cryptonote::rpc` namespace; this
  renames quite a bit to be less verbose: e.g. CORE_RPC_STATUS_OK
  becomes `rpc::STATUS_OK`, and `cryptonote::COMMAND_RPC_SOME_LONG_NAME`
  becomes `rpc::SOME_LONG_NAME` (or just SOME_LONG_NAME for code already
  working in the `rpc` namespace).
- `core_rpc_server` is now completely decoupled from providing any
  request protocol: it is now *just* the core RPC call handler.
- The HTTP RPC interface now lives in a new rpc/http_server.h; this code
  handles listening for HTTP requests and dispatching them to
  core_rpc_server, then sending the results back to the caller.
- There is similarly a rpc/lmq_server.h for LMQ RPC code; more details
  on this (and other LMQ specifics) below.
- RPC implementing code now returns the response object and throws when
  things go wrong which simplifies much of the rpc error handling.  They
  can throw anything; generic exceptions get logged and a generic
  "internal error" message gets returned to the caller, but there is
  also an `rpc_error` class to return an error code and message used by
  some json-rpc commands.
- RPC implementing functions now overload `core_rpc_server::invoke`
  following the pattern:

    RPC_BLAH_BLAH::response core_rpc_server::invoke(RPC_BLAH_BLAH::request&& req, rpc_context context);

  This overloading makes the code vastly simpler: all instantiations are
  now done with a small amount of generic instantiation code in a single
  .cpp rather than needing to go to hell and back with a nest of epee
  macros in a core header.
- each RPC endpoint is now defined by the RPC types themselves,
  including its accessible names and permissions, in
  core_rpc_server_commands_defs.h:
  - every RPC structure now has a static `names()` function that returns
    the names by which the end point is accessible.  (The first one is
    the primary, the others are for deprecated aliases).
  - RPC command wrappers define their permissions and type by inheriting
    from special tag classes:
    - rpc::RPC_COMMAND is a basic, admin-only, JSON command, available
      via JSON RPC.  *All* JSON commands are now available via JSON RPC,
      instead of the previous mix of some being at /foo and others at
      /json_rpc.  (Ones that were previously at /foo are still there for
      backwards compatibility; see `rpc::LEGACY` below).
    - rpc::PUBLIC specifies that the command should be available via a
      restricted RPC connection.
    - rpc::BINARY specifies that the command is not JSON, but rather is
      accessible as /name and takes and returns values in the magic epee
      binary "portable storage" (lol) data format.
    - rpc::LEGACY specifies that the command should be available via the
      non-json-rpc interface at `/name` for backwards compatibility (in
      addition to the JSON-RPC interface).
- some epee serialization got unwrapped and de-templatized so that it
  can be moved into a .cpp file with just declarations in the .h.  (This
  makes a *huge* difference for core_rpc_server_commands_defs.h and for
  every compilation unit that includes it which previously had to
  compile all the serialization code and then throw all by one copy away
  at link time).  This required some new macros so as to not break a ton
  of places that will use the old way putting everything in the headers;
  The RPC code uses this as does a few other places; there are comments
  in contrib/epee/include/serialization/keyvalue_serialization.h as to
  how to use it.
- Detemplatized a bunch of epee/storages code.  Most of it should have
  have been using templates at all (because it can only ever be called
  with one type!), and now it isn't.  This broke some things that didn't
  properly compile because of missing headers or (in one case) a messed
  up circular dependency.
- Significantly simplified a bunch of over-templatized serialization
  code.
- All RPC serialization definitions is now out of
  core_rpc_server_commands_defs.h and into a single .cpp file
  (core_rpc_server_commands_defs.cpp).
- core RPC no longer uses the disgusting
  BEGIN_URI_MAP2/MAP_URI_BLAH_BLAH macros.  This was a terrible design
  that forced slamming tons of code into a common header that didn't
  need to be there.
- epee::struct_init is gone.  It was a horrible hack that instiated
  multiple templates just so the coder could be so lazy and write
  `some_type var;` instead of properly value initializing with
  `some_type var{};`.
- Removed a bunch of useless crap from epee.  In particular, forcing
  extra template instantiations all over the place in order to nest
  return objects inside JSON RPC values is no longer needed, as are a
  bunch of stuff related to the above de-macroization of the code.
- get_all_service_nodes, get_service_nodes, and get_n_service_nodes are
  now combined into a single `get_service_nodes` (with deprecated
  aliases for the others), which eliminates a fair amount of
  duplication.  The biggest obstacle here was getting the requested
  fields reference passed through: this is now done by a new ability to
  stash a context in the serialization object that can be retrieved by a
  sub-serialized type.

LMQ-specifics:

- The LokiMQ instance moves into `cryptonote::core` rather than being
  inside cryptonote_protocol.  Currently the instance is used both for
  qnet and rpc calls (and so needs to be in a common place), but I also
  intend future PRs to use the batching code for job processing
  (replacing the current threaded job queue).
- rpc/lmq_server.h handles the actual LMQ-request-to-core-RPC glue.
  Unlike http_server it isn't technically running the whole LMQ stack
  from here, but the parallel name with http_server seemed appropriate.
- All RPC endpoints are supported by LMQ under the same names as defined
  generically, but prefixed with `rpc.` for public commands and `admin.`
  for restricted ones.
- service node keys are now always available, even when not running in
  `--service-node` mode: this is because we want the x25519 key for
  being able to offer CURVE encryption for lmq RPC end-points, and
  because it doesn't hurt to have them available all the time.  In the
  RPC layer this is now called "get_service_keys" (with
  "get_service_node_key" as an alias) since they aren't strictly only
  for service nodes.  This also means code needs to check
  m_service_node, and not m_service_node_keys, to tell if it is running
  as a service node.  (This is also easier to notice because
  m_service_node_keys got renamed to `m_service_keys`).
- Added block and mempool monitoring LMQ RPC endpoints: `sub.block` and
  `sub.mempool` subscribes the connection for new block and new mempool
  TX notifications.  The latter can notify on just blink txes, or all
  new mempool txes (but only new ones -- txes dumped from a block don't
  trigger it).  The client gets pushed a [`notify.block`, `height`,
  `hash`] or [`notify.tx`, `txhash`, `blob`] message when something
  arrives.

Minor details:
- rpc::version_t is now a {major,minor} pair.  Forcing everyone to pack
  and unpack a uint32_t was gross.
- Changed some macros to constexprs (e.g. CORE_RPC_ERROR_CODE_...).
  (This immediately revealed a couple of bugs in the RPC code that was
  assigning CORE_RPC_ERROR_CODE_... to a string, and it worked because
  the macro allows implicit conversion to a char).
- De-templatizing useless templates in epee (i.e. a bunch of templated
  types that were never invoked with different types) revealed a painful
  circular dependency between epee and non-epee code for tor_address and
  i2p_address.  This crap is now handled in a suitably named
  `net/epee_network_address_hack.cpp` hack because it really isn't
  trivial to extricate this mess.
- Removed `epee/include/serialization/serialize_base.h`.  Amazingly the
  code somehow still all works perfectly with this previously vital
  header removed.
- Removed bitrotted, unused epee "crypted_storage" and
  "gzipped_inmemstorage" code.
- Replaced a bunch of epee::misc_utils::auto_scope_leave_caller with
  LOKI_DEFERs.  The epee version involves quite a bit more instantiation
  and is ugly as sin.  Also made the `loki::defer` class invokable for
  some edge cases that need calling before destruction in particular
  conditions.
- Moved the systemd code around; it makes much more sense to do the
  systemd started notification as in daemon.cpp as late as possible
  rather than in core (when we can still have startup failures, e.g. if
  the RPC layer can't start).
- Made the systemd short status string available in the get_info RPC
  (and no longer require building with systemd).
- during startup, print (only) the x25519 when not in SN mode, and
  continue to print all three when in SN mode.
- DRYed out some RPC implementation code (such as set_limit)
- Made wallet_rpc stop using a raw m_wallet pointer
2020-05-11 18:44:45 -03:00
Jason Rhinelander 743d4e60ce Various linking and build fixes
- updating to latest loki-mq (1.0.0 + various linking fixes)
- BUILD_SHARED_LIBS was being handled very strangely; make it a full
option instead (defaulting to off) that a cmake invoker can specify, as
per cmake recommendations.
- travis ci tweaks/changes:
  - Add a static bionic build
  - Simplify cmake argument code
  - Add `--version` invocation for lokid and loki-wallet-cli to test
    that the binaries were linked properly.
- always build an embedded sodium statically; if we do it dynamically
and an older system one exists we are going to have trouble.
- don't force epee and blocks to be static; rather they get controlled
by the above BUILD_SHARED_LIBS, just like all the other internal
libraries.
- use some PkgConfig:: imported targets rather than bunch-of-variables.
2020-03-15 14:29:47 -03:00
Jason Rhinelander 5b97ff6e9c cmake modernization
The archaic (i.e. decade old) cmake usage here really got in the way of
trying to properly use newer libraries (like lokimq), so this undertakes
overhauling it considerably to make it much more sane (and significantly
reduce the size).

I left more of the architecture-specific bits in the top-level
CMakeLists.txt intact; most of the efforts here are about properly
loading dependencies, specifying dependencies and avoiding a whole pile
of cmake antipatterns.

This bumps the required cmake version to 3.5, which is what xenial comes
with.

- extensive use of interface libraries to include libraries,
definitions, and include paths

- use Boost::whatever instead of ${Boost_WHATEVER_LIBRARY}.  The
interface targets are (again) much better as they also give you any
needed include or linking flags without needing to worry about them.

- don't list header files when building things.  This has *never* been
correct cmake usage (cmake has always known how to wallet_rpc_headers
the headers that .cpp files include to know about build changes).

- remove the loki_add_library monstrosity; it breaks target names and
makes compiling less efficient because the author couldn't figure out
how to link things together.

- make loki_add_executable take the output filename, and set the output
path to bin/ and install to bin because *every single usage* of
loki_add_executable was immediately followed by setting the output
filename and setting the output path to bin/ and installing to bin.

- move a bunch of crap that is only used in one particular
src/whatever/CMakeLists.txt into that particular CMakeLists.txt instead
of the top level CMakeLists.txt (or src/CMakeLists.txt).

- Remove a bunch of redundant dependencies; most of them look like they
were just copy-and-pasted in, and many more aren't needed (since they
are implied by the PUBLIC linking of other dependencies).

- Removed `die` since it just does a FATAL_ERROR, but adds color (which
is useless since CMake already makes FATAL_ERRORs perfectly visible).

- Change the way LOKI_DAEMON_AND_WALLET_ONLY works to just change the
make targets to daemon and simplewallet rather than changing the build
process (this should make it faster, too, since there are various other
things that will be excluded).
2020-03-06 00:36:57 -04:00
Jason Rhinelander 055b593237 Fix contrib/depends library incompatibilities
sodium and zmq libs weren't using the same variable name which would end
up linking to system libsodium even when we meant to link to the static
one from contrib/depends.
2019-12-19 20:24:38 -04:00
Jason Rhinelander ca36648749 Split up huge instanciations & header fixes
rpc/instanciations.cpp is a huge compiler job because it includes two
separate huge template instanciations [sic] in it.  Splitting it apart
into two separate compilation units makes compilation more
parallelizable and requires less ram for the individual job.

The split also revealed a few missing headers in epee for logging macros.
2019-12-03 00:51:18 -04:00
Jason Rhinelander 08ff25be94 Use PkgConfig to properly find zmq/sodium
The existing code just assumes it is already in the path, which fails
when it's in some prefixed place with a proper .pc file installed (such
as for a homebrew installation).
2019-12-03 00:51:18 -04:00
xiphon 082730b6e5 daemon: automatic public nodes discovering and bootstrap daemon switching 2019-08-27 12:01:49 +00:00
Michal vel m@lbit 1db5357c7b rpc headers fix 2019-06-25 01:49:04 +01:00
Doyle 892469ded1 Update monero copyright to 2019 pre-emptively to make merge simpler 2019-04-12 14:36:43 +10:00
Doyle 47566c63df Merge commit '973403bc9f54ab0722b67a3c76ab6e7bafbfeedc' 2019-04-09 18:07:13 +10:00
binaryFate 1f2930ce0b Update 2019 copyright 2019-03-05 22:05:34 +01:00
Lee Clagett 973403bc9f Adding initial support for broadcasting transactions over Tor
- Support for ".onion" in --add-exclusive-node and --add-peer
  - Add --anonymizing-proxy for outbound Tor connections
  - Add --anonymous-inbounds for inbound Tor connections
  - Support for sharing ".onion" addresses over Tor connections
  - Support for broadcasting transactions received over RPC exclusively
    over Tor (else broadcast over public IP when Tor not enabled).
2019-01-28 23:56:33 +00:00
doy-lee 40506127a4 Merge commit '7e957c1' into LokiMergeUpstream 2018-12-11 13:46:35 +11:00
Jethro Grassie 517f25efd1
rpc: add version to get_info 2018-11-21 12:56:34 -05:00
doy-lee 8f03bb3fd7 Merge commit '8534f71' into LokiMergeUpstream 2018-11-12 14:55:42 +11:00
doy-lee 42f0933e58 Merge commit '7e2483e' into LokiMergeUpstream 2018-11-05 11:27:45 +11:00
Dusan Klinec e178bf234a
rpc: fix linking error of 6097472a, get_output_distribution
Undefined symbols for architecture x86_64:
  "cryptonote::core::get_output_distribution(unsigned long long, unsigned long long, unsigned long long, unsigned long long&, std::__1::vector<unsigned long long, std::__1::allocator<unsigned long long> >&, unsigned long long&) const", referenced from:
      cryptonote::rpc::RpcHandler::get_output_distribution(cryptonote::core&, unsigned long long, unsigned long long, unsigned long long, bool) in rpc_handler.cpp.o
2018-11-04 23:38:52 +01:00
Lee Clagett 6097472a19 Update ZMQ fee estimate and add ZMQ output distribution 2018-10-23 23:46:31 -04:00
doy-lee ad8cdc1d1f Merge commit '702a410' into LokiMergeUpstream20180821 2018-09-19 14:18:52 +10:00
moneromooo-monero 438d52deaf
remove epee from link lines where it's redundant
For some reason, this confuses and kills ASAN on startup
as it thinks const uint8_t ipv4_network_address::ID is
defined multiple times.
2018-06-28 16:45:22 +01:00
Doyle T 808c07768c Update cmakelists and misc refs to Loki 2018-04-25 16:13:38 +10:00
xmr-eric 18216f19dd Update 2018 copyright 2018-01-26 10:03:20 -05:00
stoffu 6d8b29ef28
fix some link errors in debug mode for macos 2018-01-10 01:57:56 +00:00
moneromooo-monero 43f5269f84
Wallets now do not depend on the daemon rpc lib
The shared RPC code is now moved off into a separate lib
2017-12-16 23:28:59 +00:00
moneromooo-monero 4abf25f3c9
cryptonote_core does not depend on p2p anymore
As a followon side effect, this makes a lot of inline code
included only in particular cpp files (and instanciated
when necessary.
2017-12-16 23:28:38 +00:00
stoffu e29282d208
build: auto update version info without manually deleting version.h 2017-09-21 07:47:37 +09:00
Thomas Winget 0299cb77ca
Fix various oversights/bugs in ZMQ RPC server code
- Add some RPC commands (and touch up a couple others)
- some bounds checking
- some better pointer management
- const correctness and error handling

-- Thanks @vtnerd for type help with serialization and CMake changes
2017-09-05 12:20:40 -04:00
Thomas Winget 77986023c3
json serialization for rpc-relevant monero types
Structured {de-,}serialization methods for (many new) types
which are used for requests or responses in the RPC.

New types include RPC requests and responses, and structs which compose
types within those.

# Conflicts:
#	src/cryptonote_core/blockchain.cpp
2017-09-05 12:20:27 -04:00
Riccardo Spagni c3599fa7b9
update copyright year, fix occasional lack of newline at line end 2017-02-21 19:38:18 +02:00
Riccardo Spagni eacf2124b6 Merge pull request #1689
ce7fcbb4 Add server auth to monerod, and client auth to wallet-cli and wallet-rpc (Lee Clagett)
2017-02-11 00:35:25 +02:00
kenshi84 8027ce0c75 extract some basic code from libcryptonote_core into libcryptonote_basic 2017-02-08 22:45:15 +09:00
Lee Clagett ce7fcbb4ae Add server auth to monerod, and client auth to wallet-cli and wallet-rpc 2017-02-06 01:15:41 -05:00
Lee Clagett bdc3d7496f Adding HTTP Digest Auth (but not yet enabled) 2016-12-13 00:19:54 -05:00
Randi Joseph 9e54616924 Dropped "bit" from bitmonero. 2016-09-26 17:22:30 -04:00
redfish e1c7af35d4 cmake: transitive deps and remove deprecated LINK_*
Keep the immediate direct deps at the library that depends on them,
declare deps as PUBLIC so that targets that link against that library
get the library's deps as transitive deps.

Break dep cycle between blockchain_db <-> crytonote_core.
No code refactoring, just hide cycle from cmake so that
it doesn't complain (cycles are allowed only between
static libs, not shared libs).

This is in preparation for supproting BUILD_SHARED_LIBS cmake
built-in option for building internal libs as shared.
2016-09-18 02:56:26 -04:00
Riccardo Spagni de03926850
updated copyright year 2015-12-31 08:39:56 +02:00
rfree2monero c511abf005 remerged; commands JSON. logging upgrade. doxygen 2015-04-01 19:00:45 +02:00
Riccardo Spagni f4b69d553a
year updated in license 2015-01-02 18:52:46 +02:00
Ben Boeckel 7d708e4223 cmake: support 2.8.7
Older versions of CMake support LINK_{PUBLIC,PRIVATE} while newer
versions prefer PUBLIC and PRIVATE instead, but still support the LINK_
prefix.
2014-10-24 15:29:51 -04:00
Ben Boeckel f53f04724c cmake: handle private vs. public headers 2014-10-23 16:42:34 -04:00
Ben Boeckel 55ca7d3b34 cmake: refactor common code with libraries 2014-10-23 16:42:34 -04:00
Ben Boeckel 89cff7bddc cmake: put each library into its own directory
This cleans up the CMake code and shows patterns more easily (to be
refactored in the next commit).
2014-10-23 16:42:34 -04:00