summaryrefslogtreecommitdiff
path: root/include/erebos/pairing.h
blob: f0952d80015341ad3f50ba95284cac44612ae4b0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#pragma once

#include <erebos/identity.h>
#include <erebos/network.h>
#include <erebos/service.h>

#include <future>
#include <map>
#include <mutex>
#include <string>
#include <variant>
#include <vector>

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<void(const Peer &)> RequestInitHook;
	void onRequestInit(RequestInitHook);

	typedef function<future<bool>(const Peer &, string)> ConfirmHook;
	void onResponse(ConfirmHook);
	void onRequest(ConfirmHook);

	typedef function<void(const Peer &)> 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<uint8_t> nonceDigest(const Identity & id1, const Identity & id2,
			const vector<uint8_t> & nonce1, const vector<uint8_t> & nonce2);
	static string confirmationNumber(const vector<uint8_t> &);
	void waitForConfirmation(Peer peer, string confirm);

	RequestInitHook requestInitHook;
	ConfirmHook responseHook;
	ConfirmHook requestHook;
	RequestNonceFailedHook requestNonceFailedHook;

	optional<Ref> result;

	enum class StatePhase {
		NoPairing,
		OurRequest,
		OurRequestConfirm,
		OurRequestReady,
		PeerRequest,
		PeerRequestConfirm,
		PairingDone,
		PairingFailed
	};

	struct State {
		StatePhase phase;
		vector<uint8_t> nonce;
		vector<uint8_t> peerCheck;
	};

	map<Peer, State> peerStates;
	mutex stateLock;
};

template<class Result>
class PairingService : public PairingServiceBase
{
protected:
	virtual Stored<Result> handlePairingComplete(const Peer &) = 0;
	virtual void handlePairingResult(Context &, Stored<Result>) = 0;

	virtual Ref handlePairingCompleteRef(const Peer &) override final;
	virtual void handlePairingResult(Context &) override final;
};

template<class Result>
Ref PairingService<Result>::handlePairingCompleteRef(const Peer & peer)
{
	return handlePairingComplete(peer).ref();
}

template<class Result>
void PairingService<Result>::handlePairingResult(Context & ctx)
{
	handlePairingResult(ctx, Stored<Result>::load(ctx.ref()));
}

}