indentation and imports cleaned up
[p2pool.git] / p2pool / data.py
index bb32016..a463665 100644 (file)
@@ -4,13 +4,12 @@ import itertools
 import random
 import time
 
-from twisted.internet import defer
 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, deferral
 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([
@@ -143,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)
@@ -187,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''')
         
@@ -203,11 +205,13 @@ 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
@@ -227,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
@@ -293,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:
@@ -310,7 +299,6 @@ class OkayTracker(bitcoin_data.Tracker):
             self.verified.add(share)
             return True
     
-    @defer.inlineCallbacks
     def think(self, ht, previous_block, now):
         desired = set()
         
@@ -348,33 +336,66 @@ class OkayTracker(bitcoin_data.Tracker):
             for share in itertools.islice(self.get_chain_known(last_hash), get):
                 if not self.attempt_verify(share, now):
                     break
-                if random.random() < .001:
-                    #print "YIELDING"
-                    yield deferral.sleep(.01)
             if head_height < self.net.CHAIN_LENGTH and last_last_hash is not None:
                 desired.add((self.verified.shares[random.choice(list(self.verified.reverse_shares[last_hash]))].peer, last_last_hash))
         
         # 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].peer is None, -self.verified.shares[h].time_seen))
+        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 __debug__:
-            #print len(self.verified.tails.get(best_tail, []))
-            #for a in scores:
-            #    print '   ', '%x'%a, self.score(a, ht)
+        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
+                )
         
-        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)
+        # 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
         
@@ -382,10 +403,10 @@ class OkayTracker(bitcoin_data.Tracker):
             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 p2pool.DEBUG:
-                    print "Stale detected!"
+                    print 'Stale detected!'
                 best = best_share.previous_hash
         
-        defer.returnValue((best, desired))
+        return best, desired
     
     @memoize.memoize_with_backing(expiring_dict.ExpiringDict(5, get_touches=False))
     def score(self, share_hash, ht):
@@ -393,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)
@@ -404,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
@@ -416,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
@@ -428,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'