lbry-sdk/torba/baseaccount.py

270 lines
10 KiB
Python
Raw Normal View History

2018-06-11 15:33:32 +02:00
from typing import Dict
from twisted.internet import defer
from torba.mnemonic import Mnemonic
from torba.bip32 import PrivateKey, PubKey, from_extended_key_string
from torba.hash import double_sha256, aes_encrypt, aes_decrypt
2018-07-14 23:47:18 +02:00
class KeyManager(object):
2018-06-11 15:33:32 +02:00
2018-07-14 23:47:18 +02:00
__slots__ = 'account', 'public_key', 'chain_number'
def __init__(self, account, public_key, chain_number):
2018-06-11 15:33:32 +02:00
self.account = account
2018-07-14 23:47:18 +02:00
self.public_key = public_key
2018-06-11 15:33:32 +02:00
self.chain_number = chain_number
2018-07-14 23:47:18 +02:00
@property
def db(self):
return self.account.ledger.db
2018-06-11 15:33:32 +02:00
2018-07-14 23:47:18 +02:00
def _query_addresses(self, limit=None, max_used_times=None, order_by=None):
return self.db.get_addresses(
self.account, self.chain_number, limit, max_used_times, order_by
2018-06-11 15:33:32 +02:00
)
2018-07-14 23:47:18 +02:00
def ensure_address_gap(self): # type: () -> defer.Deferred
raise NotImplementedError
def get_address_records(self, limit=None, only_usable=False): # type: (int, bool) -> defer.Deferred
raise NotImplementedError
@defer.inlineCallbacks
def get_addresses(self, limit=None, only_usable=False): # type: (int, bool) -> defer.Deferred
records = yield self.get_address_records(limit=limit, only_usable=only_usable)
defer.returnValue([r['address'] for r in records])
@defer.inlineCallbacks
def get_or_create_usable_address(self): # type: () -> defer.Deferred
addresses = yield self.get_addresses(limit=1, only_usable=True)
if addresses:
defer.returnValue(addresses[0])
addresses = yield self.ensure_address_gap()
defer.returnValue(addresses[0])
class KeyChain(KeyManager):
""" Implements simple version of Bitcoin Hierarchical Deterministic key management. """
__slots__ = 'gap', 'maximum_uses_per_address'
def __init__(self, account, root_public_key, chain_number, gap, maximum_uses_per_address):
# type: ('BaseAccount', PubKey, int, int, int) -> None
super(KeyChain, self).__init__(account, root_public_key.child(chain_number), chain_number)
self.gap = gap
self.maximum_uses_per_address = maximum_uses_per_address
2018-06-12 16:02:04 +02:00
@defer.inlineCallbacks
def generate_keys(self, start, end):
2018-06-11 15:33:32 +02:00
new_keys = []
2018-06-12 16:02:04 +02:00
for index in range(start, end+1):
2018-07-14 23:47:18 +02:00
new_keys.append((index, self.public_key.child(index)))
2018-06-11 15:33:32 +02:00
yield self.db.add_keys(
self.account, self.chain_number, new_keys
)
2018-06-12 16:02:04 +02:00
defer.returnValue([key[1].address for key in new_keys])
@defer.inlineCallbacks
def ensure_address_gap(self):
2018-07-14 23:47:18 +02:00
addresses = yield self._query_addresses(self.gap, None, "position DESC")
2018-06-11 15:33:32 +02:00
2018-06-12 16:02:04 +02:00
existing_gap = 0
for address in addresses:
if address['used_times'] == 0:
existing_gap += 1
else:
break
if existing_gap == self.gap:
defer.returnValue([])
start = addresses[0]['position']+1 if addresses else 0
end = start + (self.gap - existing_gap)
new_keys = yield self.generate_keys(start, end-1)
defer.returnValue(new_keys)
2018-06-11 15:33:32 +02:00
2018-07-14 23:47:18 +02:00
def get_address_records(self, limit=None, only_usable=False):
return self._query_addresses(
limit, self.maximum_uses_per_address if only_usable else None,
"used_times ASC, position ASC"
)
class SingleKey(KeyManager):
""" Single Key manager always returns the same address for all operations. """
__slots__ = ()
def __init__(self, account, root_public_key, chain_number):
# type: ('BaseAccount', PubKey) -> None
super(SingleKey, self).__init__(account, root_public_key, chain_number)
2018-06-11 15:33:32 +02:00
@defer.inlineCallbacks
2018-07-14 23:47:18 +02:00
def ensure_address_gap(self):
exists = yield self.get_address_records()
if not exists:
yield self.db.add_keys(
self.account, self.chain_number, [(0, self.public_key)]
)
defer.returnValue([self.public_key.address])
defer.returnValue([])
def get_address_records(self, **kwargs):
return self._query_addresses()
2018-06-11 15:33:32 +02:00
class BaseAccount(object):
2018-06-11 15:33:32 +02:00
mnemonic_class = Mnemonic
private_key_class = PrivateKey
public_key_class = PubKey
2018-07-14 23:47:18 +02:00
def __init__(self, ledger, name, seed, encrypted, is_hd, private_key,
2018-06-12 16:02:04 +02:00
public_key, receiving_gap=20, change_gap=6,
2018-07-14 23:47:18 +02:00
receiving_maximum_uses_per_address=2, change_maximum_uses_per_address=2):
# type: (torba.baseledger.BaseLedger, str, str, bool, bool, PrivateKey, PubKey, int, int, int, int) -> None
2018-06-12 16:02:04 +02:00
self.ledger = ledger
2018-07-14 23:47:18 +02:00
self.name = name
2018-06-12 16:02:04 +02:00
self.seed = seed
self.encrypted = encrypted
self.private_key = private_key
self.public_key = public_key
2018-07-14 23:47:18 +02:00
if is_hd:
receiving, change = self.keychains = (
KeyChain(self, public_key, 0, receiving_gap, receiving_maximum_uses_per_address),
KeyChain(self, public_key, 1, change_gap, change_maximum_uses_per_address)
)
else:
self.keychains = SingleKey(self, public_key, 0),
receiving = change = self.keychains[0]
self.receiving = receiving # type: KeyManager
self.change = change # type: KeyManager
2018-06-14 02:57:57 +02:00
ledger.add_account(self)
2018-06-11 15:33:32 +02:00
@classmethod
2018-07-14 23:47:18 +02:00
def generate(cls, ledger, password, **kwargs): # type: (torba.baseledger.BaseLedger, str) -> BaseAccount
2018-06-11 15:33:32 +02:00
seed = cls.mnemonic_class().make_seed()
2018-07-14 23:47:18 +02:00
return cls.from_seed(ledger, seed, password, **kwargs)
2018-06-11 15:33:32 +02:00
@classmethod
2018-07-14 23:47:18 +02:00
def from_seed(cls, ledger, seed, password, is_hd=True, **kwargs):
2018-06-12 16:02:04 +02:00
# type: (torba.baseledger.BaseLedger, str, str) -> BaseAccount
2018-06-11 15:33:32 +02:00
private_key = cls.get_private_key_from_seed(ledger, seed, password)
return cls(
2018-07-14 23:47:18 +02:00
ledger=ledger, name='Account #{}'.format(private_key.public_key.address),
seed=seed, encrypted=False, is_hd=is_hd,
2018-06-11 15:33:32 +02:00
private_key=private_key,
2018-07-14 23:47:18 +02:00
public_key=private_key.public_key,
**kwargs
2018-06-11 15:33:32 +02:00
)
@classmethod
def get_private_key_from_seed(cls, ledger, seed, password):
2018-06-12 16:02:04 +02:00
# type: (torba.baseledger.BaseLedger, str, str) -> PrivateKey
2018-06-11 15:33:32 +02:00
return cls.private_key_class.from_seed(
ledger, cls.mnemonic_class.mnemonic_to_seed(seed, password)
)
@classmethod
2018-06-12 16:02:04 +02:00
def from_dict(cls, ledger, d): # type: (torba.baseledger.BaseLedger, Dict) -> BaseAccount
2018-07-14 23:47:18 +02:00
if not d['encrypted'] and d['private_key']:
2018-06-11 15:33:32 +02:00
private_key = from_extended_key_string(ledger, d['private_key'])
public_key = private_key.public_key
else:
private_key = d['private_key']
public_key = from_extended_key_string(ledger, d['public_key'])
2018-07-14 23:47:18 +02:00
kwargs = dict(
2018-06-11 15:33:32 +02:00
ledger=ledger,
2018-07-14 23:47:18 +02:00
name=d['name'],
2018-06-11 15:33:32 +02:00
seed=d['seed'],
encrypted=d['encrypted'],
private_key=private_key,
public_key=public_key,
2018-07-14 23:47:18 +02:00
is_hd=False
2018-06-11 15:33:32 +02:00
)
2018-07-14 23:47:18 +02:00
if d['is_hd']:
kwargs.update(dict(
receiving_gap=d['receiving_gap'],
change_gap=d['change_gap'],
receiving_maximum_uses_per_address=d['receiving_maximum_uses_per_address'],
change_maximum_uses_per_address=d['change_maximum_uses_per_address'],
is_hd=True
))
return cls(**kwargs)
2018-06-11 15:33:32 +02:00
def to_dict(self):
2018-07-14 23:47:18 +02:00
private_key = self.private_key
if not self.encrypted and self.private_key:
private_key = self.private_key.extended_key_string()
2018-07-14 23:47:18 +02:00
d = {
2018-06-11 15:33:32 +02:00
'ledger': self.ledger.get_id(),
2018-07-14 23:47:18 +02:00
'name': self.name,
2018-06-11 15:33:32 +02:00
'seed': self.seed,
'encrypted': self.encrypted,
2018-07-14 23:47:18 +02:00
'private_key': private_key,
'public_key': self.public_key.extended_key_string(),
2018-07-14 23:47:18 +02:00
'is_hd': False
2018-06-11 15:33:32 +02:00
}
2018-07-14 23:47:18 +02:00
if isinstance(self.receiving, KeyChain) and isinstance(self.change, KeyChain):
d.update({
'receiving_gap': self.receiving.gap,
'change_gap': self.change.gap,
'receiving_maximum_uses_per_address': self.receiving.maximum_uses_per_address,
'change_maximum_uses_per_address': self.change.maximum_uses_per_address,
'is_hd': True
})
return d
2018-06-11 15:33:32 +02:00
def decrypt(self, password):
assert self.encrypted, "Key is not encrypted."
secret = double_sha256(password)
self.seed = aes_decrypt(secret, self.seed)
self.private_key = from_extended_key_string(self.ledger, aes_decrypt(secret, self.private_key))
self.encrypted = False
def encrypt(self, password):
assert not self.encrypted, "Key is already encrypted."
secret = double_sha256(password)
self.seed = aes_encrypt(secret, self.seed)
self.private_key = aes_encrypt(secret, self.private_key.extended_key_string())
self.encrypted = True
@defer.inlineCallbacks
2018-06-12 16:02:04 +02:00
def ensure_address_gap(self):
2018-06-11 15:33:32 +02:00
addresses = []
for keychain in self.keychains:
2018-06-12 16:02:04 +02:00
new_addresses = yield keychain.ensure_address_gap()
2018-06-11 15:33:32 +02:00
addresses.extend(new_addresses)
defer.returnValue(addresses)
2018-07-14 23:47:18 +02:00
@defer.inlineCallbacks
def get_addresses(self, limit=None, max_used_times=None): # type: (int, int) -> defer.Deferred
records = yield self.get_address_records(limit, max_used_times)
defer.returnValue([r['address'] for r in records])
2018-06-12 16:02:04 +02:00
2018-07-14 23:47:18 +02:00
def get_address_records(self, limit=None, max_used_times=None): # type: (int, int) -> defer.Deferred
return self.ledger.db.get_addresses(self, None, limit, max_used_times)
2018-06-12 16:02:04 +02:00
2018-06-11 15:33:32 +02:00
def get_private_key(self, chain, index):
assert not self.encrypted, "Cannot get private key on encrypted wallet account."
2018-07-14 23:47:18 +02:00
if isinstance(self.receiving, SingleKey):
return self.private_key
else:
return self.private_key.child(chain).child(index)
2018-06-11 15:33:32 +02:00
def get_balance(self, confirmations=6, **constraints):
2018-07-17 05:58:29 +02:00
if confirmations > 0:
2018-07-14 23:47:18 +02:00
height = self.ledger.headers.height - (confirmations-1)
2018-07-17 05:58:29 +02:00
constraints.update({'height__lte': height, 'height__not': -1})
return self.ledger.db.get_balance_for_account(self, **constraints)
def get_unspent_outputs(self, **constraints):
return self.ledger.db.get_utxos_for_account(self, **constraints)