Browse Source

Merge branch 'hist_generators' into develop

master
Neil Booth 8 years ago
parent
commit
e18fd4c02c
  1. 55
      server/db.py

55
server/db.py

@ -433,27 +433,41 @@ class DB(object):
return tx_hash, height return tx_hash, height
def get_balance(self, hash160): @staticmethod
'''Returns the confirmed balance of an address.''' def resolve_limit(limit):
utxos = self.get_utxos(hash_160) if limit is None:
return sum(utxo.value for utxo in utxos) return -1
assert isinstance(limit, int) and limit >= 0
def get_history(self, hash160): return limit
'''Returns an unpruned, sorted list of (tx_hash, height) tuples of
transactions that touched the address, earliest in the def get_history(self, hash160, limit=1000):
blockchain first. Includes both spending and receiving '''Generator that returns an unpruned, sorted list of (tx_hash,
transactions. height) tuples of transactions that touched the address,
earliest in the blockchain first. Includes both spending and
receiving transactions. By default yields at most 1000 entries.
Set limit to None to get them all.
''' '''
limit = self.resolve_limit(limit)
prefix = b'H' + hash160 prefix = b'H' + hash160
a = array.array('I')
for key, hist in self.db.iterator(prefix=prefix): for key, hist in self.db.iterator(prefix=prefix):
a = array.array('I')
a.frombytes(hist) a.frombytes(hist)
return [self.get_tx_hash(tx_num) for tx_num in a] for tx_num in a:
if limit == 0:
return
yield self.get_tx_hash(tx_num)
limit -= 1
def get_balance(self, hash160):
'''Returns the confirmed balance of an address.'''
return sum(utxo.value for utxo in self.get_utxos(hash_160, limit=None))
def get_utxos(self, hash160): def get_utxos(self, hash160, limit=1000):
'''Returns all UTXOs for an address sorted such that the earliest '''Generator that yields all UTXOs for an address sorted in no
in the blockchain comes first. particular order. By default yields at most 1000 entries.
Set limit to None to get them all.
''' '''
limit = self.resolve_limit(limit)
unpack = struct.unpack unpack = struct.unpack
prefix = b'u' + hash160 prefix = b'u' + hash160
utxos = [] utxos = []
@ -461,10 +475,15 @@ class DB(object):
(tx_pos, ) = unpack('<H', k[-2:]) (tx_pos, ) = unpack('<H', k[-2:])
for n in range(0, len(v), 12): for n in range(0, len(v), 12):
if limit == 0:
return
(tx_num, ) = unpack('<I', v[n:n+4]) (tx_num, ) = unpack('<I', v[n:n+4])
(value, ) = unpack('<Q', v[n+4:n+12]) (value, ) = unpack('<Q', v[n+4:n+12])
tx_hash, height = self.get_tx_hash(tx_num) tx_hash, height = self.get_tx_hash(tx_num)
utxos.append(UTXO(tx_num, tx_pos, tx_hash, height, value)) yield UTXO(tx_num, tx_pos, tx_hash, height, value)
limit -= 1
# Sorted by height and block position. def get_utxos_sorted(self, hash160):
return sorted(utxos) '''Returns all the UTXOs for an address sorted by height and
position in the block.'''
return sorted(self.get_utxos(hash160, limit=None))

Loading…
Cancel
Save