Repository: Bitmessage/PyBitmessage

Issue:
Duplicates problem: duplicate messages arrive and stay until the client shutdown
I noticed that when someone answers my message, there is high chance that after a while this same response will come again for no apparent reason. Delay of duplicate varies from 20 min to 2-3 days. Duplicates are time-stamped with the time of arrival. I only noticed this with replies, not the originals.

However, when I shut the client down and restart it, only the latest duplicate would stay, and the earlier version would disappear. So the time on the message would be entirely wrong.

8c900e119488f374b951d012b378bb4adf3ce06b



Discussion:
What types of messages is this affecting? Messages received from Chans? Normal person-to-person messages which don't involve chans?

It's person to person

Just reporting that I'm seeing this as well for person-to-person messages. I normally leave the client running, so I hadn't noticed that only the most recent message from the duplicates would remain after a restart.

I can also confirm that if you've gone and trashed all the duplicates but the first one to arrive, then that original message disappears on restart (presumably because only the most most recent would be shown, but you've trashed that).

To help me diagnose the issue, try this: the next time it happens (or if you have the duplicate messages showing in your UI right now, use the search box to search for something meaningless, then clear the search box and press enter to show all of your inbox messages. Are the duplicates showing? I imagine that they won't.

I also wish to look for patterns: Are you two using the EXE, the DMG, or the source code from December 8th or earlier or later?

Source code (git clone) as of 4th January, running on ubuntu 12.04. My apologies I don't have a specific commit id.

Alas I don't have any duplicates showing right now but I shall cheerfully try the search-and-clear test if/when I do.

That's ok; saying January is sufficient (it rules out some things).

For the purposes of helping me find my accidentally missing
deleted messages, whereabouts is the application trash? ;)

If you use a SQLite editor, you can open the messages.dat file. Close Bitmessage first. All of your current and previous inbox messages are in the inbox table. One of the fields is 'folder' which will say either 'inbox' or 'trash'. 

Aha! They're in the XDG config directory (~/.config/PyBitMessage), not the
XDG data direcotry (~/.local/share/PyBitMessage), that's why I couldn't find
the `messages.dat` file!

Many thanks!

I just run from the source code, git label in my OP

A user on Reddit reported probably the same problem here: https://pay.reddit.com/r/bitmessage/comments/1v0to6/help_bitmessage_keeps_sending_me_the_same/ceoyce0

I'm going to leave a node running which is in a bunch of chans and if it happens on my node I will have the console output to look at which should help a lot.

Someone reported the same on General Chat mailing list: BM-2DAV89w336ovy6BUJnfVRD5B9qipFbRgmr

```
What's the matter with Bitmessage? I'm receiving all the same messages over and over again!!! Anyone else?
```


Resolving patch:
diff --git a/src/class_objectProcessor.py b/src/class_objectProcessor.py
--- a/src/class_objectProcessor.py
+++ b/src/class_objectProcessor.py
@@ -100,53 +100,45 @@ def processgetpubkey(self, data):
         readPosition += streamNumberLength
 
         if requestedAddressVersionNumber == 0:
-            print 'The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.'
+            logger.debug('The requestedAddressVersionNumber of the pubkey request is zero. That doesn\'t make any sense. Ignoring it.')
             return
         elif requestedAddressVersionNumber == 1:
-            print 'The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.'
+            logger.debug('The requestedAddressVersionNumber of the pubkey request is 1 which isn\'t supported anymore. Ignoring it.')
             return
         elif requestedAddressVersionNumber > 4:
-            print 'The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.'
+            logger.debug('The requestedAddressVersionNumber of the pubkey request is too high. Can\'t understand. Ignoring it.')
             return
 
         myAddress = ''
         if requestedAddressVersionNumber <= 3 :
             requestedHash = data[readPosition:readPosition + 20]
             if len(requestedHash) != 20:
-                print 'The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.'
+                logger.debug('The length of the requested hash is not 20 bytes. Something is wrong. Ignoring.')
                 return
-            with shared.printLock:
-                print 'the hash requested in this getpubkey request is:', requestedHash.encode('hex')
+            logger.info('the hash requested in this getpubkey request is: %s' % requestedHash.encode('hex'))
             if requestedHash in shared.myAddressesByHash:  # if this address hash is one of mine
                 myAddress = shared.myAddressesByHash[requestedHash]
         elif requestedAddressVersionNumber >= 4:
             requestedTag = data[readPosition:readPosition + 32]
             if len(requestedTag) != 32:
-                print 'The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.'
+                logger.debug('The length of the requested tag is not 32 bytes. Something is wrong. Ignoring.')
                 return
-            with shared.printLock:
-                print 'the tag requested in this getpubkey request is:', requestedTag.encode('hex')
+            logger.debug('the tag requested in this getpubkey request is: %s' % requestedTag.encode('hex'))
             if requestedTag in shared.myAddressesByTag:
                 myAddress = shared.myAddressesByTag[requestedTag]
 
         if myAddress == '':
-            with shared.printLock:
-                print 'This getpubkey request is not for any of my keys.'
+            logger.info('This getpubkey request is not for any of my keys.')
             return
 
         if decodeAddress(myAddress)[1] != requestedAddressVersionNumber:
-            with shared.printLock:
-                sys.stderr.write(
-                 '(Within the recgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.\n')
+            logger.warning('(Within the processgetpubkey function) Someone requested one of my pubkeys but the requestedAddressVersionNumber doesn\'t match my actual address version number. Ignoring.')
             return
         if decodeAddress(myAddress)[2] != streamNumber:
-            with shared.printLock:
-                sys.stderr.write(
-                 '(Within the recgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.\n')
+            logger.warning('(Within the processgetpubkey function) Someone requested one of my pubkeys but the stream number on which we heard this getpubkey object doesn\'t match this address\' stream number. Ignoring.')
             return
         if shared.safeConfigGetBoolean(myAddress, 'chan'):
-            with shared.printLock:
-                print 'Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.'
+            logger.info('Ignoring getpubkey request because it is for one of my chan addresses. The other party should already have the pubkey.')
             return
         try:
             lastPubkeySendTime = int(shared.config.get(
@@ -154,12 +146,9 @@ def processgetpubkey(self, data):
         except:
             lastPubkeySendTime = 0
         if lastPubkeySendTime > time.time() - shared.lengthOfTimeToHoldOnToAllPubkeys:  # If the last time we sent our pubkey was more recent than 28 days ago...
-            with shared.printLock:
-                print 'Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is:', lastPubkeySendTime
+            logger.info('Found getpubkey-requested-item in my list of EC hashes BUT we already sent it recently. Ignoring request. The lastPubkeySendTime is: %s' % lastPubkeySendTime) 
             return
-
-        with shared.printLock:
-            print 'Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.'
+        logger.info('Found getpubkey-requested-hash in my list of EC hashes. Telling Worker thread to do the POW for a pubkey message and send it out.') 
         if requestedAddressVersionNumber == 2:
             shared.workerQueue.put((
                 'doPOWForMyV2Pubkey', requestedHash))
@@ -193,15 +182,14 @@ def processpubkey(self, data):
             data[readPosition:readPosition + 10])
         readPosition += varintLength
         if addressVersion == 0:
-            print '(Within processpubkey) addressVersion of 0 doesn\'t make sense.'
+            logger.debug('(Within processpubkey) addressVersion of 0 doesn\'t make sense.')
             return
         if addressVersion > 4 or addressVersion == 1:
-            with shared.printLock:
-                print 'This version of Bitmessage cannot handle version', addressVersion, 'addresses.'
+            logger.info('This version of Bitmessage cannot handle version %s addresses.' % addressVersion)
             return
         if addressVersion == 2:
             if len(data) < 146:  # sanity check. This is the minimum possible length.
-                print '(within processpubkey) payloadLength less than 146. Sanity check failed.'
+                logger.debug('(within processpubkey) payloadLength less than 146. Sanity check failed.')
                 return
             bitfieldBehaviors = data[readPosition:readPosition + 4]
             readPosition += 4
@@ -212,7 +200,7 @@ def processpubkey(self, data):
             readPosition += 64
             publicEncryptionKey = data[readPosition:readPosition + 64]
             if len(publicEncryptionKey) < 64:
-                print 'publicEncryptionKey length less than 64. Sanity check failed.'
+                logger.debug('publicEncryptionKey length less than 64. Sanity check failed.')
                 return
             sha = hashlib.new('sha512')
             sha.update(
@@ -221,20 +209,25 @@ def processpubkey(self, data):
             ripeHasher.update(sha.digest())
             ripe = ripeHasher.digest()
 
-            with shared.printLock:
-                print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
-                print 'ripe', ripe.encode('hex')
-                print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
-                print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
 
+            logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
+                        ripe %s\n\
+                        publicSigningKey in hex: %s\n\
+                        publicEncryptionKey in hex: %s' % (addressVersion, 
+                                                           streamNumber, 
+                                                           ripe.encode('hex'), 
+                                                           publicSigningKey.encode('hex'), 
+                                                           publicEncryptionKey.encode('hex')
+                                                           )
+                        )
 
             queryreturn = sqlQuery(
                 '''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
             if queryreturn != []:  # if this pubkey is already in our database and if we have used it personally:
-                print 'We HAVE used this pubkey personally. Updating time.'
+                logger.info('We HAVE used this pubkey personally. Updating time.')
                 t = (ripe, addressVersion, data, embeddedTime, 'yes')
             else:
-                print 'We have NOT used this pubkey personally. Inserting in database.'
+                logger.info('We have NOT used this pubkey personally. Inserting in database.')
                 t = (ripe, addressVersion, data, embeddedTime, 'no')
                      # This will also update the embeddedTime.
             sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
@@ -242,7 +235,7 @@ def processpubkey(self, data):
             self.possibleNewPubkey(ripe = ripe)
         if addressVersion == 3:
             if len(data) < 170:  # sanity check.
-                print '(within processpubkey) payloadLength less than 170. Sanity check failed.'
+                logger.warning('(within processpubkey) payloadLength less than 170. Sanity check failed.')
                 return
             bitfieldBehaviors = data[readPosition:readPosition + 4]
             readPosition += 4
@@ -266,11 +259,11 @@ def processpubkey(self, data):
             signature = data[readPosition:readPosition + signatureLength]
             try:
                 if not highlevelcrypto.verify(data[8:endOfSignedDataPosition], signature, publicSigningKey.encode('hex')):
-                    print 'ECDSA verify failed (within processpubkey)'
+                    logger.warning('ECDSA verify failed (within processpubkey)')
                     return
-                print 'ECDSA verify passed (within processpubkey)'
+                logger.info('ECDSA verify passed (within processpubkey)')
             except Exception as err:
-                print 'ECDSA verify failed (within processpubkey)', err
+                logger.warning('ECDSA verify failed (within processpubkey) %s' % err)
                 return
 
             sha = hashlib.new('sha512')
@@ -278,20 +271,25 @@ def processpubkey(self, data):
             ripeHasher = hashlib.new('ripemd160')
             ripeHasher.update(sha.digest())
             ripe = ripeHasher.digest()
-
-            with shared.printLock:
-                print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
-                print 'ripe', ripe.encode('hex')
-                print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
-                print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
-
+            
+
+            logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
+                        ripe %s\n\
+                        publicSigningKey in hex: %s\n\
+                        publicEncryptionKey in hex: %s' % (addressVersion, 
+                                                           streamNumber, 
+                                                           ripe.encode('hex'), 
+                                                           publicSigningKey.encode('hex'), 
+                                                           publicEncryptionKey.encode('hex')
+                                                           )
+                        )
 
             queryreturn = sqlQuery('''SELECT usedpersonally FROM pubkeys WHERE hash=? AND addressversion=? AND usedpersonally='yes' ''', ripe, addressVersion)
             if queryreturn != []:  # if this pubkey is already in our database and if we have used it personally:
-                print 'We HAVE used this pubkey personally. Updating time.'
+                logger.info('We HAVE used this pubkey personally. Updating time.')
                 t = (ripe, addressVersion, data, embeddedTime, 'yes')
             else:
-                print 'We have NOT used this pubkey personally. Inserting in database.'
+                logger.info('We have NOT used this pubkey personally. Inserting in database.')
                 t = (ripe, addressVersion, data, embeddedTime, 'no')
                      # This will also update the embeddedTime.
             sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
@@ -308,15 +306,14 @@ def processpubkey(self, data):
             would run and handle that event quite quickly. 
             """ 
             if len(data) < 350:  # sanity check.
-                print '(within processpubkey) payloadLength less than 350. Sanity check failed.'
+                logger.debug('(within processpubkey) payloadLength less than 350. Sanity check failed.')
                 return
             signedData = data[8:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
             tag = data[readPosition:readPosition + 32]
             readPosition += 32
             encryptedData = data[readPosition:]
             if tag not in shared.neededPubkeys:
-                with shared.printLock:
-                    print 'We don\'t need this v4 pubkey. We didn\'t ask for it.'
+                logger.info('We don\'t need this v4 pubkey. We didn\'t ask for it.')
                 return
 
             # Let us try to decrypt the pubkey
@@ -326,8 +323,7 @@ def processpubkey(self, data):
             except:
                 # Someone must have encrypted some data with a different key
                 # but tagged it with a tag for which we are watching.
-                with shared.printLock:
-                    print 'Pubkey decryption was unsuccessful.'
+                logger.info('Pubkey decryption was unsuccessful.')
                 return
 
             readPosition = 0
@@ -353,11 +349,11 @@ def processpubkey(self, data):
             signature = decryptedData[readPosition:readPosition + signatureLength]
             try:
                 if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
-                    print 'ECDSA verify failed (within processpubkey)'
+                    logger.info('ECDSA verify failed (within processpubkey)')
                     return
-                print 'ECDSA verify passed (within processpubkey)'
+                logger.info('ECDSA verify passed (within processpubkey)')
             except Exception as err:
-                print 'ECDSA verify failed (within processpubkey)', err
+                logger.info('ECDSA verify failed (within processpubkey) %s' % err)
                 return
 
             sha = hashlib.new('sha512')
@@ -369,17 +365,19 @@ def processpubkey(self, data):
             # We need to make sure that the tag on the outside of the encryption
             # is the one generated from hashing these particular keys.
             if tag != hashlib.sha512(hashlib.sha512(encodeVarint(addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]:
-                with shared.printLock:
-                    print 'Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.'
+                logger.info('Someone was trying to act malicious: tag doesn\'t match the keys in this pubkey message. Ignoring it.')
                 return
-            else:
-                print 'Tag successfully matches keys in pubkey message' # testing. Will remove soon.
-
-            with shared.printLock:
-                print 'within recpubkey, addressVersion:', addressVersion, ', streamNumber:', streamNumber
-                print 'ripe', ripe.encode('hex')
-                print 'publicSigningKey in hex:', publicSigningKey.encode('hex')
-                print 'publicEncryptionKey in hex:', publicEncryptionKey.encode('hex')
+            
+            logger.info('within recpubkey, addressVersion: %s, streamNumber: %s \n\
+                        ripe %s\n\
+                        publicSigningKey in hex: %s\n\
+                        publicEncryptionKey in hex: %s' % (addressVersion, 
+                                                           streamNumber, 
+                                                           ripe.encode('hex'), 
+                                                           publicSigningKey.encode('hex'), 
+                                                           publicEncryptionKey.encode('hex')
+                                                           )
+                        )
 
             t = (ripe, addressVersion, signedData, embeddedTime, 'yes')
             sqlExecute('''INSERT INTO pubkeys VALUES (?,?,?,?,?)''', *t)
@@ -393,8 +391,7 @@ def processpubkey(self, data):
         # Display timing data
         timeRequiredToProcessPubkey = time.time(
         ) - pubkeyProcessingStartTime
-        with shared.printLock:
-            print 'Time required to process this pubkey:', timeRequiredToProcessPubkey
+        logger.debug('Time required to process this pubkey: %s' % timeRequiredToProcessPubkey)
 
 
     def processmsg(self, data):
@@ -419,9 +416,7 @@ def processmsg(self, data):
         initialDecryptionSuccessful = False
         # Let's check whether this is a message acknowledgement bound for us.
         if data[readPosition:] in shared.ackdataForWhichImWatching:
-            with shared.printLock:
-                print 'This msg IS an acknowledgement bound for me.'
-
+            logger.info('This msg IS an acknowledgement bound for me.')
             del shared.ackdataForWhichImWatching[data[readPosition:]]
             sqlExecute('UPDATE sent SET status=? WHERE ackdata=?',
                        'ackreceived', data[readPosition:])
@@ -429,9 +424,7 @@ def processmsg(self, data):
                 time.strftime(shared.config.get('bitmessagesettings', 'timeformat'), time.localtime(int(time.time()))), 'utf-8')))))
             return
         else:
-            with shared.printLock:
-                print 'This was NOT an acknowledgement bound for me.'
-            # print 'shared.ackdataForWhichImWatching', shared.ackdataForWhichImWatching
+            logger.info('This was NOT an acknowledgement bound for me.')
 
 
         # This is not an acknowledgement bound for me. See if it is a message
@@ -442,16 +435,14 @@ def processmsg(self, data):
                     data[readPosition:])
                 toRipe = key  # This is the RIPE hash of my pubkeys. We need this below to compare to the destination_ripe included in the encrypted data.
                 initialDecryptionSuccessful = True
-                with shared.printLock:
-                    print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
+                logger.info('EC decryption successful using key associated with ripe hash: %s' % key.encode('hex')) 
                 break
             except Exception as err:
                 pass
                 # print 'cryptorObject.decrypt Exception:', err
         if not initialDecryptionSuccessful:
             # This is not a message bound for me.
-            with shared.printLock:
-                print 'Length of time program spent failing to decrypt this message:', time.time() - messageProcessingStartTime, 'seconds.'
+            logger.info('Length of time program spent failing to decrypt this message: %s seconds.' % (time.time() - messageProcessingStartTime,)) 
             return
 
         # This is a message bound for me.
@@ -462,24 +453,24 @@ def processmsg(self, data):
             decryptedData[readPosition:readPosition + 10])
         readPosition += messageVersionLength
         if messageVersion != 1:
-            print 'Cannot understand message versions other than one. Ignoring message.'
+            logger.info('Cannot understand message versions other than one. Ignoring message.') 
             return
         sendersAddressVersionNumber, sendersAddressVersionNumberLength = decodeVarint(
             decryptedData[readPosition:readPosition + 10])
         readPosition += sendersAddressVersionNumberLength
         if sendersAddressVersionNumber == 0:
-            print 'Cannot understand sendersAddressVersionNumber = 0. Ignoring message.'
+            logger.info('Cannot understand sendersAddressVersionNumber = 0. Ignoring message.') 
             return
         if sendersAddressVersionNumber > 4:
-            print 'Sender\'s address version number', sendersAddressVersionNumber, 'not yet supported. Ignoring message.'
+            logger.info('Sender\'s address version number %s not yet supported. Ignoring message.' % sendersAddressVersionNumber)  
             return
         if len(decryptedData) < 170:
-            print 'Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.'
+            logger.info('Length of the unencrypted data is unreasonably short. Sanity check failed. Ignoring message.')
             return
         sendersStreamNumber, sendersStreamNumberLength = decodeVarint(
             decryptedData[readPosition:readPosition + 10])
         if sendersStreamNumber == 0:
-            print 'sender\'s stream number is 0. Ignoring message.'
+            logger.info('sender\'s stream number is 0. Ignoring message.')
             return
         readPosition += sendersStreamNumberLength
         behaviorBitfield = decryptedData[readPosition:readPosition + 4]
@@ -494,18 +485,18 @@ def processmsg(self, data):
             requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 10])
             readPosition += varintLength
-            print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
+            logger.info('sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s' % requiredAverageProofOfWorkNonceTrialsPerByte)
             requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 10])
             readPosition += varintLength
-            print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
+            logger.info('sender\'s requiredPayloadLengthExtraBytes is %s' % requiredPayloadLengthExtraBytes)
         endOfThePublicKeyPosition = readPosition  # needed for when we store the pubkey in our database of pubkeys for later use.
         if toRipe != decryptedData[readPosition:readPosition + 20]:
-            with shared.printLock:
-                print 'The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.'
-                print 'See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html'
-                print 'your toRipe:', toRipe.encode('hex')
-                print 'embedded destination toRipe:', decryptedData[readPosition:readPosition + 20].encode('hex')
+            logger.info('The original sender of this message did not send it to you. Someone is attempting a Surreptitious Forwarding Attack.\n\
+                See: http://world.std.com/~dtd/sign_encrypt/sign_encrypt7.html \n\
+                your toRipe: %s\n\
+                embedded destination toRipe: %s' % (toRipe.encode('hex'), decryptedData[readPosition:readPosition + 20].encode('hex'))
+                       )
             return
         readPosition += 20
         messageEncodingType, messageEncodingTypeLength = decodeVarint(
@@ -530,14 +521,15 @@ def processmsg(self, data):
             readPosition:readPosition + signatureLength]
         try:
             if not highlevelcrypto.verify(decryptedData[:positionOfBottomOfAckData], signature, pubSigningKey.encode('hex')):
-                print 'ECDSA verify failed'
+                logger.debug('ECDSA verify failed')
                 return
-            print 'ECDSA verify passed'
+            logger.debug('ECDSA verify passed')
         except Exception as err:
-            print 'ECDSA verify failed', err
+            logger.debug('ECDSA verify failed %s' % err)
             return
-        with shared.printLock:
-            print 'As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person:', helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), '  ..and here is the testnet address:', helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey), '. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.'
+        logger.debug('As a matter of intellectual curiosity, here is the Bitcoin address associated with the keys owned by the other person: %s  ..and here is the testnet address: %s. The other person must take their private signing key from Bitmessage and import it into Bitcoin (or a service like Blockchain.info) for it to be of any use. Do not use this unless you know what you are doing.' %
+                     (helper_bitcoin.calculateBitcoinAddressFromPubkey(pubSigningKey), helper_bitcoin.calculateTestnetAddressFromPubkey(pubSigningKey))
+                     )
 
         # calculate the fromRipe.
         sha = hashlib.new('sha512')
@@ -574,8 +566,10 @@ def processmsg(self, data):
             self.possibleNewPubkey(address = fromAddress)
         # If this message is bound for one of my version 3 addresses (or
         # higher), then we must check to make sure it meets our demanded
-        # proof of work requirement.
-        if decodeAddress(toAddress)[1] >= 3:  # If the toAddress version number is 3 or higher:
+        # proof of work requirement. If this is bound for one of my chan
+        # addresses then we skip this check; the minimum network POW is
+        # fine.
+        if decodeAddress(toAddress)[1] >= 3 and not shared.safeConfigGetBoolean(toAddress, 'chan'):  # If the toAddress version number is 3 or higher and not one of my chan addresses:
             if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress):  # If I'm not friendly with this person:
                 requiredNonceTrialsPerByte = shared.config.getint(
                     toAddress, 'noncetrialsperbyte')
@@ -590,8 +584,7 @@ def processmsg(self, data):
                 '''SELECT label FROM blacklist where address=? and enabled='1' ''',
                 fromAddress)
             if queryreturn != []:
-                with shared.printLock:
-                    print 'Message ignored because address is in blacklist.'
+                logger.info('Message ignored because address is in blacklist.')
 
                 blockMessage = True
         else:  # We're using a whitelist
@@ -599,7 +592,7 @@ def processmsg(self, data):
                 '''SELECT label FROM whitelist where address=? and enabled='1' ''',
                 fromAddress)
             if queryreturn == []:
-                print 'Message ignored because address not in whitelist.'
+                logger.info('Message ignored because address not in whitelist.')
                 blockMessage = True
         if not blockMessage:
             toLabel = shared.config.get(toAddress, 'label')
@@ -608,11 +601,12 @@ def processmsg(self, data):
 
             if messageEncodingType == 2:
                 subject, body = self.decodeType2Message(message)
+                logger.info('Message subject (first 100 characters): %s' % repr(subject)[:100])
             elif messageEncodingType == 1:
                 body = message
                 subject = ''
             elif messageEncodingType == 0:
-                print 'messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.'
+                logger.info('messageEncodingType == 0. Doing nothing with the message. They probably just sent it so that we would store their public key or send their ack data for them.') 
             else:
                 body = 'Unknown encoding type.\n\n' + repr(message)
                 subject = ''
@@ -682,9 +676,10 @@ def processmsg(self, data):
         sum = 0
         for item in shared.successfullyDecryptMessageTimings:
             sum += item
-        with shared.printLock:
-            print 'Time to decrypt this message successfully:', timeRequiredToAttemptToDecryptMessage
-            print 'Average time for all message decryption successes since startup:', sum / len(shared.successfullyDecryptMessageTimings)
+        logger.debug('Time to decrypt this message successfully: %s\n\
+                     Average time for all message decryption successes since startup: %s.' %
+                     (timeRequiredToAttemptToDecryptMessage, sum / len(shared.successfullyDecryptMessageTimings)) 
+                     )
 
 
     def processbroadcast(self, data):
@@ -708,7 +703,7 @@ def processbroadcast(self, data):
             data[readPosition:readPosition + 9])
         readPosition += broadcastVersionLength
         if broadcastVersion < 1 or broadcastVersion > 3:
-            print 'Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
+            logger.debug('Cannot decode incoming broadcast versions higher than 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.') 
             return
         if broadcastVersion == 1:
             beginningOfPubkeyPosition = readPosition  # used when we add the pubkey to our pubkey table
@@ -736,9 +731,7 @@ def processbroadcast(self, data):
                 sendersHash = data[readPosition:readPosition + 20]
                 if sendersHash not in shared.broadcastSendersForWhichImWatching:
                     # Display timing data
-                    with shared.printLock:
-                        print 'Time spent deciding that we are not interested in this v1 broadcast:', time.time() - messageProcessingStartTime
-
+                    logger.debug('Time spent deciding that we are not interested in this v1 broadcast: %s' % (time.time() - messageProcessingStartTime,))
                     return
                 # At this point, this message claims to be from sendersHash and
                 # we are interested in it. We still have to hash the public key
@@ -770,17 +763,16 @@ def processbroadcast(self, data):
                 signature = data[readPosition:readPosition + signatureLength]
                 try:
                     if not highlevelcrypto.verify(data[12:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
-                        print 'ECDSA verify failed'
+                        logger.debug('ECDSA verify failed')
                         return
-                    print 'ECDSA verify passed'
+                    logger.debug('ECDSA verify passed')
                 except Exception as err:
-                    print 'ECDSA verify failed', err
+                    logger.debug('ECDSA verify failed %s' % err)
                     return
                 # verify passed
                 fromAddress = encodeAddress(
                     sendersAddressVersion, sendersStream, ripe.digest())
-                with shared.printLock:
-                    print 'fromAddress:', fromAddress
+                logger.debug('fromAddress: %s' % fromAddress)
 
                 # Let's store the public key in case we want to reply to this person.
                 # We don't have the correct nonce or time (which would let us
@@ -803,11 +795,12 @@ def processbroadcast(self, data):
 
                 if messageEncodingType == 2:
                     subject, body = decodeType2Message(message)
+                    logger.info('Broadcast subject (first 100 characters): %s' % repr(subject)[:100])
                 elif messageEncodingType == 1:
                     body = message
                     subject = ''
                 elif messageEncodingType == 0:
-                    print 'messageEncodingType == 0. Doing nothing with the message.'
+                    logger.debug('messageEncodingType == 0. Doing nothing with the message.')
                 else:
                     body = 'Unknown encoding type.\n\n' + repr(message)
                     subject = ''
@@ -835,8 +828,7 @@ def processbroadcast(self, data):
                             call([apiNotifyPath, "newBroadcast"])
 
                 # Display timing data
-                with shared.printLock:
-                    print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
+                logger.debug('Time spent processing this interesting broadcast: %s' % (time.time() - messageProcessingStartTime,))
 
         if broadcastVersion == 2:
             cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
@@ -848,16 +840,14 @@ def processbroadcast(self, data):
                     decryptedData = cryptorObject.decrypt(data[readPosition:])
                     toRipe = key  # This is the RIPE hash of the sender's pubkey. We need this below to compare to the RIPE hash of the sender's address to verify that it was encrypted by with their key rather than some other key.
                     initialDecryptionSuccessful = True
-                    print 'EC decryption successful using key associated with ripe hash:', key.encode('hex')
+                    logger.info('EC decryption successful using key associated with ripe hash: %s' % key.encode('hex'))
                     break
                 except Exception as err:
                     pass
                     # print 'cryptorObject.decrypt Exception:', err
             if not initialDecryptionSuccessful:
                 # This is not a broadcast I am interested in.
-                with shared.printLock:
-                    print 'Length of time program spent failing to decrypt this v2 broadcast:', time.time() - messageProcessingStartTime, 'seconds.'
-
+                logger.debug('Length of time program spent failing to decrypt this v2 broadcast: %s seconds.' % (time.time() - messageProcessingStartTime,))
                 return
             # At this point this is a broadcast I have decrypted and thus am
             # interested in.
@@ -867,13 +857,13 @@ def processbroadcast(self, data):
             sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
             if sendersAddressVersion < 2 or sendersAddressVersion > 3:
-                print 'Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
+                logger.info('Cannot decode senderAddressVersion other than 2 or 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.')
                 return
             readPosition += sendersAddressVersionLength
             sendersStream, sendersStreamLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
             if sendersStream != cleartextStreamNumber:
-                print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
+                logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.') 
                 return
             readPosition += sendersStreamLength
             behaviorBitfield = decryptedData[readPosition:readPosition + 4]
@@ -888,11 +878,11 @@ def processbroadcast(self, data):
                 requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                     decryptedData[readPosition:readPosition + 10])
                 readPosition += varintLength
-                print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
+                logger.debug('sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s' % requiredAverageProofOfWorkNonceTrialsPerByte)
                 requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                     decryptedData[readPosition:readPosition + 10])
                 readPosition += varintLength
-                print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
+                logger.debug('sender\'s requiredPayloadLengthExtraBytes is %s' % requiredPayloadLengthExtraBytes)
             endOfPubkeyPosition = readPosition
 
             sha = hashlib.new('sha512')
@@ -901,7 +891,7 @@ def processbroadcast(self, data):
             ripe.update(sha.digest())
 
             if toRipe != ripe.digest():
-                print 'The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
+                logger.info('The encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.') 
                 return
             messageEncodingType, messageEncodingTypeLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
@@ -921,11 +911,11 @@ def processbroadcast(self, data):
                 readPosition:readPosition + signatureLength]
             try:
                 if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
-                    print 'ECDSA verify failed'
+                    logger.debug('ECDSA verify failed')
                     return
-                print 'ECDSA verify passed'
+                logger.debug('ECDSA verify passed')
             except Exception as err:
-                print 'ECDSA verify failed', err
+                logger.debug('ECDSA verify failed %s' % err)
                 return
             # verify passed
 
@@ -950,11 +940,12 @@ def processbroadcast(self, data):
 
             if messageEncodingType == 2:
                 subject, body = self.decodeType2Message(message)
+                logger.info('Broadcast subject (first 100 characters): %s' % repr(subject)[:100])
             elif messageEncodingType == 1:
                 body = message
                 subject = ''
             elif messageEncodingType == 0:
-                print 'messageEncodingType == 0. Doing nothing with the message.'
+                logger.info('messageEncodingType == 0. Doing nothing with the message.')
             else:
                 body = 'Unknown encoding type.\n\n' + repr(message)
                 subject = ''
@@ -982,8 +973,7 @@ def processbroadcast(self, data):
                         call([apiNotifyPath, "newBroadcast"])
 
             # Display timing data
-            with shared.printLock:
-                print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
+            logger.info('Time spent processing this interesting broadcast: %s' % (time.time() - messageProcessingStartTime,))
 
         if broadcastVersion == 3:
             cleartextStreamNumber, cleartextStreamNumberLength = decodeVarint(
@@ -992,17 +982,15 @@ def processbroadcast(self, data):
             embeddedTag = data[readPosition:readPosition+32]
             readPosition += 32
             if embeddedTag not in shared.MyECSubscriptionCryptorObjects:
-                with shared.printLock:
-                    print 'We\'re not interested in this broadcast.'
+                logger.debug('We\'re not interested in this broadcast.') 
                 return
             # We are interested in this broadcast because of its tag.
             cryptorObject = shared.MyECSubscriptionCryptorObjects[embeddedTag]
             try:
                 decryptedData = cryptorObject.decrypt(data[readPosition:])
-                print 'EC decryption successful'
+                logger.debug('EC decryption successful')
             except Exception as err:
-                with shared.printLock:
-                    print 'Broadcast version 3 decryption Unsuccessful.'
+                logger.debug('Broadcast version 3 decryption Unsuccessful.') 
                 return
 
             signedBroadcastVersion, readPosition = decodeVarint(
@@ -1011,13 +999,13 @@ def processbroadcast(self, data):
             sendersAddressVersion, sendersAddressVersionLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
             if sendersAddressVersion < 4:
-                print 'Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.'
+                logger.info('Cannot decode senderAddressVersion less than 4 for broadcast version number 3. Assuming the sender isn\'t being silly, you should upgrade Bitmessage because this message shall be ignored.') 
                 return
             readPosition += sendersAddressVersionLength
             sendersStream, sendersStreamLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
             if sendersStream != cleartextStreamNumber:
-                print 'The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.'
+                logger.info('The stream number outside of the encryption on which the POW was completed doesn\'t match the stream number inside the encryption. Ignoring broadcast.') 
                 return
             readPosition += sendersStreamLength
             behaviorBitfield = decryptedData[readPosition:readPosition + 4]
@@ -1032,11 +1020,11 @@ def processbroadcast(self, data):
                 requiredAverageProofOfWorkNonceTrialsPerByte, varintLength = decodeVarint(
                     decryptedData[readPosition:readPosition + 10])
                 readPosition += varintLength
-                print 'sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is', requiredAverageProofOfWorkNonceTrialsPerByte
+                logger.debug('sender\'s requiredAverageProofOfWorkNonceTrialsPerByte is %s' % requiredAverageProofOfWorkNonceTrialsPerByte)
                 requiredPayloadLengthExtraBytes, varintLength = decodeVarint(
                     decryptedData[readPosition:readPosition + 10])
                 readPosition += varintLength
-                print 'sender\'s requiredPayloadLengthExtraBytes is', requiredPayloadLengthExtraBytes
+                logger.debug('sender\'s requiredPayloadLengthExtraBytes is %s' % requiredPayloadLengthExtraBytes)
             endOfPubkeyPosition = readPosition
 
             sha = hashlib.new('sha512')
@@ -1048,7 +1036,7 @@ def processbroadcast(self, data):
             calculatedTag = hashlib.sha512(hashlib.sha512(encodeVarint(
                 sendersAddressVersion) + encodeVarint(sendersStream) + calculatedRipe).digest()).digest()[32:]
             if calculatedTag != embeddedTag:
-                print 'The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.'
+                logger.debug('The tag and encryption key used to encrypt this message doesn\'t match the keys inbedded in the message itself. Ignoring message.') 
                 return
             messageEncodingType, messageEncodingTypeLength = decodeVarint(
                 decryptedData[readPosition:readPosition + 9])
@@ -1068,18 +1056,17 @@ def processbroadcast(self, data):
                 readPosition:readPosition + signatureLength]
             try:
                 if not highlevelcrypto.verify(decryptedData[:readPositionAtBottomOfMessage], signature, sendersPubSigningKey.encode('hex')):
-                    print 'ECDSA verify failed'
+                    logger.debug('ECDSA verify failed')
                     return
-                print 'ECDSA verify passed'
+                logger.debug('ECDSA verify passed')
             except Exception as err:
-                print 'ECDSA verify failed', err
+                logger.debug('ECDSA verify failed %s' % err)
                 return
             # verify passed
 
             fromAddress = encodeAddress(
                 sendersAddressVersion, sendersStream, calculatedRipe)
-            with shared.printLock:
-                print 'fromAddress:', fromAddress
+            logger.info('fromAddress: %s' % fromAddress)
 
             # Let's store the public key in case we want to reply to this person.
             sqlExecute(
@@ -1096,11 +1083,12 @@ def processbroadcast(self, data):
 
             if messageEncodingType == 2:
                 subject, body = self.decodeType2Message(message)
+                logger.info('Broadcast subject (first 100 characters): %s' % repr(subject)[:100])
             elif messageEncodingType == 1:
                 body = message
                 subject = ''
             elif messageEncodingType == 0:
-                print 'messageEncodingType == 0. Doing nothing with the message.'
+                logger.info('messageEncodingType == 0. Doing nothing with the message.')
             else:
                 body = 'Unknown encoding type.\n\n' + repr(message)
                 subject = ''
@@ -1128,9 +1116,7 @@ def processbroadcast(self, data):
                         call([apiNotifyPath, "newBroadcast"])
 
             # Display timing data
-            with shared.printLock:
-                print 'Time spent processing this interesting broadcast:', time.time() - messageProcessingStartTime
-
+            logger.debug('Time spent processing this interesting broadcast: %s' % (time.time() - messageProcessingStartTime,))
 
     # We have inserted a pubkey into our pubkey table which we received from a
     # pubkey, msg, or broadcast message. It might be one that we have been
@@ -1139,15 +1125,14 @@ def possibleNewPubkey(self, ripe=None, address=None):
         # For address versions <= 3, we wait on a key with the correct ripe hash
         if ripe != None:
             if ripe in shared.neededPubkeys:
-                print 'We have been awaiting the arrival of this pubkey.'
+                logger.info('We have been awaiting the arrival of this pubkey.')
                 del shared.neededPubkeys[ripe]
                 sqlExecute(
                     '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
                     ripe)
                 shared.workerQueue.put(('sendmessage', ''))
             else:
-                with shared.printLock:
-                    print 'We don\'t need this pub key. We didn\'t ask for it. Pubkey hash:', ripe.encode('hex')
+                logger.debug('We don\'t need this pub key. We didn\'t ask for it. Pubkey hash: %s' % ripe.encode('hex'))
         # For address versions >= 4, we wait on a pubkey with the correct tag.
         # Let us create the tag from the address and see if we were waiting
         # for it.
@@ -1156,7 +1141,7 @@ def possibleNewPubkey(self, ripe=None, address=None):
             tag = hashlib.sha512(hashlib.sha512(encodeVarint(
                 addressVersion) + encodeVarint(streamNumber) + ripe).digest()).digest()[32:]
             if tag in shared.neededPubkeys:
-                print 'We have been awaiting the arrival of this pubkey.'
+                logger.info('We have been awaiting the arrival of this pubkey.')
                 del shared.neededPubkeys[tag]
                 sqlExecute(
                     '''UPDATE sent SET status='doingmsgpow' WHERE toripe=? AND (status='awaitingpubkey' or status='doingpubkeypow') and folder='sent' ''',
@@ -1165,17 +1150,17 @@ def possibleNewPubkey(self, ripe=None, address=None):
 
     def ackDataHasAVaildHeader(self, ackData):
         if len(ackData) < 24:
-            print 'The length of ackData is unreasonably short. Not sending ackData.'
+            logger.info('The length of ackData is unreasonably short. Not sending ackData.')
             return False
         if ackData[0:4] != '\xe9\xbe\xb4\xd9':
-            print 'Ackdata magic bytes were wrong. Not sending ackData.'
+            logger.info('Ackdata magic bytes were wrong. Not sending ackData.')
             return False
         ackDataPayloadLength, = unpack('>L', ackData[16:20])
         if len(ackData) - 24 != ackDataPayloadLength:
-            print 'ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.'
+            logger.info('ackData payload length doesn\'t match the payload length specified in the header. Not sending ackdata.')
             return False
         if ackData[20:24] != hashlib.sha512(ackData[24:]).digest()[0:4]:  # test the checksum in the message.
-            print 'ackdata checksum wrong. Not sending ackdata.'
+            logger.info('ackdata checksum wrong. Not sending ackdata.')
             return False
         if ackDataPayloadLength > 180000000: # If the size of the message is greater than 180MB, ignore it.
             return False
diff --git a/src/shared.py b/src/shared.py
--- a/src/shared.py
+++ b/src/shared.py
@@ -290,7 +290,6 @@ def isProofOfWorkSufficient(
         payloadLengthExtraBytes = networkDefaultPayloadLengthExtraBytes
     POW, = unpack('>Q', hashlib.sha512(hashlib.sha512(data[
                   :8] + hashlib.sha512(data[8:]).digest()).digest()).digest()[0:8])
-    # print 'POW:', POW
     return POW <= 2 ** 64 / ((len(data) + payloadLengthExtraBytes) * (nonceTrialsPerByte))
 
 def doCleanShutdown():
@@ -431,15 +430,13 @@ def decryptAndCheckPubkeyPayload(payload, address):
     embeddedVersionNumber, varintLength = decodeVarint(
         payload[readPosition:readPosition + 10])
     if embeddedVersionNumber != addressVersion:
-        with shared.printLock:
-            print 'Pubkey decryption was UNsuccessful due to address version mismatch. This shouldn\'t have happened.'
+        logger.info('Pubkey decryption was UNsuccessful due to address version mismatch. This shouldn\'t have happened.')
         return 'failed'
     readPosition += varintLength
     embeddedStreamNumber, varintLength = decodeVarint(
         payload[readPosition:readPosition + 10])
     if embeddedStreamNumber != streamNumber:
-        with shared.printLock:
-            print 'Pubkey decryption was UNsuccessful due to stream number mismatch. This shouldn\'t have happened.'
+        logger.info('Pubkey decryption was UNsuccessful due to stream number mismatch. This shouldn\'t have happened.')
         return 'failed'
     readPosition += varintLength
     signedData = payload[8:readPosition] # Some of the signed data is not encrypted so let's keep it for now.
@@ -454,10 +451,9 @@ def decryptAndCheckPubkeyPayload(payload, address):
     except:
         # Someone must have encrypted some data with a different key
         # but tagged it with a tag for which we are watching.
-        with shared.printLock:
-            print 'Pubkey decryption was UNsuccessful. This shouldn\'t have happened.'
+        logger.info('Pubkey decryption was UNsuccessful. This shouldn\'t have happened.')
         return 'failed'
-    print 'Pubkey decryption successful'
+    logger.debug('Pubkey decryption successful')
     readPosition = 4 # bypass the behavior bitfield
     publicSigningKey = '\x04' + decryptedData[readPosition:readPosition + 64]
     # Is it possible for a public key to be invalid such that trying to
@@ -479,11 +475,11 @@ def decryptAndCheckPubkeyPayload(payload, address):
     signature = decryptedData[readPosition:readPosition + signatureLength]
     try:
         if not highlevelcrypto.verify(signedData, signature, publicSigningKey.encode('hex')):
-            print 'ECDSA verify failed (within decryptAndCheckPubkeyPayload).'
+            logger.info('ECDSA verify failed (within decryptAndCheckPubkeyPayload).')
             return 'failed'
-        print 'ECDSA verify passed (within decryptAndCheckPubkeyPayload)'
+        logger.debug('ECDSA verify passed (within decryptAndCheckPubkeyPayload)')
     except Exception as err:
-        print 'ECDSA verify failed (within decryptAndCheckPubkeyPayload)', err
+        logger.debug('ECDSA verify failed (within decryptAndCheckPubkeyPayload) %s' % err)
         return 'failed'
 
     sha = hashlib.new('sha512')
@@ -496,8 +492,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
         # Although this pubkey object had the tag were were looking for and was
         # encrypted with the correct encryption key, it doesn't contain the
         # correct keys. Someone is either being malicious or using buggy software.
-        with shared.printLock:
-            print 'Pubkey decryption was UNsuccessful due to RIPE mismatch. This shouldn\'t have happened.'
+        logger.info('Pubkey decryption was UNsuccessful due to RIPE mismatch. This shouldn\'t have happened.')
         return 'failed'
     
     t = (ripe, addressVersion, signedData, int(time.time()), 'yes')
@@ -509,7 +504,7 @@ def decryptAndCheckPubkeyPayload(payload, address):
 def checkAndShareMsgWithPeers(data):
     # Let us check to make sure that the proof of work is sufficient.
     if not isProofOfWorkSufficient(data):
-        print 'Proof of work in msg message insufficient.'
+        logger.debug('Proof of work in msg message insufficient.')
         return
 
     readPosition = 8
@@ -523,21 +518,27 @@ def checkAndShareMsgWithPeers(data):
     else:
         readPosition += 4
 
+    if embeddedTime > (int(time.time()) + 10800): 
+        logger.debug('The embedded time in this msg message is more than three hours in the future. That doesn\'t make sense. Ignoring message.')
+        return
+    if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept):
+        logger.debug('The embedded time in this msg message is too old. Ignoring message.')
+        return
     streamNumberAsClaimedByMsg, streamNumberAsClaimedByMsgLength = decodeVarint(
         data[readPosition:readPosition + 9])
     if not streamNumberAsClaimedByMsg in streamsInWhichIAmParticipating:
-        print 'The streamNumber', streamNumberAsClaimedByMsg, 'isn\'t one we are interested in.'
+        logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumberAsClaimedByMsg)
         return
     readPosition += streamNumberAsClaimedByMsgLength
     inventoryHash = calculateInventoryHash(data)
     shared.numberOfInventoryLookupsPerformed += 1
     inventoryLock.acquire()
     if inventoryHash in inventory:
-        print 'We have already received this msg message. Ignoring.'
+        logger.debug('We have already received this msg message. Ignoring.')
         inventoryLock.release()
         return
     elif isInSqlInventory(inventoryHash):
-        print 'We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.'
+        logger.debug('We have already received this msg message (it is stored on disk in the SQL inventory). Ignoring it.')
         inventoryLock.release()
         return
     # This msg message is valid. Let's let our peers know about it.
@@ -546,8 +547,7 @@ def checkAndShareMsgWithPeers(data):
         objectType, streamNumberAsClaimedByMsg, data, embeddedTime,'')
     inventorySets[streamNumberAsClaimedByMsg].add(inventoryHash)
     inventoryLock.release()
-    with printLock:
-        print 'advertising inv with hash:', inventoryHash.encode('hex')
+    logger.debug('advertising inv with hash: %s' % inventoryHash.encode('hex'))
     broadcastToSendDataQueues((streamNumberAsClaimedByMsg, 'advertiseobject', inventoryHash))
 
     # Now let's enqueue it to be processed ourselves.
@@ -560,10 +560,10 @@ def checkAndShareMsgWithPeers(data):
 
 def checkAndSharegetpubkeyWithPeers(data):
     if not isProofOfWorkSufficient(data):
-        print 'Proof of work in getpubkey message insufficient.'
+        logger.debug('Proof of work in getpubkey message insufficient.')
         return
     if len(data) < 34:
-        print 'getpubkey message doesn\'t contain enough data. Ignoring.'
+        logger.debug('getpubkey message doesn\'t contain enough data. Ignoring.')
         return
     readPosition = 8  # bypass the nonce
     embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
@@ -577,10 +577,10 @@ def checkAndSharegetpubkeyWithPeers(data):
         readPosition += 4
 
     if embeddedTime > int(time.time()) + 10800:
-        print 'The time in this getpubkey message is too new. Ignoring it. Time:', embeddedTime
+        logger.debug('The time in this getpubkey message is too new. Ignoring it. Time: %s' % embeddedTime)
         return
     if embeddedTime < int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept:
-        print 'The time in this getpubkey message is too old. Ignoring it. Time:', embeddedTime
+        logger.debug('The time in this getpubkey message is too old. Ignoring it. Time: %s' % embeddedTime)
         return
     requestedAddressVersionNumber, addressVersionLength = decodeVarint(
         data[readPosition:readPosition + 10])
@@ -588,7 +588,7 @@ def checkAndSharegetpubkeyWithPeers(data):
     streamNumber, streamNumberLength = decodeVarint(
         data[readPosition:readPosition + 10])
     if not streamNumber in streamsInWhichIAmParticipating:
-        print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
+        logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
         return
     readPosition += streamNumberLength
 
@@ -596,11 +596,11 @@ def checkAndSharegetpubkeyWithPeers(data):
     inventoryHash = calculateInventoryHash(data)
     inventoryLock.acquire()
     if inventoryHash in inventory:
-        print 'We have already received this getpubkey request. Ignoring it.'
+        logger.debug('We have already received this getpubkey request. Ignoring it.')
         inventoryLock.release()
         return
     elif isInSqlInventory(inventoryHash):
-        print 'We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.'
+        logger.debug('We have already received this getpubkey request (it is stored on disk in the SQL inventory). Ignoring it.')
         inventoryLock.release()
         return
 
@@ -610,8 +610,7 @@ def checkAndSharegetpubkeyWithPeers(data):
     inventorySets[streamNumber].add(inventoryHash)
     inventoryLock.release()
     # This getpubkey request is valid. Forward to peers.
-    with printLock:
-        print 'advertising inv with hash:', inventoryHash.encode('hex')
+    logger.debug('advertising inv with hash: %s' % inventoryHash.encode('hex'))
     broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
 
     # Now let's queue it to be processed ourselves.
@@ -627,7 +626,7 @@ def checkAndSharePubkeyWithPeers(data):
         return
     # Let us make sure that the proof of work is sufficient.
     if not isProofOfWorkSufficient(data):
-        print 'Proof of work in pubkey message insufficient.'
+        logger.debug('Proof of work in pubkey message insufficient.')
         return
 
     readPosition = 8  # for the nonce
@@ -642,12 +641,10 @@ def checkAndSharePubkeyWithPeers(data):
         readPosition += 4
 
     if embeddedTime < int(time.time()) - lengthOfTimeToHoldOnToAllPubkeys:
-        with printLock:
-            print 'The embedded time in this pubkey message is too old. Ignoring. Embedded time is:', embeddedTime
+        logger.debug('The embedded time in this pubkey message is too old. Ignoring. Embedded time is: %s' % embeddedTime)
         return
     if embeddedTime > int(time.time()) + 10800:
-        with printLock:
-            print 'The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.'
+        logger.debug('The embedded time in this pubkey message more than several hours in the future. This is irrational. Ignoring message.') 
         return
     addressVersion, varintLength = decodeVarint(
         data[readPosition:readPosition + 10])
@@ -656,11 +653,11 @@ def checkAndSharePubkeyWithPeers(data):
         data[readPosition:readPosition + 10])
     readPosition += varintLength
     if not streamNumber in streamsInWhichIAmParticipating:
-        print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
+        logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
         return
     if addressVersion >= 4:
         tag = data[readPosition:readPosition + 32]
-        print 'tag in received pubkey is:', tag.encode('hex')
+        logger.debug('tag in received pubkey is: %s' % tag.encode('hex'))
     else:
         tag = ''
 
@@ -668,11 +665,11 @@ def checkAndSharePubkeyWithPeers(data):
     inventoryHash = calculateInventoryHash(data)
     inventoryLock.acquire()
     if inventoryHash in inventory:
-        print 'We have already received this pubkey. Ignoring it.'
+        logger.debug('We have already received this pubkey. Ignoring it.')
         inventoryLock.release()
         return
     elif isInSqlInventory(inventoryHash):
-        print 'We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.'
+        logger.debug('We have already received this pubkey (it is stored on disk in the SQL inventory). Ignoring it.')
         inventoryLock.release()
         return
     objectType = 'pubkey'
@@ -681,8 +678,7 @@ def checkAndSharePubkeyWithPeers(data):
     inventorySets[streamNumber].add(inventoryHash)
     inventoryLock.release()
     # This object is valid. Forward it to peers.
-    with printLock:
-        print 'advertising inv with hash:', inventoryHash.encode('hex')
+    logger.debug('advertising inv with hash: %s' % inventoryHash.encode('hex'))
     broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
 
 
@@ -698,7 +694,7 @@ def checkAndSharePubkeyWithPeers(data):
 def checkAndShareBroadcastWithPeers(data):
     # Let us verify that the proof of work is sufficient.
     if not isProofOfWorkSufficient(data):
-        print 'Proof of work in broadcast message insufficient.'
+        logger.debug('Proof of work in broadcast message insufficient.')
         return
     readPosition = 8  # bypass the nonce
     embeddedTime, = unpack('>I', data[readPosition:readPosition + 4])
@@ -712,13 +708,13 @@ def checkAndShareBroadcastWithPeers(data):
         readPosition += 4
 
     if embeddedTime > (int(time.time()) + 10800):  # prevent funny business
-        print 'The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.'
+        logger.debug('The embedded time in this broadcast message is more than three hours in the future. That doesn\'t make sense. Ignoring message.') 
         return
     if embeddedTime < (int(time.time()) - maximumAgeOfAnObjectThatIAmWillingToAccept):
-        print 'The embedded time in this broadcast message is too old. Ignoring message.'
+        logger.debug('The embedded time in this broadcast message is too old. Ignoring message.')
         return
     if len(data) < 180:
-        print 'The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.'
+        logger.debug('The payload length of this broadcast packet is unreasonably low. Someone is probably trying funny business. Ignoring message.')
         return
     broadcastVersion, broadcastVersionLength = decodeVarint(
         data[readPosition:readPosition + 10])
@@ -727,22 +723,21 @@ def checkAndShareBroadcastWithPeers(data):
         streamNumber, streamNumberLength = decodeVarint(data[readPosition:readPosition + 10])
         readPosition += streamNumberLength
         if not streamNumber in streamsInWhichIAmParticipating:
-            print 'The streamNumber', streamNumber, 'isn\'t one we are interested in.'
+            logger.debug('The streamNumber %s isn\'t one we are interested in.' % streamNumber)
             return
     if broadcastVersion >= 3:
         tag = data[readPosition:readPosition+32]
-        print 'debugging. in broadcast, tag is:', tag.encode('hex')
     else:
         tag = ''
     shared.numberOfInventoryLookupsPerformed += 1
     inventoryLock.acquire()
     inventoryHash = calculateInventoryHash(data)
     if inventoryHash in inventory:
-        print 'We have already received this broadcast object. Ignoring.'
+        logger.debug('We have already received this broadcast object. Ignoring.')
         inventoryLock.release()
         return
     elif isInSqlInventory(inventoryHash):
-        print 'We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.'
+        logger.debug('We have already received this broadcast object (it is stored on disk in the SQL inventory). Ignoring it.')
         inventoryLock.release()
         return
     # It is valid. Let's let our peers know about it.
@@ -752,8 +747,7 @@ def checkAndShareBroadcastWithPeers(data):
     inventorySets[streamNumber].add(inventoryHash)
     inventoryLock.release()
     # This object is valid. Forward it to peers.
-    with printLock:
-        print 'advertising inv with hash:', inventoryHash.encode('hex')
+    logger.debug('advertising inv with hash: %s' % inventoryHash.encode('hex'))
     broadcastToSendDataQueues((streamNumber, 'advertiseobject', inventoryHash))
 
     # Now let's queue it to be processed ourselves.


Test patch: