From a16b33031c7bcf2eabf1e0c3571000234b7740df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Roman=20Smr=C5=BE?= Date: Sun, 24 Jan 2021 22:46:48 +0100 Subject: Attach service --- include/erebos/pairing.h | 104 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 104 insertions(+) create mode 100644 include/erebos/pairing.h (limited to 'include/erebos/pairing.h') diff --git a/include/erebos/pairing.h b/include/erebos/pairing.h new file mode 100644 index 0000000..f0952d8 --- /dev/null +++ b/include/erebos/pairing.h @@ -0,0 +1,104 @@ +#pragma once + +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace erebos { + +using std::function; +using std::future; +using std::map; +using std::mutex; +using std::string; +using std::variant; +using std::vector; + +/** + * Template-less base class for the paring functionality that does not depend + * on the result parameter. + */ +class PairingServiceBase : public Service +{ +public: + typedef function RequestInitHook; + void onRequestInit(RequestInitHook); + + typedef function(const Peer &, string)> ConfirmHook; + void onResponse(ConfirmHook); + void onRequest(ConfirmHook); + + typedef function RequestNonceFailedHook; + void onRequestNonceFailed(RequestNonceFailedHook); + +protected: + void requestPairing(UUID serviceId, const Peer & peer); + virtual void handle(Context &) override; + virtual Ref handlePairingCompleteRef(const Peer &) = 0; + virtual void handlePairingResult(Context &) = 0; + +private: + static vector nonceDigest(const Identity & id1, const Identity & id2, + const vector & nonce1, const vector & nonce2); + static string confirmationNumber(const vector &); + void waitForConfirmation(Peer peer, string confirm); + + RequestInitHook requestInitHook; + ConfirmHook responseHook; + ConfirmHook requestHook; + RequestNonceFailedHook requestNonceFailedHook; + + optional result; + + enum class StatePhase { + NoPairing, + OurRequest, + OurRequestConfirm, + OurRequestReady, + PeerRequest, + PeerRequestConfirm, + PairingDone, + PairingFailed + }; + + struct State { + StatePhase phase; + vector nonce; + vector peerCheck; + }; + + map peerStates; + mutex stateLock; +}; + +template +class PairingService : public PairingServiceBase +{ +protected: + virtual Stored handlePairingComplete(const Peer &) = 0; + virtual void handlePairingResult(Context &, Stored) = 0; + + virtual Ref handlePairingCompleteRef(const Peer &) override final; + virtual void handlePairingResult(Context &) override final; +}; + +template +Ref PairingService::handlePairingCompleteRef(const Peer & peer) +{ + return handlePairingComplete(peer).ref(); +} + +template +void PairingService::handlePairingResult(Context & ctx) +{ + handlePairingResult(ctx, Stored::load(ctx.ref())); +} + +} -- cgit v1.2.3