Skip to content
This repository was archived by the owner on Nov 4, 2026. It is now read-only.

[WIP] Add jmwalletd and support wallet display RPC. - #670

Closed
AdamISZ wants to merge 12 commits into
masterfrom
rpc-api-1
Closed

AdamISZ wants to merge 12 commits into
masterfrom
rpc-api-1

Conversation

@AdamISZ

@AdamISZ AdamISZ commented Aug 18, 2020

Copy link
Copy Markdown
Member

Just a first start in a basic form only suitable for testing.

Uses Klein to provide HTTP server support. The server is TLS and if you want to test it you must add key.pem and cert.pem into the scripts/ directory.

provides /wallet/walletname/unlock for which the password is provided in POST, and /wallet/walletname/display providing the full jmclient.wallet_utils.WalletView serialization in a new json format.
Note the preflight/preflight2 methods are for CORS, obviously that is not a final form.

Apart from filling out the API, the most important outstanding issue is state/session management; we provide an unlock but have no access control linking the unlocking action with future permissible actions.

This code is an illustration of what is meant by this gist, also see this new repo for an Angular client for this RPC server.

@decentclock

Copy link
Copy Markdown
Contributor

I played around with this a little. I can successfully load a wallet generated both manually, and one created by ygrunner.py. Maybe this is to be expected, but if I want to load a different wallet after loading the first one, I have to completely shutdown jmwalletd.py.

Question: could the Angular client replace our Qt interface?

@AdamISZ

AdamISZ commented Aug 22, 2020

Copy link
Copy Markdown
Member Author

I played around with this a little. I can successfully load a wallet generated both manually, and one created by ygrunner.py. Maybe this is to be expected, but if I want to load a different wallet after loading the first one, I have to completely shutdown jmwalletd.py.

Yeah, this is like level 0; as noted above, there is no state management and no access control in this yet. In fact I feel like this will be the most important thing to get right if we go forward with it. We can go with cookie file based authentication, a bit like in the Bitcoin Core RPC, I think that's fine, but the tricky thing will be to have this daemon manage access to specific wallets (possibly in parallel? but let's be less ambitious to start with), including state (is the wallet unlocked) and including possibly some granularity (read only access, signing access, etc).

Question: could the Angular client replace our Qt interface?

Yes I think it would make sense to go down that road, but to get "one-click" like currently the Windows exe has, we'll also need to somehow package at least the python jmwalletd and all its dependencies. Not to mention of course actually writing the Angular (or similar) app. So that's a long way off.

@AdamISZ

AdamISZ commented Oct 12, 2020

Copy link
Copy Markdown
Member Author

Rebased on master a663efd

@kristapsk

Copy link
Copy Markdown
Member

Ping @AdamISZ, still needs rebase!

@AdamISZ

AdamISZ commented Mar 10, 2021

Copy link
Copy Markdown
Member Author

Thanks for reminder; as you know I was busy but I will do it now.

@AdamISZ

AdamISZ commented Mar 10, 2021

Copy link
Copy Markdown
Member Author

Rebased on master as of b438b71 but a couple of points to note:

  • due to constraints of time, I have not yet tested whether the rebase broke anything. If anyone else tests it first and finds an issue, obviously drop the info here.
  • there is one more commit with a 'direct send/payment' RPC made available; obviously this is the next feature to add, but I don't think I got to the point of adding it to the javascript app in jmcontrolcenter, so it may not be actually complete or functional, yet.

Comment thread jmclient/jmclient/client_protocol.py Resolved
Comment thread jmclient/jmclient/client_protocol.py Resolved
@AdamISZ

AdamISZ commented Mar 11, 2021

Copy link
Copy Markdown
Member Author

Thanks. I think there is also an error in that extra commit. I'll come back to this shortly, sorry for delay.

Comment thread scripts/jmwalletd.py Resolved
@tzawlxih

tzawlxih commented Mar 12, 2021 •

Copy link
Copy Markdown

I'm not able to run it, get errors from get_POST_body it is not able to serialize any response.

Tested on python 3.9 and 3.6

User data location: /home/user/.local/src/joinmarket/scripts/jmdata/
2021-03-12 21:47:38,438 [DEBUG]  rpc: getblockchaininfo []
2021-03-12 21:47:39,687 [INFO]  Starting jmwalletd on port: 28183
2021-03-12 21:47:39,757 [INFO]  Listening on port 27183
<Request at 0x7f4c576008b0 method=POST uri=/wallet/wallet.jmdat/unlock?password=testpass&walletname=testname&wallettype=sw clientproto=HTTP/1.1>
b'POST'
b'/wallet/wallet.jmdat/unlock?password=testpass&walletname=testname&wallettype=sw'
{b'password': [b'testpass'], b'walletname': [b'testname'], b'wallettype': [b'sw']}
b'/wallet/wallet.jmdat/unlock'
<_io.BytesIO object at 0x7f4c57605770>
[(b'Host', [b'localhost:28183']), (b'User-Agent', [b'insomnia/2021.1.0']), (b'Accept', [b'*/*']), (b'Content-Length', [b'0'])]

Traceback (most recent call last):
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/twisted/web/server.py", line 302, in render
    body = resrc.render(self)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/klein/_resource.py", line 204, in render
    d = defer.maybeDeferred(_execute)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/twisted/internet/defer.py", line 151, in maybeDeferred
    result = f(*args, **kw)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/klein/_resource.py", line 196, in _execute
    d = defer.maybeDeferred(
--- <exception caught here> ---
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/twisted/internet/defer.py", line 151, in maybeDeferred
    result = f(*args, **kw)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/klein/_app.py", line 129, in execute_endpoint
    return endpoint_f(self._instance, *args, **kwargs)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/klein/_app.py", line 241, in _f
    return _call(instance, f, request, *a, **kw)
  File "/home/user/.local/src/joinmarket-clientserver/jmvenv/lib/python3.9/site-packages/klein/_app.py", line 60, in _call
    result = __klein_f__(*args, **kwargs)
  File "/home/user/.local/src/joinmarket-clientserver/scripts/jmwalletd.py", line 365, in unlockwallet
    auth_json = self.get_POST_body(request, ["password"])
  File "/home/user/.local/src/joinmarket-clientserver/scripts/jmwalletd.py", line 294, in get_POST_body
    json_data = json.loads(request.content.read().decode("utf-8"))
  File "/usr/lib/python3.9/json/__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.9/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.9/json/decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

@AdamISZ

AdamISZ commented Mar 13, 2021 •

Copy link
Copy Markdown
Member Author

After the fixes in 5b0bf4a , test suite is passing. Will now try to reproduce json decoding failure raised by @tzawlxih .

@AdamISZ

AdamISZ commented Mar 13, 2021 •

Copy link
Copy Markdown
Member Author

@tzawlxih so it appears from your traceback that you attempted to pass the password as a parameter in the url, but it should have been passed in the body of the POST request. See my Angular client code as an example (iirc it interprets {password} as json in the form: {"password": value-of-var-password} .. if that's confusing look at e.g. the POST request for startMakerService just below it) :

https://github.com/JoinMarket-Org/jmcontrolcenter/blob/de33e691e7d27a6ab910f0402b69e047a9eab0e8/src/app/wallet.service.ts#L45-L51

@AdamISZ

AdamISZ commented Mar 13, 2021

Copy link
Copy Markdown
Member Author

I guess the natural follow-on comment is, even at this experimental stage, I should write a documentation of this RPC. Unfortunately I don't think I have the tooling to auto-generate it right now, but not too big of a deal, it should be fairly small.

@AdamISZ

AdamISZ commented Mar 13, 2021

Copy link
Copy Markdown
Member Author

A couple of comments to record from the brief meeting last week. There was some general agreement that:

  • First requirement is to get a better handle on session management
  • Perhaps the next issue to address is having a subscription model for live updates w.r.t. bitcoin transactions; this might be addressed with websockets
  • services to be included are those already present: wallet service (to which a direct-send (non coinjoin spend) function is to be added; payjoin service may fold-in automatically), maker service, snicker service, but also not yet: orderbook service, taker service for initiating coinjoins.

To that list, as per above comment, should be added: RPC documentation.

@AdamISZ

AdamISZ commented Mar 13, 2021

Copy link
Copy Markdown
Member Author

So 8e4bf80 adds documentation of the RPC methods. It is definitely an incomplete document, but it should give enough information in order to be able to run successfully, using the existing methods (apart from the direct-send which is not yet in a complete state I think).

@AdamISZ

AdamISZ commented Mar 14, 2021

Copy link
Copy Markdown
Member Author

Rebased on master as of c0491eb

@raulcano

raulcano commented Mar 14, 2021 •

Copy link
Copy Markdown

A couple of comments to record from the brief meeting last week. There was some general agreement that:

* First requirement is to get a better handle on session management

* Perhaps the next issue to address is having a subscription model for live updates w.r.t. bitcoin transactions; this _might_ be addressed with websockets

* services to be included are those already present: wallet service (to which a direct-send (non coinjoin spend) function is to be added; payjoin service may fold-in automatically), maker service, snicker service, but also not yet: orderbook service, taker service for initiating coinjoins.

To that list, as per above comment, should be added: RPC documentation.

Hi, I've been checking on possible ways to go ahead with the next steps (session mgmt. , websockets) and I was wondering if it would make sense to use a Django based infrastructure that would wrap all of that more or less alright, in addition with the basics already covered (i.e. secure connection , endpoints exposed).
In this preliminary research I was considering this as a potential good solution including all our reqs. and that would escalate nicely (e.g. if we wanted to add user management and other features in the future). Of course, this would require rewriting the whole API, so that doesn't sounds very attractive.

Any thoughts?

Ps. About session management, where you thinking in adding a user table for user control? That means we could do a basic user authentication and authorization on what wallets that user is allowed to access. Not sure we want that extra layer since any user providing the correct unlock password is already proof of the user being authorised.


Django SSL/TLs
https://docs.djangoproject.com/en/dev/topics/security/#ssl-https

Django REST api
https://www.django-rest-framework.org/

Django session management
Some authentication flow
https://briancaffey.github.io/2020/11/27/how-to-authenticate-django-rest-framework-from-vue-app-with-session-authentication-httponly-cookies/#the-authentication-flow

https://www.django-rest-framework.org/tutorial/4-authentication-and-permissions/#authenticating-with-the-api
https://www.django-rest-framework.org/api-guide/authentication/#sessionauthentication
https://docs.djangoproject.com/en/3.1/topics/http/sessions/

Django websockets
https://jaydenwindle.com/writing/django-websockets-zero-dependencies/
https://www.untangled.dev/2020/08/02/django-websockets-minimal-setup/

kristapsk
kristapsk previously approved these changes Mar 15, 2021
@kristapsk
kristapsk dismissed their stale review March 15, 2021 21:33

Didn't want to ACK whole PR, needs more review / work, it was mistake.

@AdamISZ

AdamISZ commented Mar 19, 2021

Copy link
Copy Markdown
Member Author

@raulcano i'm sorry that i didn't answer this a few days ago, it slipped my mind with other things happening.

So, django is an option I certainly thought about, but I didn't quite get to the point of figuring out how I could get it working properly with twisted. My guess is it's possible but it might be a little tricky, and it's hard to find documentation on this. If you could somehow replace the existing instance of Klein() with a server providing GET and POST events from django, which also added inbuilt authentication features, then I agree that would be great.
I'm sure you're right that websockets in django will be a well understood thing, but again it may be tricky with twisted. I had some fragments of code earlier when I looked into this, I'll see if i can find them.

Ps. About session management, where you thinking in adding a user table for user control? That means we could do a basic user authentication and authorization on what wallets that user is allowed to access. Not sure we want that extra layer since any user providing the correct unlock password is already proof of the user being authorised.

I mean, maybe, but for now just assume we are dealing with a single user accessing one wallet at a time, just because it's easier and it's unlikely we'll really need to address a more complex use case than that.

Sorry I haven't read your links yet, but I will get round to it soon.

@AdamISZ

AdamISZ commented Mar 19, 2021

Copy link
Copy Markdown
Member Author

Re: fragment mentioned above, it was this (from several months ago; I don't remember too much). To emphasize, I don't know if this works, so it may be useless, but: it was a result of me finding that autobahn was something that supported websockets in twisted, possibly. So with caveats, here:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory


class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")
        t = task.LoopingCall(self.sendDummyMessage)
        t.start(5.0)

    def onMessage(self, payload, isBinary):
        if isBinary:
            print("Binary message received: {} bytes".format(len(payload)))
        else:
            print("Text message received: {}".format(payload.decode('utf8')))

        # echo back message verbatim
        self.sendMessage(payload, isBinary)

    def sendDummyMessage(self):
        print('sending dummy message')
        self.sendMessage(b"this is a dummy message")

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {}".format(reason))


# allow websocket connections
websocketfactory = WebSocketServerFactory()
websocketfactory.protocol = MyServerProtocol
reactor.listenTCP(9001, websocketfactory)

@raulcano

raulcano commented Mar 19, 2021 •

Copy link
Copy Markdown

@AdamISZ Thanks for the answer. I have put on hold the idea of Django last days, to look for other more lightweight solutions.
For the moment, one of my initial findings is that Klein does not support session management, and while we all know the concept and could implement that manually, I think it's a best practice to use some battle-tested framework.

The discussion here sums it up pretty well:
image

It seems that Flask could be an option. It is lightweight and has session management features and the option to work with websockets. https://www.tutorialspoint.com/flask/flask_quick_guide.htm
I still need to check how this could work with twisted (there seems to be a way)

In parallel to looking into this I'll keep searching if there's a good alternative to keep Klein with sessions and so on.
In the end, given the use case (not intended for massive use, just the owner of the server accessing the api plus maybe some other users) maybe it won't be too risky to implement the session management by ourselves.

@AdamISZ

AdamISZ commented Mar 19, 2021

Copy link
Copy Markdown
Member Author

@raulcano yes, good. I do remember seeing Flask and thinking it may be a sensible option here. Although my memory isn't clear, it may well be that I went with Klein just because it was the simplest to set up, but if Flask can offer us some kind of authentication framework then hopefully it will be a good idea. Your stackoverflow link at least suggests we might be able to drop-in replace it here.

@raulcano

Copy link
Copy Markdown

I'll get familiar with flask these days and try to see if I get somewhere. Will report back.

AdamISZ added 11 commits July 20, 2021 16:39
Uses Klein to provide HTTP server support.
This commit adds a basic authorization method to all
requests using a cookie stored by the client (so similar
to what is done by Bitcoin RPC). This cookie is sent
in a custom header 'JMCookie'.
Additionally, preflight CORS requests are handled for all
routes generically.
Also more comments are added to the current main functions.
Also a /lock route is added to allow the user to shut down
the wallet service and close the wallet.
Still very rudimentary of course.
This commit adds a JMShutdown command to
the AMP protocol, allowing a clean shutdown
of a long running bot (e.g. maker) by shutting
down its message channel connections.
The yield generator is now made a Service.
Access the port that was chosen (to avoid conflicting
with other simultaneously running jmdaemon instances,
especially in test scenarios) in the jmwalletd startup,
and use that in starting the YieldGenerator service.
Also fixes a bug in YieldGenerator service startup -
self.yieldgen not maker.
@AdamISZ AdamISZ mentioned this pull request Aug 9, 2021
@AdamISZ

AdamISZ commented Sep 4, 2021

Copy link
Copy Markdown
Member Author

Closing, at least for the time being, in favour of #996 .

@AdamISZ AdamISZ closed this Sep 4, 2021
@AdamISZ
AdamISZ deleted the rpc-api-1 branch November 30, 2021 16:37
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants