-
Notifications
You must be signed in to change notification settings - Fork 0
/
accounts.py
451 lines (395 loc) · 17.8 KB
/
accounts.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
import logging
from datetime import datetime
from bigchaindb_driver import BigchainDB
from bigchaindb_driver.crypto import generate_keypair
from prov.model import ProvDocument, ProvElement, ProvAgent
from prov2bigchaindb.core import utils, exceptions, local_stores
log = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
class BaseAccount(object):
"""
BigchainDB Base Account
"""
def __init__(self, account_id: str, store: local_stores.SqliteStore):
"""
Instantiate BaseAccount object
:param account_id: Internal id of Account
:type account_id: str
:param store: Local database object
:type store: local_stores.SqliteStore
"""
assert account_id is not None
assert store is not None
self.store = store
self.account_id = account_id
self.tx_id = ''
self.private_key, self.public_key = generate_keypair()
try:
self.account_id, self.public_key, self.private_key, self.tx_id = self.store.get_account(self.account_id)
log.debug("Found account for %s with public_key %s", self.account_id, self.public_key)
except exceptions.NoAccountFoundException:
self.store.write_account(self.account_id, self.public_key, self.private_key)
log.debug("New account for %s with public_key %s", self.account_id, self.public_key)
def __str__(self):
return "{} : {}".format(self.account_id, self.public_key)
def _create_asset(self, bdb_connection: BigchainDB, asset: dict, metadata: dict = None) -> dict:
"""
Create and transfer new CREATE transaction
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:param asset: Dictonary with asset data
:type asset: dict
:param metadata: Dictonary with additional metadata
:type metadata: dict or None
:return: Result with created CREATE transactions
:rtype: dict
"""
if metadata is None:
metadata = {}
metadata['timestamp'] = datetime.utcnow().timestamp()
prepared_creation_tx = bdb_connection.transactions.prepare(operation='CREATE',
signers=self.public_key,
asset=asset,
metadata=metadata)
fulfilled_creation_tx = bdb_connection.transactions.fulfill(prepared_creation_tx,
private_keys=self.private_key)
sent_creation_tx = bdb_connection.transactions.send(fulfilled_creation_tx)
if fulfilled_creation_tx != sent_creation_tx:
raise exceptions.CreateRecordException()
return sent_creation_tx
def _transfer_asset(self, bdb_connection: BigchainDB, recipient_pub_key: str, tx: dict,
metadata: dict = None) -> dict:
"""
Create and transfer new TRANSFER transaction
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:param recipient_pub_key: Public key of the recipient
:type recipient_pub_key: str
:param tx: Transaction which should be transferd
:type tx: dict
:param metadata: Dictionary with additional metadata
:type metadata: dict or None
:return: Result with created CREATE transactions
:rtype: dict
"""
if metadata is None:
metadata = {}
metadata['timestamp'] = datetime.utcnow().timestamp()
transfer_asset = {'id': tx['id']}
output_index = 0
output = tx['outputs'][output_index]
transfer_input = {
'fulfillment': output['condition']['details'],
'fulfills': {
'output_index': output_index,
'transaction_id': tx['id']
},
'owners_before': output['public_keys']
}
prepared_transfer_tx = bdb_connection.transactions.prepare(
operation='TRANSFER',
asset=transfer_asset,
metadata=metadata,
inputs=transfer_input,
recipients=recipient_pub_key
)
fulfilled_transfer_tx = bdb_connection.transactions.fulfill(
prepared_transfer_tx,
private_keys=self.private_key,
)
sent_transfer_tx = bdb_connection.transactions.send(fulfilled_transfer_tx)
if fulfilled_transfer_tx != sent_transfer_tx:
raise exceptions.CreateRecordException()
return sent_transfer_tx
def get_id(self) -> str:
"""
Get Account id
:return: Internal id of Account
:rtype: str
"""
return self.account_id
def get_public_key(self) -> str:
"""
Get public key
:return: Public key of Account
:rtype: str
"""
return self.public_key
class DocumentConceptAccount(BaseAccount):
"""
BigchainDB Document Concept Account
"""
def __init__(self, account_id: str, store: local_stores.SqliteStore):
"""
Instantiate Document Concept Account object
:param account_id: Internal id of Account
:type account_id: str
:param store: Local database object
:type store: local_stores.SqliteStore
"""
super().__init__(account_id, store)
def save_asset(self, asset: dict, bdb_connection: BigchainDB) -> str:
"""
Write asset to BigchainDB
:param asset: Dictonary with asset data
:type asset: dict
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transaction Id
:rtype: str
"""
asset = {'data': asset}
metadata = {'account_id': self.account_id}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
tx = self._transfer_asset(bdb_connection, self.public_key, tx, metadata)
log.info("Created document: %s - %s", self.account_id, tx['id'])
return tx['id']
class GraphConceptAccount(BaseAccount):
"""
BigchainDB Graph Concept Account
"""
def __init__(self, prov_element: ProvElement, prov_relations: dict, id_mapping: dict, namespaces: list,
store: local_stores.SqliteStore = local_stores.SqliteStore()):
"""
Instantiate Graph Concept Account object
:param prov_element: ProvElement related to account
:type prov_element: ProvElement
:param prov_relations: List including dictionaries of all outgoing ProvRelations
:type prov_relations: list
:param namespaces: List of Prov Namespaces
:type namespaces: list
:param store: Local database object
:type store: local_stores.SqliteStore
"""
assert prov_element is not None
assert prov_relations is not None
assert namespaces is not None
self.prov_element = prov_element
self.prov_namespaces = namespaces
self.prov_relations_with_id = prov_relations['with_id']
self.id_mapping = id_mapping
self.prov_relations_without_id = prov_relations['without_id']
super().__init__(str(prov_element.identifier), store)
def get_tx_id(self) -> str:
"""
Get the tx_id that describes the account in BigchainDB
:return: Transaction id of account
:rtype: str
"""
return self.tx_id
def has_relations_with_id(self) -> bool:
"""
Indicates whether an account has relation with ids or not
:return: True if one or more relation does have ids
:rtype: bool
"""
return len(self.prov_relations_with_id) != 0
def has_relations_without_id(self) -> bool:
"""
Indicates whether an account has relation without ids or not
:return: True if one or more relation does have ids
:rtype: bool
"""
return len(self.prov_relations_without_id) != 0
def __str__(self):
return "{} : {}\n\t{}\n\t{}".format(self.account_id, self.public_key, self.prov_relations_with_id,
self.prov_relations_without_id)
def __create_instance_document(self) -> ProvDocument:
"""
Creates a valid ProvDocument describing an account
:return: Representation of account as ProvDocument
:rtype: ProvDocument
"""
doc = ProvDocument()
for n in self.prov_namespaces:
doc.add_namespace(n.prefix, n.uri)
doc.add_record(self.prov_element)
return doc
def __create_relation(self, relation) -> (ProvDocument, dict):
"""
Returns a ProvDocument and mapping for all relations
:return: Relation as ProvDocument and
:rtype: ( ProvDocument, dict)
"""
doc = ProvDocument()
mapping = {}
for relation_type, relation_attr in relation.formal_attributes:
if relation_attr:
try:
recipient = self.store.get_account(str(relation_attr))
mapping[recipient[0]] = recipient[3]
except exceptions.NoAccountFoundException:
try:
recipient = self.id_mapping.get(str(relation_attr))
mapping[str(relation_attr)] = recipient
except exceptions.NoRelationFoundException:
log.info("Found no tx for %s", relation_attr)
for n in self.prov_namespaces:
doc.add_namespace(n.prefix, n.uri)
doc.add_record(relation)
return doc, mapping
def save_relations_with_ids(self, bdb_connection: BigchainDB) -> list:
"""
Writes all assets with relations (having ids) to BigchainDB
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transactions ids of all relations
:rtype: list
"""
if self.tx_id == '':
raise exceptions.AccountNotCreatedException("Account must be created before transactions")
tx_list = []
for relation in self.prov_relations_with_id:
doc, mapping = self.__create_relation(relation)
for record in doc.get_records():
recipient = self.store.get_account(str(record.args[1]))
asset = {'data': {'prov': doc.serialize(format='json'), 'map': mapping}}
metadata = {'relation': '->'.join([self.account_id, recipient[0]])}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
metadata = {'relation': '->'.join([self.account_id, recipient[0]])}
tx = self._transfer_asset(bdb_connection, recipient[1], tx, metadata)
tx_list.append(tx['id'])
self.id_mapping[str(record.identifier)] = tx['id']
log.debug("Created relation %s: %s -> %s - %s", record.identifier, self.account_id, recipient[0],
tx['id'])
return tx_list
def save_relations_without_ids(self, bdb_connection: BigchainDB) -> list:
"""
Write all assets with relations to BigchainDB
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transactions ids of all relations
:rtype: list
"""
if self.tx_id == '':
raise exceptions.AccountNotCreatedException("Account must be created before transactions")
tx_list = []
for relation in self.prov_relations_without_id:
doc, mapping = self.__create_relation(relation)
for records in doc.get_records():
recipient = self.store.get_account(str(records.args[1]))
asset = {'data': {'prov': doc.serialize(format='json'), 'map': mapping}}
metadata = {'relation': '->'.join([self.account_id, recipient[0]])}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
metadata = {'relation': '->'.join([self.account_id, recipient[0]])}
tx = self._transfer_asset(bdb_connection, recipient[1], tx, metadata)
tx_list.append(tx['id'])
log.debug("Created relation: %s -> %s - %s", self.account_id, recipient[0], tx['id'])
return tx_list
def save_instance_asset(self, bdb_connection: BigchainDB) -> str:
"""
Write provenance describing the account to BigchainDB
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transactions id of instance
:rtype: str
"""
if self.tx_id == '':
prov_document = self.__create_instance_document()
asset = {'data': {'prov': prov_document.serialize(format='json')}}
metadata = {'instance': self.account_id}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
tx = self._transfer_asset(bdb_connection, self.public_key, tx, metadata)
self.store.write_tx_id(self.account_id, tx['id'])
self.tx_id = tx['id']
log.debug("Created instance: %s - %s", self.account_id, tx['id'])
return self.tx_id
class RoleConceptAccount(BaseAccount):
"""
BigchainDB Graph Concept Account
"""
def __init__(self, agent: ProvAgent, relations: list, elements: dict, id_mapping: dict, namespaces: list,
store: local_stores.SqliteStore = local_stores.SqliteStore()):
"""
Instantiate Graph Concept Account object
:param agent: ProvAgent related to account
:type agent: ProvAgent
:param namespaces: List of Prov Namespaces
:type namespaces: list
:param store: Local database object
:type store: local_stores.SqliteStore
"""
assert agent is not None
assert elements is not None
assert namespaces is not None
self.prov_agent = agent
self.prov_agent_relations = relations
self.prov_namespaces = namespaces
self.prov_elements = elements
self.id_mapping = id_mapping
super().__init__(str(agent.identifier), store)
def get_tx_id(self) -> str:
"""
Get the tx_id that describes the account in BigchainDB
:return: Transaction id of account
:rtype: str
"""
return self.tx_id
def __str__(self):
return "{} : {}\n\t{}\n\t{}".format(self.account_id, self.public_key,
self.prov_agent_relations, self.prov_elements)
def __create_document(self, element, relations) -> tuple:
"""
Returns a ProvDocument and mapping for all relations
:return: Relation as ProvDocument and
:rtype: (ProvDocument, map)
"""
doc = ProvDocument()
doc.add_record(element)
mapping = {}
for relation in relations:
for n in self.prov_namespaces:
doc.add_namespace(n.prefix, n.uri)
doc.add_record(relation)
return doc, mapping
def save_elements(self, bdb_connection: BigchainDB) -> list:
"""
Writes all elements with assets to BigchainDB
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transactions ids of all relations
:rtype: list
"""
if self.tx_id == '':
raise exceptions.AccountNotCreatedException("Account must be created before transactions")
tx_list = []
for ordered_element in self.prov_elements.values():
for element, relations in ordered_element.items():
doc, mapping = self.__create_document(element, relations)
asset = {'data': {'prov': doc.serialize(format='json'), 'map': mapping}}
metadata = {'instance': self.account_id}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
tx = self._transfer_asset(bdb_connection, self.public_key, tx, metadata)
self.store.write_account(str(element.identifier), '', '', tx['id'])
tx_list.append(tx['id'])
# for id, tx_id in mapping.items():
# if not tx_id:
# self.id_mapping[id] = tx['id']
# self.id_mapping[str(element.identifier)] = tx['id']
log.debug("Created element %s related to %s - %s", element.identifier, self.account_id, tx['id'])
return tx_list
def save_instance_asset(self, bdb_connection: BigchainDB) -> str:
"""
Write provenance describing the account to BigchainDB
:param bdb_connection: Connection object for BigchainDB
:type bdb_connection: BigchainDB
:return: Transactions id of instance
:rtype: str
"""
if self.tx_id == '':
prov_document, mapping = self.__create_document(self.prov_agent, self.prov_agent_relations)
asset = {'data': {'prov': prov_document.serialize(format='json'), 'map': mapping}}
metadata = {'instance': self.account_id}
tx = self._create_asset(bdb_connection, asset, metadata)
utils.wait_until_valid(tx['id'], bdb_connection)
tx = self._transfer_asset(bdb_connection, self.public_key, tx, metadata)
self.store.write_tx_id(self.account_id, tx['id'])
self.id_mapping[self.account_id] = tx['id']
self.tx_id = tx['id']
log.debug("Created agent: %s - %s", self.account_id, tx['id'])
return self.tx_id