indentation and imports cleaned up
[p2pool.git] / p2pool / data.py
index 538222b..a463665 100644 (file)
@@ -6,9 +6,10 @@ import time
 
 from twisted.python import log
 
-from p2pool.bitcoin import data as bitcoin_data
-from p2pool.bitcoin import script
-from p2pool.util import memoize, expiring_dict, math, skiplist
+import p2pool
+from p2pool import skiplists
+from p2pool.bitcoin import data as bitcoin_data, script
+from p2pool.util import memoize, expiring_dict, math
 
 
 merkle_branch_type = bitcoin_data.ListType(bitcoin_data.ComposedType([
@@ -95,9 +96,6 @@ def share_info_to_gentx(share_info, block_target, tracker, net):
     )
 
 class Share(object):
-    peer = None
-    highest_block_on_arrival = None
-    
     @classmethod
     def from_block(cls, block):
         return cls(block['header'], gentx_to_share_info(block['txs'][0]), other_txs=block['txs'][1:])
@@ -110,6 +108,8 @@ class Share(object):
     def from_share1b(cls, share1b):
         return cls(**share1b)
     
+    __slots__ = 'header previous_block share_info merkle_branch other_txs timestamp share_data new_script subsidy previous_hash previous_share_hash target nonce bitcoin_hash hash time_seen shared peer'.split(' ')
+    
     def __init__(self, header, share_info, merkle_branch=None, other_txs=None):
         if merkle_branch is None and other_txs is None:
             raise ValueError('need either merkle_branch or other_txs')
@@ -142,7 +142,7 @@ class Share(object):
         self.target = self.share_data['target']
         self.nonce = self.share_data['nonce']
         
-        if len(self.nonce) > 20:
+        if len(self.nonce) > 100:
             raise ValueError('nonce too long!')
         
         self.bitcoin_hash = bitcoin_data.block_header_type.hash256(header)
@@ -156,10 +156,12 @@ class Share(object):
         if script.get_sigop_count(self.new_script) > 1:
             raise ValueError('too many sigops!')
         
+        # XXX eww
         self.time_seen = time.time()
         self.shared = False
+        self.peer = None
     
-    def as_block(self, tracke, net):
+    def as_block(self, tracker, net):
         if self.other_txs is None:
             raise ValueError('share does not contain all txs')
         
@@ -184,6 +186,9 @@ class Share(object):
         
         gentx = share_info_to_gentx(self.share_info, self.header['target'], tracker, net)
         
+        if len(gentx['tx_ins'][0]['script']) > 100:
+            raise ValueError('''coinbase too large!''')
+        
         if check_merkle_branch(gentx, self.merkle_branch) != self.header['merkle_root']:
             raise ValueError('''gentx doesn't match header via merkle_branch''')
         
@@ -193,8 +198,6 @@ class Share(object):
             
             if len(bitcoin_data.block_type.pack(dict(header=self.header, txs=[gentx] + self.other_txs))) > 1000000 - 1000:
                 raise ValueError('''block size too large''')
-        
-        self.gentx = gentx
     
     def flag_shared(self):
         self.shared = True
@@ -202,18 +205,18 @@ class Share(object):
     def __repr__(self):
         return '<Share %s>' % (' '.join('%s=%r' % (k, v) for k, v in self.__dict__.iteritems()),)
 
-def get_pool_attempts_per_second(tracker, previous_share_hash, net):
-    # XXX could be optimized to use nth_parent and cumulative_weights
-    chain = list(itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.TARGET_LOOKBEHIND))
-    attempts = sum(bitcoin_data.target_to_average_attempts(share.target) for share in chain[:-1])
-    time = chain[0].timestamp - chain[-1].timestamp
+def get_pool_attempts_per_second(tracker, previous_share_hash, net, dist=None):
+    if dist is None:
+        dist = net.TARGET_LOOKBEHIND
+    near = tracker.shares[previous_share_hash]
+    far = tracker.shares[tracker.get_nth_parent_hash(previous_share_hash, dist - 1)]
+    attempts = tracker.get_work(near.hash) - tracker.get_work(far.hash)
+    time = near.timestamp - far.timestamp
     if time == 0:
         time = 1
     return attempts//time
 
 def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonce, block_target, net):
-    if __debug__:
-        print "start generate_transaction"
     height, last = tracker.get_height_and_last(previous_share_hash)
     if height < net.TARGET_LOOKBEHIND:
         target = bitcoin_data.FloatingIntegerType().truncate_to(2**256//2**20 - 1)
@@ -228,30 +231,10 @@ def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonc
     attempts_to_block = bitcoin_data.target_to_average_attempts(block_target)
     max_weight = net.SPREAD * attempts_to_block
     
-    '''
-    class fake_share(object):
-        pass
-    fake_share.new_script = new_script
-    fake_share.target = target
-    
-    dest_weights = {}
-    total_weight = 0
-    for share in itertools.chain([fake_share], itertools.islice(tracker.get_chain_to_root(previous_share_hash), net.CHAIN_LENGTH)):
-        weight = bitcoin_data.target_to_average_attempts(share.target)
-        if weight > max_weight - total_weight:
-            weight = max_weight - total_weight
-        
-        dest_weights[share.new_script] = dest_weights.get(share.new_script, 0) + weight
-        total_weight += weight
-        
-        if total_weight == max_weight:
-            break
-    '''
-    
     this_weight = min(bitcoin_data.target_to_average_attempts(target), max_weight)
     other_weights, other_weights_total = tracker.get_cumulative_weights(previous_share_hash, min(height, net.CHAIN_LENGTH), max(0, max_weight - this_weight))
     dest_weights, total_weight = math.add_dicts([{new_script: this_weight}, other_weights]), this_weight + other_weights_total
-    total_weight = sum(dest_weights.itervalues())
+    assert total_weight == sum(dest_weights.itervalues())
     
     amounts = dict((script, subsidy*(396*weight)//(400*total_weight)) for (script, weight) in dest_weights.iteritems())
     amounts[new_script] = amounts.get(new_script, 0) + subsidy*2//400
@@ -268,9 +251,6 @@ def generate_transaction(tracker, previous_share_hash, new_script, subsidy, nonc
     dests = sorted(pre_dests, key=lambda script: (script == new_script, script))
     assert dests[-1] == new_script
     
-    if __debug__:
-        print "end generate_transaction"
-    
     return dict(
         version=1,
         tx_ins=[dict(
@@ -297,7 +277,12 @@ class OkayTracker(bitcoin_data.Tracker):
         self.net = net
         self.verified = bitcoin_data.Tracker()
         
-        self.get_cumulative_weights = skiplist.WeightsSkipList(self)
+        self.get_cumulative_weights = skiplists.WeightsSkipList(self)
+    
+    def add(self, share, known_verified=False):
+        bitcoin_data.Tracker.add(self, share)
+        if known_verified:
+            self.verified.add(share)
     
     def attempt_verify(self, share, now):
         if share.hash in self.verified.shares:
@@ -308,19 +293,13 @@ class OkayTracker(bitcoin_data.Tracker):
         try:
             share.check(self, now, self.net)
         except:
-            print
-            print 'Share check failed:'
-            log.err()
-            print
+            log.err(None, 'Share check failed:')
             return False
         else:
             self.verified.add(share)
             return True
     
     def think(self, ht, previous_block, now):
-        if __debug__:
-            print "start think"
-        
         desired = set()
         
         # O(len(self.heads))
@@ -363,37 +342,70 @@ class OkayTracker(bitcoin_data.Tracker):
         # decide best tree
         best_tail = max(self.verified.tails, key=lambda h: self.score(max(self.verified.tails[h], key=self.verified.get_height), ht)) if self.verified.tails else None
         # decide best verified head
-        scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (self.verified.get_work(h), ht.get_min_height(self.verified.shares[h].previous_block), -self.verified.shares[h].time_seen))
-        
-        
-        #if __debug__:
-            #print len(self.verified.tails.get(best_tail, []))
-            #for a in scores:
-            #    print '   ', '%x'%a, self.score(a, ht)
-        
-        for share_hash in scores[:-5]:
-            if self.shares[share_hash].time_seen > time.time() - 30:
-                continue
-            self.remove(share_hash)
-            self.verified.remove(share_hash)
+        scores = sorted(self.verified.tails.get(best_tail, []), key=lambda h: (
+            self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
+            ht.get_min_height(self.verified.shares[h].previous_block),
+            self.verified.shares[h].peer is None,
+            -self.verified.shares[h].time_seen
+        ))
+        
+        
+        if p2pool.DEBUG:
+            print len(self.verified.tails.get(best_tail, []))
+            for h in scores:
+                print '   ', format_hash(h), format_hash(self.verified.shares[h].previous_hash), (
+                    self.verified.get_work(self.verified.get_nth_parent_hash(h, min(5, self.verified.get_height(h)))),
+                    ht.get_min_height(self.verified.shares[h].previous_block),
+                    self.verified.shares[h].peer is None,
+                    -self.verified.shares[h].time_seen
+                )
+        
+        # eat away at heads
+        if scores:
+            while True:
+                to_remove = set()
+                for share_hash, tail in self.heads.iteritems():
+                    if share_hash in scores[-5:]:
+                        continue
+                    if self.shares[share_hash].time_seen > time.time() - 30:
+                        continue
+                    if max(self.shares[before_tail_hash].time_seen for before_tail_hash in self.reverse_shares.get(tail)) > time.time() - 120:
+                        continue
+                    to_remove.add(share_hash)
+                for share_hash in to_remove:
+                    self.remove(share_hash)
+                    if share_hash in self.verified.shares:
+                        self.verified.remove(share_hash)
+                if not to_remove:
+                    break
         
-        #for tail, heads in list(self.tails.iteritems()):
-        #    if min(self.get_height(head) for head in heads) > 2*net.CHAIN_LENGTH + 10:
-        #        self.remove(tail)
-        #        self.verified.remove(tail)
+        # drop tails
+        while True:
+            removed = False
+            # if removed from this, it must be removed from verified
+            for tail, heads in list(self.tails.iteritems()):
+                if min(self.get_height(head) for head in heads) < 2*self.net.CHAIN_LENGTH + 10:
+                    continue
+                start = time.time()
+                for aftertail in list(self.reverse_shares.get(tail, set())):
+                    self.remove(aftertail)
+                    if aftertail in self.verified.shares:
+                        self.verified.remove(aftertail)
+                    removed = True
+                end = time.time()
+                print "removed! %x %f" % (tail, end - start)
+            if not removed:
+                break
         
         best = scores[-1] if scores else None
         
         if best is not None:
             best_share = self.verified.shares[best]
             if ht.get_min_height(best_share.header['previous_block']) < ht.get_min_height(previous_block) and best_share.bitcoin_hash != previous_block and best_share.peer is not None:
-                if __debug__:
-                    print "stale detected!"
+                if p2pool.DEBUG:
+                    print 'Stale detected!'
                 best = best_share.previous_hash
         
-        if __debug__:
-            print "end think"
-        
         return best, desired
     
     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
@@ -402,9 +414,7 @@ class OkayTracker(bitcoin_data.Tracker):
         score2 = 0
         attempts = 0
         max_height = 0
-        # XXX should only look past a certain share, not at recent ones
         share2_hash = self.verified.get_nth_parent_hash(share_hash, min(self.net.CHAIN_LENGTH//2, head_height//2)) if last is not None else share_hash
-        # XXX this must go in the opposite direction for max_height to make sense
         for share in reversed(list(itertools.islice(self.verified.get_chain_known(share2_hash), self.net.CHAIN_LENGTH))):
             max_height = max(max_height, ht.get_min_height(share.header['previous_block']))
             attempts += bitcoin_data.target_to_average_attempts(share.target)
@@ -413,6 +423,10 @@ class OkayTracker(bitcoin_data.Tracker):
                 score2 = this_score
         return min(head_height, self.net.CHAIN_LENGTH), score2
 
+def format_hash(x):
+    if x is None:
+        return 'xxxxxxxx'
+    return '%08x' % (x % 2**32)
 
 class Mainnet(bitcoin_data.Mainnet):
     SHARE_PERIOD = 5 # seconds
@@ -425,6 +439,8 @@ class Mainnet(bitcoin_data.Mainnet):
     ADDRS_TABLE = 'addrs'
     P2P_PORT = 9333
     MAX_TARGET = 2**256//2**32 - 1
+    PERSIST = True
+    HEADERSTORE_FILENAME = 'headers.dat'
 
 class Testnet(bitcoin_data.Testnet):
     SHARE_PERIOD = 1 # seconds
@@ -437,3 +453,5 @@ class Testnet(bitcoin_data.Testnet):
     ADDRS_TABLE = 'addrs_testnet'
     P2P_PORT = 19333
     MAX_TARGET = 2**256//2**20 - 1
+    PERSIST = False
+    HEADERSTORE_FILENAME = 'testnet_headers.dat'