-
Notifications
You must be signed in to change notification settings - Fork 516
/
wallet_setup.py
233 lines (197 loc) · 8.29 KB
/
wallet_setup.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
"""Indy-SDK wallet setup and configuration."""
import json
import logging
from typing import Any, Mapping
import indy.anoncreds
import indy.did
import indy.crypto
import indy.wallet
from indy.error import IndyError, ErrorCode
from ...core.error import ProfileError, ProfileDuplicateError, ProfileNotFoundError
from ...core.profile import Profile
from .error import IndyErrorHandler
from .wallet_plugin import load_postgres_plugin
LOGGER = logging.getLogger(__name__)
class IndyWalletConfig:
"""A helper class for handling Indy-SDK wallet configuration."""
DEFAULT_FRESHNESS = False
DEFAULT_KEY = ""
DEFAULT_KEY_DERIVATION = "ARGON2I_MOD"
DEFAULT_STORAGE_TYPE = None
KEY_DERIVATION_RAW = "RAW"
KEY_DERIVATION_ARGON2I_INT = "ARGON2I_INT"
KEY_DERIVATION_ARGON2I_MOD = "ARGON2I_MOD"
def __init__(self, config: Mapping[str, Any] = None):
"""Initialize an `IndySdkWalletConfig` instance.
Args:
config: {name, key, seed, did, auto_recreate, auto_remove,
storage_type, storage_config, storage_creds}
"""
config = config or {}
self.auto_recreate = config.get("auto_recreate", False)
self.auto_remove = config.get("auto_remove", False)
self.freshness_time = config.get("freshness_time", self.DEFAULT_FRESHNESS)
self.key = config.get("key", self.DEFAULT_KEY)
self.key_derivation_method = (
config.get("key_derivation_method") or self.DEFAULT_KEY_DERIVATION
)
# self.rekey = config.get("rekey")
# self.rekey_derivation_method = config.get("rekey_derivation_method")
self.name = config.get("name") or Profile.DEFAULT_NAME
self.storage_type = config.get("storage_type") or self.DEFAULT_STORAGE_TYPE
self.storage_config = config.get("storage_config", None)
self.storage_creds = config.get("storage_creds", None)
if self.storage_type == "postgres_storage":
load_postgres_plugin(self.storage_config, self.storage_creds)
@property
def wallet_config(self) -> dict:
"""Accessor for the Indy wallet config."""
ret = {
"id": self.name,
"freshness_time": self.freshness_time,
"storage_type": self.storage_type,
}
if self.storage_config is not None:
ret["storage_config"] = json.loads(self.storage_config)
return ret
@property
def wallet_access(self) -> dict:
"""Accessor the Indy wallet access info."""
ret = {"key": self.key, "key_derivation_method": self.key_derivation_method}
# if self.rekey:
# ret["rekey"] = self.rekey
# if self.rekey_derivation_method:
# ret["rekey_derivation_method"] = self.rekey_derivation_method
if self.storage_creds is not None:
ret["storage_credentials"] = json.loads(self.storage_creds)
return ret
async def create_wallet(self) -> "IndyOpenWallet":
"""Create a new wallet.
Raises:
ProfileDuplicateError: If there was an existing wallet with the same name
ProfileError: If there was a problem removing the wallet
ProfileError: If there was another libindy error
"""
if self.auto_recreate:
try:
await self.remove_wallet()
except ProfileNotFoundError:
pass
try:
await indy.wallet.create_wallet(
config=json.dumps(self.wallet_config),
credentials=json.dumps(self.wallet_access),
)
except IndyError as x_indy:
if x_indy.error_code == ErrorCode.WalletAlreadyExistsError:
raise IndyErrorHandler.wrap_error(
x_indy,
f"Cannot create wallet '{self.name}', already exists",
ProfileDuplicateError,
) from x_indy
raise IndyErrorHandler.wrap_error(
x_indy,
f"Error creating wallet '{self.name}'",
ProfileError,
) from x_indy
try:
return await self.open_wallet(created=True)
except ProfileNotFoundError as err:
raise ProfileError(
f"Wallet '{self.name}' not found after creation"
) from err
async def remove_wallet(self):
"""Remove an existing wallet.
Raises:
ProfileNotFoundError: If the wallet could not be found
ProfileError: If there was another libindy error
"""
try:
await indy.wallet.delete_wallet(
config=json.dumps(self.wallet_config),
credentials=json.dumps(self.wallet_access),
)
except IndyError as x_indy:
if x_indy.error_code == ErrorCode.WalletNotFoundError:
raise IndyErrorHandler.wrap_error(
x_indy,
f"Wallet '{self.name}' not found",
ProfileNotFoundError,
) from x_indy
raise IndyErrorHandler.wrap_error(
x_indy, f"Error removing wallet '{self.name}'", ProfileError
) from x_indy
async def open_wallet(self, created: bool = False) -> "IndyOpenWallet":
"""Open wallet, removing and/or creating it if so configured.
Raises:
ProfileError: If wallet not found after creation
ProfileNotFoundError: If the wallet is not found
ProfileError: If the wallet is already open
ProfileError: If there is another libindy error
"""
handle = None
while True:
try:
handle = await indy.wallet.open_wallet(
config=json.dumps(self.wallet_config),
credentials=json.dumps(self.wallet_access),
)
# if self.rekey:
# self.key = self.rekey
# self.rekey = None
# if self.rekey_derivation_method:
# self.key_derivation_method = self.rekey_derivation_method
# self.rekey_derivation_method = None
break
except IndyError as x_indy:
if x_indy.error_code == ErrorCode.WalletNotFoundError:
raise IndyErrorHandler.wrap_error(
x_indy, f"Wallet '{self.name}' not found", ProfileNotFoundError
) from x_indy
elif x_indy.error_code == ErrorCode.WalletAlreadyOpenedError:
raise IndyErrorHandler.wrap_error(
x_indy, f"Wallet '{self.name}' is already open", ProfileError
) from x_indy
else:
raise IndyErrorHandler.wrap_error(
x_indy, f"Error opening wallet '{self.name}'", ProfileError
) from x_indy
LOGGER.info("Creating master secret...")
try:
master_secret_id = await indy.anoncreds.prover_create_master_secret(
handle, self.name
)
except IndyError as x_indy:
if x_indy.error_code == ErrorCode.AnoncredsMasterSecretDuplicateNameError:
LOGGER.info("Master secret already exists")
master_secret_id = self.name
else:
raise IndyErrorHandler.wrap_error(
x_indy, f"Wallet '{self.name}' error", ProfileError
) from x_indy
return IndyOpenWallet(self, created, handle, master_secret_id)
class IndyOpenWallet:
"""Handle and metadata for an opened Indy wallet."""
def __init__(
self,
config: IndyWalletConfig,
created,
handle,
master_secret_id: str,
):
"""Create a new IndyOpenWallet instance."""
self.config = config
self.created = created
self.handle = handle
self.master_secret_id = master_secret_id
@property
def name(self) -> str:
"""Accessor for the opened wallet name."""
return self.config.name
async def close(self):
"""Close previously-opened wallet, removing it if so configured."""
if self.handle:
await indy.wallet.close_wallet(self.handle)
self.handle = None
if self.config.auto_remove:
await self.config.remove_wallet()