forked from hyperledger/indy-node
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathagent.py
214 lines (174 loc) · 6.5 KB
/
agent.py
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import asyncio
import os
from typing import Tuple
from plenum.common.motor import Motor
from plenum.common.signer_did import DidSigner
from plenum.common.signer_simple import SimpleSigner
from plenum.common.startable import Status
from plenum.common.types import HA
from plenum.common.util import randomString
from sovrin_client.agent.agent_net import AgentNet
from sovrin_client.client.client import Client
from sovrin_client.client.wallet.wallet import Wallet
from sovrin_common.config import agentLoggingLevel
from sovrin_common.config_util import getConfig
from sovrin_common.identity import Identity
from sovrin_common.strict_types import strict_types, decClassMethods
from stp_core.common.log import getlogger
from stp_core.network.port_dispenser import genHa
from stp_core.network.util import checkPortAvailable
from stp_core.types import Identifier
logger = getlogger()
logger.setLevel(agentLoggingLevel)
@decClassMethods(strict_types())
class Agent(Motor, AgentNet):
def __init__(self,
name: str=None,
basedirpath: str=None,
client: Client=None,
port: int=None,
loop=None,
config=None,
endpointArgs=None):
self.endpoint = None
if port:
checkPortAvailable(HA("0.0.0.0", port))
Motor.__init__(self)
self.loop = loop or asyncio.get_event_loop()
self._eventListeners = {} # Dict[str, set(Callable)]
self._name = name or 'Agent'
self._port = port
self.config = config or getConfig()
self.basedirpath = basedirpath or os.path.expanduser(
self.config.baseDir)
self.endpointArgs = endpointArgs
# Client used to connect to Sovrin and forward on owner's txns
self._client = client # type: Client
# known identifiers of this agent's owner
self.ownerIdentifiers = {} # type: Dict[Identifier, Identity]
self.logger = logger
@property
def client(self):
return self._client
@client.setter
def client(self, client):
self._client = client
@property
def name(self):
return self._name
@property
def port(self):
return self._port
async def prod(self, limit) -> int:
c = 0
if self.get_status() == Status.starting:
self.status = Status.started
c += 1
if self.client:
c += await self.client.prod(limit)
if self.endpoint:
c += await self.endpoint.service(limit)
return c
def start(self, loop):
AgentNet.__init__(self,
name=self._name.replace(" ", ""),
port=self._port,
basedirpath=self.basedirpath,
msgHandler=self.handleEndpointMessage,
config=self.config,
endpoint_args=self.endpointArgs)
super().start(loop)
if self.client:
self.client.start(loop)
if self.endpoint:
self.endpoint.start()
def stop(self, *args, **kwargs):
super().stop(*args, **kwargs)
if self.client:
self.client.stop()
if self.endpoint:
self.endpoint.stop()
def _statusChanged(self, old, new):
pass
def onStopping(self, *args, **kwargs):
pass
def connect(self, network: str):
"""
Uses the client to connect to Sovrin
:param network: (test|live)
:return:
"""
raise NotImplementedError
def syncKeys(self):
"""
Iterates through ownerIdentifiers and ensures the keys are correct
according to Sovrin. Updates the updated
:return:
"""
raise NotImplementedError
def handleOwnerRequest(self, request):
"""
Consumes an owner request, verifies it's authentic (by checking against
synced owner identifiers' keys), and handles it.
:param request:
:return:
"""
raise NotImplementedError
def handleEndpointMessage(self, msg):
raise NotImplementedError
def ensureConnectedToDest(self, name, ha, clbk, *args):
if self.endpoint.isConnectedTo(name=name, ha=ha):
if clbk:
clbk(*args)
else:
self.loop.call_later(.2, self.ensureConnectedToDest,
name, ha, clbk, *args)
def sendMessage(self, msg, name: str = None, ha: Tuple = None):
def _send(msg):
nonlocal name, ha
self.endpoint.send(msg, name, ha)
logger.debug("Message sent (to -> {}): {}".format(ha, msg))
# TODO: if we call following isConnectedTo method by ha,
# there was a case it found more than one remote, so for now,
# I have changed it to call by remote name (which I am not sure
# fixes the issue), need to come back to this.
if not self.endpoint.isConnectedTo(name=name, ha=ha):
self.ensureConnectedToDest(name, ha, _send, msg)
else:
_send(msg)
def registerEventListener(self, eventName, listener):
cur = self._eventListeners.get(eventName)
if cur:
self._eventListeners[eventName] = cur.add(listener)
else:
self._eventListeners[eventName] = {listener}
def deregisterEventListener(self, eventName, listener):
cur = self._eventListeners.get(eventName)
if cur:
self._eventListeners[eventName] = cur - set(listener)
def createAgent(agentClass, name, wallet=None, basedirpath=None, port=None,
loop=None, clientClass=Client):
config = getConfig()
if not wallet:
wallet = Wallet(name)
wallet.addIdentifier(signer=DidSigner(
seed=randomString(32).encode('utf-8')))
if not basedirpath:
basedirpath = config.baseDir
if not port:
_, port = genHa()
client = create_client(base_dir_path=basedirpath, client_class=clientClass)
return agentClass(basedirpath=basedirpath,
client=client,
wallet=wallet,
port=port,
loop=loop)
def create_client(base_dir_path=None, client_class=Client):
config = getConfig()
if not base_dir_path:
base_dir_path = config.baseDir
_, clientPort = genHa()
client = client_class(randomString(6),
ha=("0.0.0.0", clientPort),
basedirpath=base_dir_path)
return client