forked from openwallet-foundation/acapy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfaber.py
More file actions
252 lines (212 loc) · 8.35 KB
/
Copy pathfaber.py
File metadata and controls
252 lines (212 loc) · 8.35 KB
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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import asyncio
import json
import logging
import os
import random
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # noqa
from runners.support.agent import DemoAgent, default_genesis_txns
from runners.support.utils import (
log_json,
log_msg,
log_status,
log_timer,
prompt,
prompt_loop,
require_indy,
)
LOGGER = logging.getLogger(__name__)
class FaberAgent(DemoAgent):
def __init__(self, http_port: int, admin_port: int, **kwargs):
super().__init__(
"Faber Agent",
http_port,
admin_port,
prefix="Faber",
extra_args=["--auto-accept-invites", "--auto-accept-requests"],
**kwargs,
)
self.connection_id = None
self._connection_ready = asyncio.Future()
self.cred_state = {}
# TODO define a dict to hold credential attributes
# based on credential_definition_id
self.cred_attrs = {}
async def detect_connection(self):
await self._connection_ready
@property
def connection_ready(self):
return self._connection_ready.done() and self._connection_ready.result()
async def handle_connections(self, message):
if message["connection_id"] == self.connection_id:
if message["state"] == "active" and not self._connection_ready.done():
self.log("Connected")
self._connection_ready.set_result(True)
async def handle_credentials(self, message):
state = message["state"]
credential_exchange_id = message["credential_exchange_id"]
prev_state = self.cred_state.get(credential_exchange_id)
if prev_state == state:
return # ignore
self.cred_state[credential_exchange_id] = state
self.log(
"Credential: state =",
state,
", credential_exchange_id =",
credential_exchange_id,
)
if state == "request_received":
log_status("#17 Issue credential to X")
# issue credentials based on the credential_definition_id
cred_attrs = self.cred_attrs[message["credential_definition_id"]]
await self.admin_POST(
f"/credential_exchange/{credential_exchange_id}/issue",
{"credential_values": cred_attrs},
)
async def handle_presentations(self, message):
state = message["state"]
presentation_exchange_id = message["presentation_exchange_id"]
self.log(
"Presentation: state =",
state,
", presentation_exchange_id =",
presentation_exchange_id,
)
if state == "presentation_received":
log_status("#27 Process the proof provided by X")
log_status("#28 Check if proof is valid")
proof = await self.admin_POST(
f"/presentation_exchange/{presentation_exchange_id}/verify_presentation"
)
self.log("Proof =", proof["verified"])
async def handle_basicmessages(self, message):
self.log("Received message:", message["content"])
async def main(start_port: int, show_timing: bool = False):
genesis = await default_genesis_txns()
if not genesis:
print("Error retrieving ledger genesis transactions")
sys.exit(1)
agent = None
try:
log_status("#1 Provision an agent and wallet, get back configuration details")
agent = FaberAgent(
start_port, start_port + 1, genesis_data=genesis, timing=show_timing
)
await agent.listen_webhooks(start_port + 2)
await agent.register_did()
with log_timer("Startup duration:"):
await agent.start_process()
log_msg("Admin url is at:", agent.admin_url)
log_msg("Endpoint url is at:", agent.endpoint)
# Create a schema
with log_timer("Publish schema/cred def duration:"):
log_status("#3/4 Create a new schema/cred def on the ledger")
version = format(
"%d.%d.%d"
% (
random.randint(1, 101),
random.randint(1, 101),
random.randint(1, 101),
)
)
(
schema_id,
credential_definition_id,
) = await agent.register_schema_and_creddef(
"degree schema", version, ["name", "date", "degree", "age"]
)
# TODO add an additional credential for Student ID
with log_timer("Generate invitation duration:"):
# Generate an invitation
log_status(
"#5 Create a connection to alice and print out the invite details"
)
connection = await agent.admin_POST("/connections/create-invitation")
agent.connection_id = connection["connection_id"]
log_json(connection, label="Invitation response:")
log_msg("*****************")
log_msg(json.dumps(connection["invitation"]), label="Invitation:", color=None)
log_msg("*****************")
log_msg("Waiting for connection...")
await agent.detect_connection()
async for option in prompt_loop(
"(1) Issue Credential, (2) Send Proof Request, "
+ "(3) Send Message (X) Exit? [1/2/3/X] "
):
if option is None or option in "xX":
break
elif option == "1":
log_status("#13 Issue credential offer to X")
offer = {
"credential_definition_id": credential_definition_id,
"connection_id": agent.connection_id,
}
# TODO define attributes to send for credential
agent.cred_attrs[credential_definition_id] = {
"name": "Alice Smith",
"date": "2018-05-28",
"degree": "Maths",
"age": "24",
}
await agent.admin_POST("/credential_exchange/send-offer", offer)
# TODO issue an additional credential for Student ID
elif option == "2":
log_status("#20 Request proof of degree from alice")
proof_attrs = [
{"name": "name", "restrictions": [{"issuer_did": agent.did}]},
{"name": "date", "restrictions": [{"issuer_did": agent.did}]},
{"name": "degree", "restrictions": [{"issuer_did": agent.did}]},
{"name": "self_attested_thing"},
]
proof_predicates = [{"name": "age", "p_type": ">=", "p_value": 18}]
proof_request = {
"name": "Proof of Education",
"version": "1.0",
"connection_id": agent.connection_id,
"requested_attributes": proof_attrs,
"requested_predicates": proof_predicates,
}
await agent.admin_POST(
"/presentation_exchange/send_request", proof_request
)
elif option == "3":
msg = await prompt("Enter message: ")
await agent.admin_POST(
f"/connections/{agent.connection_id}/send-message", {"content": msg}
)
if show_timing:
timing = await agent.fetch_timing()
if timing:
for line in agent.format_timing(timing):
log_msg(line)
finally:
terminated = True
try:
if agent:
await agent.terminate()
except Exception:
LOGGER.exception("Error terminating agent:")
terminated = False
await asyncio.sleep(0.1)
if not terminated:
os._exit(1)
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Runs a Faber demo agent.")
parser.add_argument(
"-p",
"--port",
type=int,
default=8020,
metavar=("<port>"),
help="Choose the starting port number to listen on",
)
parser.add_argument(
"--timing", action="store_true", help="Enable timing information"
)
args = parser.parse_args()
require_indy()
try:
asyncio.get_event_loop().run_until_complete(main(args.port, args.timing))
except KeyboardInterrupt:
os._exit(1)