Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_buyer.py 27KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  1. ###############################################################################
  2. #
  3. # The MIT License (MIT)
  4. #
  5. # Copyright (c) typedef int GmbH
  6. #
  7. # Permission is hereby granted, free of charge, to any person obtaining a copy
  8. # of this software and associated documentation files (the "Software"), to deal
  9. # in the Software without restriction, including without limitation the rights
  10. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. # copies of the Software, and to permit persons to whom the Software is
  12. # furnished to do so, subject to the following conditions:
  13. #
  14. # The above copyright notice and this permission notice shall be included in
  15. # all copies or substantial portions of the Software.
  16. #
  17. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. # THE SOFTWARE.
  24. #
  25. ###############################################################################
  26. import uuid
  27. import binascii
  28. from pprint import pformat
  29. import os
  30. import cbor2
  31. import nacl.secret
  32. import nacl.utils
  33. import nacl.exceptions
  34. import nacl.public
  35. import txaio
  36. from autobahn.wamp.exception import ApplicationError
  37. from autobahn.wamp.protocol import ApplicationSession
  38. from ._util import unpack_uint256, pack_uint256
  39. import eth_keys
  40. from ..util import hl, hlval
  41. from ._eip712_channel_close import sign_eip712_channel_close, recover_eip712_channel_close
  42. class Transaction(object):
  43. def __init__(self, channel, delegate, pubkey, key_id, channel_seq, amount, balance, signature):
  44. self.channel = channel
  45. self.delegate = delegate
  46. self.pubkey = pubkey
  47. self.key_id = key_id
  48. self.channel_seq = channel_seq
  49. self.amount = amount
  50. self.balance = balance
  51. self.signature = signature
  52. def marshal(self):
  53. res = {
  54. 'channel': self.channel,
  55. 'delegate': self.delegate,
  56. 'pubkey': self.pubkey,
  57. 'key_id': self.key_id,
  58. 'channel_seq': self.channel_seq,
  59. 'amount': self.amount,
  60. 'balance': self.balance,
  61. 'signature': self.signature,
  62. }
  63. return res
  64. def __str__(self):
  65. return pformat(self.marshal())
  66. class SimpleBuyer(object):
  67. """
  68. Simple XBR buyer component. This component can be used by a XBR buyer delegate to
  69. handle the automated buying of data encryption keys from the XBR market maker.
  70. """
  71. log = None
  72. def __init__(self, market_maker_adr, buyer_key, max_price):
  73. """
  74. :param market_maker_adr:
  75. :type market_maker_adr:
  76. :param buyer_key: Consumer delegate (buyer) private Ethereum key.
  77. :type buyer_key: bytes
  78. :param max_price: Maximum price we are willing to buy per key.
  79. :type max_price: int
  80. """
  81. assert type(market_maker_adr) == bytes and len(market_maker_adr) == 20, 'market_maker_adr must be bytes[20], but got "{}"'.format(market_maker_adr)
  82. assert type(buyer_key) == bytes and len(buyer_key) == 32, 'buyer delegate must be bytes[32], but got "{}"'.format(buyer_key)
  83. assert type(max_price) == int and max_price > 0
  84. self.log = txaio.make_logger()
  85. # market maker address
  86. self._market_maker_adr = market_maker_adr
  87. self._xbrmm_config = None
  88. # buyer delegate raw ethereum private key (32 bytes)
  89. self._pkey_raw = buyer_key
  90. # buyer delegate ethereum private key object
  91. self._pkey = eth_keys.keys.PrivateKey(buyer_key)
  92. # buyer delegate ethereum private account from raw private key
  93. # FIXME
  94. # self._acct = Account.privateKeyToAccount(self._pkey)
  95. self._acct = None
  96. # buyer delegate ethereum account canonical address
  97. self._addr = self._pkey.public_key.to_canonical_address()
  98. # buyer delegate ethereum account canonical checksummed address
  99. # FIXME
  100. # self._caddr = web3.Web3.toChecksumAddress(self._addr)
  101. self._caddr = None
  102. # ephemeral data consumer key
  103. self._receive_key = nacl.public.PrivateKey.generate()
  104. # maximum price per key we are willing to pay
  105. self._max_price = max_price
  106. # will be filled with on-chain payment channel contract, once started
  107. self._channel = None
  108. # channel current (off-chain) balance
  109. self._balance = 0
  110. # channel sequence number
  111. self._seq = 0
  112. # this holds the keys we bought (map: key_id => nacl.secret.SecretBox)
  113. self._keys = {}
  114. self._session = None
  115. self._running = False
  116. # automatically initiate a close of the payment channel when running into
  117. # a transaction failing because of insufficient balance remaining in the channel
  118. self._auto_close_channel = True
  119. # FIXME: poor mans local transaction store
  120. self._transaction_idx = {}
  121. self._transactions = []
  122. async def start(self, session, consumer_id):
  123. """
  124. Start buying keys to decrypt XBR data by calling ``unwrap()``.
  125. :param session: WAMP session over which to communicate with the XBR market maker.
  126. :type session: :class:`autobahn.wamp.protocol.ApplicationSession`
  127. :param consumer_id: XBR consumer ID.
  128. :type consumer_id: str
  129. :return: Current remaining balance in payment channel.
  130. :rtype: int
  131. """
  132. assert isinstance(session, ApplicationSession)
  133. assert type(consumer_id) == str
  134. assert not self._running
  135. self._session = session
  136. self._running = True
  137. self.log.debug('Start buying from consumer delegate address {address} (public key 0x{public_key}..)',
  138. address=hl(self._caddr),
  139. public_key=binascii.b2a_hex(self._pkey.public_key[:10]).decode())
  140. try:
  141. self._xbrmm_config = await session.call('xbr.marketmaker.get_config')
  142. # get the currently active (if any) payment channel for the delegate
  143. assert type(self._addr) == bytes and len(self._addr) == 20
  144. self._channel = await session.call('xbr.marketmaker.get_active_payment_channel', self._addr)
  145. if not self._channel:
  146. raise Exception('no active payment channel found')
  147. channel_oid = self._channel['channel_oid']
  148. assert type(channel_oid) == bytes and len(channel_oid) == 16
  149. self._channel_oid = uuid.UUID(bytes=channel_oid)
  150. # get the current (off-chain) balance of the payment channel
  151. payment_balance = await session.call('xbr.marketmaker.get_payment_channel_balance', self._channel_oid.bytes)
  152. except:
  153. session.leave()
  154. raise
  155. # FIXME
  156. if type(payment_balance['remaining']) == bytes:
  157. payment_balance['remaining'] = unpack_uint256(payment_balance['remaining'])
  158. if not payment_balance['remaining'] > 0:
  159. raise Exception('no off-chain balance remaining on payment channel')
  160. self._balance = payment_balance['remaining']
  161. self._seq = payment_balance['seq']
  162. self.log.info('Ok, buyer delegate started [active payment channel {channel_oid} with remaining balance {remaining} at sequence {seq}]',
  163. channel_oid=hl(self._channel_oid), remaining=hlval(self._balance), seq=hlval(self._seq))
  164. return self._balance
  165. async def stop(self):
  166. """
  167. Stop buying keys.
  168. """
  169. assert self._running
  170. self._running = False
  171. self.log.info('Ok, buyer delegate stopped.')
  172. async def balance(self):
  173. """
  174. Return current balance of payment channel:
  175. * ``amount``: The initial amount with which the payment channel was opened.
  176. * ``remaining``: The remaining amount of XBR in the payment channel that can be spent.
  177. * ``inflight``: The amount of XBR allocated to buy transactions that are currently processed.
  178. :return: Current payment balance.
  179. :rtype: dict
  180. """
  181. assert self._session and self._session.is_attached()
  182. payment_balance = await self._session.call('xbr.marketmaker.get_payment_channel_balance', self._channel['channel_oid'])
  183. return payment_balance
  184. async def open_channel(self, buyer_addr, amount, details=None):
  185. """
  186. :param amount:
  187. :type amount:
  188. :param details:
  189. :type details:
  190. :return:
  191. :rtype:
  192. """
  193. assert self._session and self._session.is_attached()
  194. # FIXME
  195. signature = os.urandom(64)
  196. payment_channel = await self._session.call('xbr.marketmaker.open_payment_channel',
  197. buyer_addr,
  198. self._addr,
  199. amount,
  200. signature)
  201. balance = {
  202. 'amount': payment_channel['amount'],
  203. 'remaining': payment_channel['remaining'],
  204. 'inflight': payment_channel['inflight'],
  205. }
  206. return balance
  207. async def close_channel(self, details=None):
  208. """
  209. Requests to close the currently active payment channel.
  210. :return:
  211. """
  212. async def unwrap(self, key_id, serializer, ciphertext):
  213. """
  214. Decrypt XBR data. This functions will potentially make the buyer call the
  215. XBR market maker to buy data encryption keys from the XBR provider.
  216. :param key_id: ID of the data encryption used for decryption
  217. of application payload.
  218. :type key_id: bytes
  219. :param serializer: Application payload serializer.
  220. :type serializer: str
  221. :param ciphertext: Ciphertext of encrypted application payload to
  222. decrypt.
  223. :type ciphertext: bytes
  224. :return: Decrypted application payload.
  225. :rtype: object
  226. """
  227. assert type(key_id) == bytes and len(key_id) == 16
  228. # FIXME: support more app payload serializers
  229. assert type(serializer) == str and serializer in ['cbor']
  230. assert type(ciphertext) == bytes
  231. market_oid = self._channel['market_oid']
  232. channel_oid = self._channel['channel_oid']
  233. # FIXME
  234. current_block_number = 1
  235. verifying_chain_id = self._xbrmm_config['verifying_chain_id']
  236. verifying_contract_adr = binascii.a2b_hex(self._xbrmm_config['verifying_contract_adr'][2:])
  237. # if we don't have the key, buy it!
  238. if key_id in self._keys:
  239. self.log.debug('Key {key_id} already in key store (or currently being bought).',
  240. key_id=hl(uuid.UUID(bytes=key_id)))
  241. else:
  242. self.log.debug('Key {key_id} not yet in key store - buying key ..', key_id=hl(uuid.UUID(bytes=key_id)))
  243. # mark the key as currently being bought already (the location of code here is multi-entrant)
  244. self._keys[key_id] = False
  245. # get (current) price for key we want to buy
  246. quote = await self._session.call('xbr.marketmaker.get_quote', key_id)
  247. # set price we pay set to the (current) quoted price
  248. amount = unpack_uint256(quote['price'])
  249. self.log.debug('Key {key_id} has current price quote {amount}',
  250. key_id=hl(uuid.UUID(bytes=key_id)), amount=hl(int(amount / 10**18)))
  251. if amount > self._max_price:
  252. raise ApplicationError('xbr.error.max_price_exceeded',
  253. '{}.unwrap() - key {} needed cannot be bought: price {} exceeds maximum price of {}'.format(self.__class__.__name__, uuid.UUID(bytes=key_id), int(amount / 10 ** 18), int(self._max_price / 10 ** 18)))
  254. # check (locally) we have enough balance left in the payment channel to buy the key
  255. balance = self._balance - amount
  256. if balance < 0:
  257. if self._auto_close_channel:
  258. # FIXME: sign last transaction (from persisted local history)
  259. last_tx = None
  260. txns = self.past_transactions()
  261. if txns:
  262. last_tx = txns[0]
  263. if last_tx:
  264. # tx1 is the delegate portion, and tx2 is the market maker portion:
  265. # tx1, tx2 = last_tx
  266. # close_adr = tx1.channel
  267. # close_seq = tx1.channel_seq
  268. # close_balance = tx1.balance
  269. # close_is_final = True
  270. close_seq = self._seq
  271. close_balance = self._balance
  272. close_is_final = True
  273. signature = sign_eip712_channel_close(self._pkey_raw,
  274. verifying_chain_id,
  275. verifying_contract_adr,
  276. current_block_number,
  277. market_oid,
  278. channel_oid,
  279. close_seq,
  280. close_balance,
  281. close_is_final)
  282. self.log.debug('auto-closing payment channel {channel_oid} [close_seq={close_seq}, close_balance={close_balance}, close_is_final={close_is_final}]',
  283. channel_oid=uuid.UUID(bytes=channel_oid),
  284. close_seq=close_seq,
  285. close_balance=int(close_balance / 10**18),
  286. close_is_final=close_is_final)
  287. # call market maker to initiate closing of payment channel
  288. await self._session.call('xbr.marketmaker.close_channel',
  289. channel_oid,
  290. verifying_chain_id,
  291. current_block_number,
  292. verifying_contract_adr,
  293. pack_uint256(close_balance),
  294. close_seq,
  295. close_is_final,
  296. signature)
  297. # FIXME: wait for and acquire new payment channel instead of bailing out ..
  298. raise ApplicationError('xbr.error.channel_closed',
  299. '{}.unwrap() - key {} cannot be bought: payment channel {} ran empty and we initiated close at remaining balance of {}'.format(self.__class__.__name__,
  300. uuid.UUID(bytes=key_id),
  301. channel_oid,
  302. int(close_balance / 10 ** 18)))
  303. raise ApplicationError('xbr.error.insufficient_balance',
  304. '{}.unwrap() - key {} cannot be bought: insufficient balance {} in payment channel for amount {}'.format(self.__class__.__name__,
  305. uuid.UUID(bytes=key_id),
  306. int(self._balance / 10 ** 18),
  307. int(amount / 10 ** 18)))
  308. buyer_pubkey = self._receive_key.public_key.encode(encoder=nacl.encoding.RawEncoder)
  309. channel_seq = self._seq + 1
  310. is_final = False
  311. # XBRSIG[1/8]: compute EIP712 typed data signature
  312. signature = sign_eip712_channel_close(self._pkey_raw, verifying_chain_id, verifying_contract_adr,
  313. current_block_number, market_oid, channel_oid, channel_seq,
  314. balance, is_final)
  315. # persist 1st phase of the transaction locally
  316. self._save_transaction_phase1(channel_oid, self._addr, buyer_pubkey, key_id, channel_seq, amount, balance, signature)
  317. # call the market maker to buy the key
  318. try:
  319. receipt = await self._session.call('xbr.marketmaker.buy_key',
  320. self._addr,
  321. buyer_pubkey,
  322. key_id,
  323. channel_oid,
  324. channel_seq,
  325. pack_uint256(amount),
  326. pack_uint256(balance),
  327. signature)
  328. except ApplicationError as e:
  329. if e.error == 'xbr.error.channel_closed':
  330. self.stop()
  331. raise e
  332. except Exception as e:
  333. self.log.error('Encountered error while calling market maker to buy key!')
  334. self.log.failure()
  335. self._keys[key_id] = e
  336. raise e
  337. # XBRSIG[8/8]: check market maker signature
  338. marketmaker_signature = receipt['signature']
  339. marketmaker_channel_seq = receipt['channel_seq']
  340. marketmaker_amount_paid = unpack_uint256(receipt['amount_paid'])
  341. marketmaker_remaining = unpack_uint256(receipt['remaining'])
  342. marketmaker_inflight = unpack_uint256(receipt['inflight'])
  343. signer_address = recover_eip712_channel_close(verifying_chain_id, verifying_contract_adr,
  344. current_block_number, market_oid, channel_oid,
  345. marketmaker_channel_seq, marketmaker_remaining,
  346. False, marketmaker_signature)
  347. if signer_address != self._market_maker_adr:
  348. self.log.warn('{klass}.unwrap()::XBRSIG[8/8] - EIP712 signature invalid: signer_address={signer_address}, delegate_adr={delegate_adr}',
  349. klass=self.__class__.__name__,
  350. signer_address=hl(binascii.b2a_hex(signer_address).decode()),
  351. delegate_adr=hl(binascii.b2a_hex(self._market_maker_adr).decode()))
  352. raise ApplicationError('xbr.error.invalid_signature',
  353. '{}.unwrap()::XBRSIG[8/8] - EIP712 signature invalid or not signed by market maker'.format(self.__class__.__name__))
  354. if self._seq + 1 != marketmaker_channel_seq:
  355. raise ApplicationError('xbr.error.invalid_transaction',
  356. '{}.buy_key(): invalid transaction (channel sequence number mismatch - expected {}, but got {})'.format(self.__class__.__name__, self._seq, receipt['channel_seq']))
  357. if self._balance - amount != marketmaker_remaining:
  358. raise ApplicationError('xbr.error.invalid_transaction',
  359. '{}.buy_key(): invalid transaction (channel remaining amount mismatch - expected {}, but got {})'.format(self.__class__.__name__, self._balance - amount, receipt['remaining']))
  360. self._seq = marketmaker_channel_seq
  361. self._balance = marketmaker_remaining
  362. # persist 2nd phase of the transaction locally
  363. self._save_transaction_phase2(channel_oid, self._market_maker_adr, buyer_pubkey, key_id, marketmaker_channel_seq,
  364. marketmaker_amount_paid, marketmaker_remaining, marketmaker_signature)
  365. # unseal the data encryption key
  366. sealed_key = receipt['sealed_key']
  367. unseal_box = nacl.public.SealedBox(self._receive_key)
  368. try:
  369. key = unseal_box.decrypt(sealed_key)
  370. except nacl.exceptions.CryptoError as e:
  371. self._keys[key_id] = e
  372. raise ApplicationError('xbr.error.decryption_failed', '{}.unwrap() - could not unseal data encryption key: {}'.format(self.__class__.__name__, e))
  373. # remember the key, so we can use it to actually decrypt application payload data
  374. self._keys[key_id] = nacl.secret.SecretBox(key)
  375. transactions_count = self.count_transactions()
  376. self.log.info(
  377. '{klass}.unwrap() - {tx_type} key {key_id} bought for {amount_paid} [payment_channel={payment_channel}, remaining={remaining}, inflight={inflight}, buyer_pubkey={buyer_pubkey}, transactions={transactions}]',
  378. klass=self.__class__.__name__,
  379. tx_type=hl('XBR BUY ', color='magenta'),
  380. key_id=hl(uuid.UUID(bytes=key_id)),
  381. amount_paid=hl(str(int(marketmaker_amount_paid / 10 ** 18)) + ' XBR', color='magenta'),
  382. payment_channel=hl(binascii.b2a_hex(receipt['payment_channel']).decode()),
  383. remaining=hl(int(marketmaker_remaining / 10 ** 18)),
  384. inflight=hl(int(marketmaker_inflight / 10 ** 18)),
  385. buyer_pubkey=hl(binascii.b2a_hex(buyer_pubkey).decode()),
  386. transactions=transactions_count)
  387. # if the key is already being bought, wait until the one buying path of execution has succeeded and done
  388. log_counter = 0
  389. while self._keys[key_id] is False:
  390. if log_counter % 100:
  391. self.log.debug('{klass}.unwrap() - waiting for key "{key_id}" currently being bought ..',
  392. klass=self.__class__.__name__, key_id=hl(uuid.UUID(bytes=key_id)))
  393. log_counter += 1
  394. await txaio.sleep(.2)
  395. # check if the key buying failed and fail the unwrapping in turn
  396. if isinstance(self._keys[key_id], Exception):
  397. e = self._keys[key_id]
  398. raise e
  399. # now that we have the data encryption key, decrypt the application payload
  400. # the decryption key here is an instance of nacl.secret.SecretBox
  401. try:
  402. message = self._keys[key_id].decrypt(ciphertext)
  403. except nacl.exceptions.CryptoError as e:
  404. # Decryption failed. Ciphertext failed verification
  405. raise ApplicationError('xbr.error.decryption_failed', '{}.unwrap() - failed to unwrap encrypted data: {}'.format(self.__class__.__name__, e))
  406. # deserialize the application payload
  407. # FIXME: support more app payload serializers
  408. try:
  409. payload = cbor2.loads(message)
  410. except cbor2.decoder.CBORDecodeError as e:
  411. # premature end of stream (expected to read 4187 bytes, got 27 instead)
  412. raise ApplicationError('xbr.error.deserialization_failed', '{}.unwrap() - failed to deserialize application payload: {}'.format(self.__class__.__name__, e))
  413. return payload
  414. def _save_transaction_phase1(self, channel_oid, delegate_adr, buyer_pubkey, key_id, channel_seq, amount, balance, signature):
  415. """
  416. :param channel_oid:
  417. :param delegate_adr:
  418. :param buyer_pubkey:
  419. :param key_id:
  420. :param channel_seq:
  421. :param amount:
  422. :param balance:
  423. :param signature:
  424. :return:
  425. """
  426. if key_id in self._transaction_idx:
  427. raise RuntimeError('save_transaction_phase1: duplicate transaction for key 0x{}'.format(binascii.b2a_hex(key_id)))
  428. tx1 = Transaction(channel_oid, delegate_adr, buyer_pubkey, key_id, channel_seq, amount, balance, signature)
  429. key_idx = len(self._transactions)
  430. self._transactions.append([tx1, None])
  431. self._transaction_idx[key_id] = key_idx
  432. def _save_transaction_phase2(self, channel_oid, delegate_adr, buyer_pubkey, key_id, channel_seq, amount, balance, signature):
  433. """
  434. :param channel_oid:
  435. :param delegate_adr:
  436. :param buyer_pubkey:
  437. :param key_id:
  438. :param channel_seq:
  439. :param amount:
  440. :param balance:
  441. :param signature:
  442. :return:
  443. """
  444. if key_id not in self._transaction_idx:
  445. raise RuntimeError('save_transaction_phase2: transaction for key 0x{} not found'.format(binascii.b2a_hex(key_id)))
  446. key_idx = self._transaction_idx[key_id]
  447. if self._transactions[key_idx][1]:
  448. raise RuntimeError(
  449. 'save_transaction_phase2: duplicate transaction for key 0x{}'.format(binascii.b2a_hex(key_id)))
  450. tx1 = self._transactions[key_idx][0]
  451. tx2 = Transaction(channel_oid, delegate_adr, buyer_pubkey, key_id, channel_seq, amount, balance, signature)
  452. assert tx1.channel == tx2.channel
  453. # assert tx1.delegate == tx2.delegate
  454. assert tx1.pubkey == tx2.pubkey
  455. assert tx1.key_id == tx2.key_id
  456. assert tx1.channel_seq == tx2.channel_seq
  457. assert tx1.amount == tx2.amount
  458. assert tx1.balance == tx2.balance
  459. # note: signatures will differ (obviously)!
  460. assert tx1.signature != tx2.signature
  461. self._transactions[key_idx][1] = tx2
  462. def past_transactions(self, filter_complete=True, limit=1):
  463. """
  464. :param filter_complete:
  465. :param limit:
  466. :return:
  467. """
  468. assert type(filter_complete) == bool
  469. assert type(limit) == int and limit > 0
  470. n = 0
  471. res = []
  472. while n < limit:
  473. if len(self._transactions) > n:
  474. tx = self._transactions[-n]
  475. if not filter_complete or (tx[0] and tx[1]):
  476. res.append(tx)
  477. n += 1
  478. else:
  479. break
  480. return res
  481. def count_transactions(self):
  482. """
  483. :return:
  484. """
  485. res = {
  486. 'complete': 0,
  487. 'pending': 0,
  488. }
  489. for tx1, tx2 in self._transactions:
  490. if tx1 and tx2:
  491. res['complete'] += 1
  492. else:
  493. res['pending'] += 1
  494. return res
  495. def get_transaction(self, key_id):
  496. """
  497. :param key_id:
  498. :return:
  499. """
  500. idx = self._transaction_idx.get(key_id, None)
  501. if idx:
  502. return self._transactions[idx]
  503. def is_complete(self, key_id):
  504. """
  505. :param key_id:
  506. :return:
  507. """
  508. idx = self._transaction_idx.get(key_id, None)
  509. if idx:
  510. tx1, tx2 = self._transactions[idx]
  511. return tx1 and tx2
  512. return False