cic-internal-integration/apps/cic-eth/cic_eth/eth/nonce.py

83 lines
2.4 KiB
Python
Raw Normal View History

2021-04-04 14:40:59 +02:00
# standard imports
import logging
# external imports
import celery
2021-10-07 17:12:35 +02:00
from chainlib.eth.address import is_checksum_address, is_address, strip_0x
2021-04-04 14:40:59 +02:00
2021-02-01 18:12:51 +01:00
# local imports
2021-04-04 14:40:59 +02:00
from cic_eth.db.models.role import AccountRole
from cic_eth.db.models.base import SessionBase
2021-10-07 17:12:35 +02:00
from cic_eth.encode import tx_normalize
2021-04-04 14:40:59 +02:00
from cic_eth.task import CriticalSQLAlchemyTask
2021-03-06 18:55:51 +01:00
from cic_eth.db.models.nonce import (
Nonce,
NonceReservation,
)
2021-02-01 18:12:51 +01:00
2021-04-04 14:40:59 +02:00
celery_app = celery.current_app
logg = logging.getLogger()
class CustodialTaskNonceOracle():
2021-02-01 18:12:51 +01:00
"""Ensures atomic nonce increments for all transactions across all tasks and threads.
:param address: Address to generate nonces for
:type address: str, 0x-hex
:param default_nonce: Initial nonce value to use if no nonce cache entry already exists
:type default_nonce: number
"""
def __init__(self, address, uuid, session=None):
2021-02-01 18:12:51 +01:00
self.address = address
self.uuid = uuid
self.session = session
2021-02-01 18:12:51 +01:00
def get_nonce(self):
return self.next_nonce()
def next_nonce(self):
2021-02-01 18:12:51 +01:00
"""Get next unique nonce.
:returns: Nonce
:rtype: number
"""
2021-10-07 17:12:35 +02:00
address = tx_normalize.wallet_address(self.address)
r = NonceReservation.release(address, self.uuid, session=self.session)
return r[1]
2021-04-04 14:40:59 +02:00
@celery_app.task(bind=True, base=CriticalSQLAlchemyTask)
def reserve_nonce(self, chained_input, chain_spec_dict, signer_address=None):
self.log_banner()
session = SessionBase.create_session()
address = None
if signer_address == None:
address = chained_input
logg.debug('non-explicit address for reserve nonce, using arg head {}'.format(chained_input))
else:
2021-10-07 17:12:35 +02:00
if is_address(signer_address):
2021-04-04 14:40:59 +02:00
address = signer_address
logg.debug('explicit address for reserve nonce {}'.format(signer_address))
else:
address = AccountRole.get_address(signer_address, session=session)
logg.debug('role for reserve nonce {} -> {}'.format(signer_address, address))
2021-10-07 17:12:35 +02:00
if not is_address(address):
2021-04-04 14:40:59 +02:00
raise ValueError('invalid result when resolving address for nonce {}'.format(address))
root_id = self.request.root_id
2021-10-07 17:12:35 +02:00
address = tx_normalize.wallet_address(address)
2021-04-04 14:40:59 +02:00
r = NonceReservation.next(address, root_id, session=session)
logg.debug('nonce {} reserved for address {} task {}'.format(r[1], address, r[0]))
session.commit()
session.close()
return chained_input