2018-04-16 20:19:30 +02:00
|
|
|
"""
|
2018-05-08 16:01:20 +02:00
|
|
|
Tests for core and those that do not work outside
|
|
|
|
(because of import error for example)
|
2018-04-16 20:19:30 +02:00
|
|
|
"""
|
|
|
|
|
2018-10-03 17:42:12 +02:00
|
|
|
import os
|
|
|
|
import pickle # nosec
|
|
|
|
import Queue
|
2018-05-08 16:39:07 +02:00
|
|
|
import random # nosec
|
2020-12-19 09:48:58 +01:00
|
|
|
import shutil
|
2020-01-30 15:49:34 +01:00
|
|
|
import socket
|
2018-05-08 16:01:20 +02:00
|
|
|
import string
|
2020-10-12 13:58:16 +02:00
|
|
|
import sys
|
2018-10-03 17:42:12 +02:00
|
|
|
import time
|
2018-04-16 10:26:52 +02:00
|
|
|
import unittest
|
|
|
|
|
2020-05-15 12:49:59 +02:00
|
|
|
import protocol
|
2018-10-03 17:42:12 +02:00
|
|
|
import state
|
2020-11-05 08:40:54 +01:00
|
|
|
import helper_sent
|
2020-12-23 20:42:18 +01:00
|
|
|
import helper_addressbook
|
2020-11-05 08:40:54 +01:00
|
|
|
|
2019-07-29 13:19:18 +02:00
|
|
|
from bmconfigparser import BMConfigParser
|
2018-05-08 16:01:20 +02:00
|
|
|
from helper_msgcoding import MsgEncode, MsgDecode
|
2019-10-21 14:20:29 +02:00
|
|
|
from helper_startup import start_proxyconfig
|
2020-11-16 14:20:28 +01:00
|
|
|
from helper_sql import sqlQuery
|
2020-07-16 16:05:32 +02:00
|
|
|
from network import asyncore_pollchoose as asyncore, knownnodes
|
2020-05-15 12:49:59 +02:00
|
|
|
from network.bmproto import BMProto
|
2019-07-29 13:19:18 +02:00
|
|
|
from network.connectionpool import BMConnectionPool
|
2020-05-15 12:49:59 +02:00
|
|
|
from network.node import Node, Peer
|
2019-07-29 13:19:18 +02:00
|
|
|
from network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
2018-10-03 17:42:12 +02:00
|
|
|
from queues import excQueue
|
2020-05-15 12:49:59 +02:00
|
|
|
from version import softwareVersion
|
2018-10-03 17:42:12 +02:00
|
|
|
|
2020-10-28 17:01:55 +01:00
|
|
|
from common import cleanup
|
|
|
|
|
2019-10-21 14:20:29 +02:00
|
|
|
try:
|
|
|
|
import stem.version as stem_version
|
|
|
|
except ImportError:
|
|
|
|
stem_version = None
|
|
|
|
|
2018-10-03 17:42:12 +02:00
|
|
|
knownnodes_file = os.path.join(state.appdata, 'knownnodes.dat')
|
|
|
|
|
|
|
|
|
|
|
|
def pickle_knownnodes():
|
2019-09-26 13:24:59 +02:00
|
|
|
"""Generate old style pickled knownnodes.dat"""
|
2018-10-03 17:42:12 +02:00
|
|
|
now = time.time()
|
|
|
|
with open(knownnodes_file, 'wb') as dst:
|
|
|
|
pickle.dump({
|
|
|
|
stream: {
|
2019-11-03 16:11:52 +01:00
|
|
|
Peer(
|
2018-10-03 17:42:12 +02:00
|
|
|
'%i.%i.%i.%i' % tuple([
|
|
|
|
random.randint(1, 255) for i in range(4)]),
|
|
|
|
8444): {'lastseen': now, 'rating': 0.1}
|
|
|
|
for i in range(1, 4) # 3 test nodes
|
|
|
|
}
|
|
|
|
for stream in range(1, 4) # 3 test streams
|
|
|
|
}, dst)
|
|
|
|
|
|
|
|
|
2018-04-16 10:26:52 +02:00
|
|
|
class TestCore(unittest.TestCase):
|
2018-05-08 16:01:20 +02:00
|
|
|
"""Test case, which runs in main pybitmessage thread"""
|
2020-12-23 20:42:18 +01:00
|
|
|
addr = 'BM-2cVvkzJuQDsQHLqxRXc6HZGPLZnkBLzEZY'
|
2018-05-08 16:01:20 +02:00
|
|
|
|
|
|
|
def test_msgcoding(self):
|
|
|
|
"""test encoding and decoding (originally from helper_msgcoding)"""
|
|
|
|
msg_data = {
|
|
|
|
'subject': ''.join(
|
2018-05-08 16:39:07 +02:00
|
|
|
random.choice(string.ascii_lowercase + string.digits) # nosec
|
2018-05-08 16:01:20 +02:00
|
|
|
for _ in range(40)),
|
|
|
|
'body': ''.join(
|
2018-05-08 16:39:07 +02:00
|
|
|
random.choice(string.ascii_lowercase + string.digits) # nosec
|
2018-05-08 16:01:20 +02:00
|
|
|
for _ in range(10000))
|
|
|
|
}
|
|
|
|
|
|
|
|
obj1 = MsgEncode(msg_data, 1)
|
|
|
|
obj2 = MsgEncode(msg_data, 2)
|
|
|
|
obj3 = MsgEncode(msg_data, 3)
|
|
|
|
# print "1: %i 2: %i 3: %i" % (
|
|
|
|
# len(obj1.data), len(obj2.data), len(obj3.data))
|
|
|
|
|
|
|
|
obj1e = MsgDecode(1, obj1.data)
|
|
|
|
# no subject in trivial encoding
|
|
|
|
self.assertEqual(msg_data['body'], obj1e.body)
|
|
|
|
|
|
|
|
obj2e = MsgDecode(2, obj2.data)
|
|
|
|
self.assertEqual(msg_data['subject'], obj2e.subject)
|
|
|
|
self.assertEqual(msg_data['body'], obj2e.body)
|
|
|
|
|
|
|
|
obj3e = MsgDecode(3, obj3.data)
|
|
|
|
self.assertEqual(msg_data['subject'], obj3e.subject)
|
|
|
|
self.assertEqual(msg_data['body'], obj3e.body)
|
2018-04-16 10:26:52 +02:00
|
|
|
|
2019-07-05 10:45:12 +02:00
|
|
|
try:
|
|
|
|
MsgEncode({'body': 'A msg with no subject'}, 3)
|
|
|
|
except Exception as e:
|
|
|
|
self.fail(
|
2019-07-10 12:23:10 +02:00
|
|
|
'Exception %s while trying to encode message'
|
2019-07-05 10:45:12 +02:00
|
|
|
' with no subject!' % e
|
|
|
|
)
|
|
|
|
|
2019-07-29 13:19:18 +02:00
|
|
|
@unittest.skip('Bad environment for asyncore.loop')
|
2019-07-10 12:23:10 +02:00
|
|
|
def test_tcpconnection(self):
|
|
|
|
"""initial fill script from network.tcp"""
|
2019-07-29 13:19:18 +02:00
|
|
|
BMConfigParser().set('bitmessagesettings', 'dontconnect', 'true')
|
2019-07-10 12:23:10 +02:00
|
|
|
try:
|
2019-11-03 16:11:52 +01:00
|
|
|
for peer in (Peer("127.0.0.1", 8448),):
|
2019-07-10 12:23:10 +02:00
|
|
|
direct = TCPConnection(peer)
|
|
|
|
while asyncore.socket_map:
|
|
|
|
print("loop, state = %s" % direct.state)
|
|
|
|
asyncore.loop(timeout=10, count=1)
|
|
|
|
except:
|
|
|
|
self.fail('Exception in test loop')
|
|
|
|
|
2019-07-29 13:19:18 +02:00
|
|
|
@staticmethod
|
|
|
|
def _wipe_knownnodes():
|
2018-10-03 17:42:12 +02:00
|
|
|
with knownnodes.knownNodesLock:
|
|
|
|
knownnodes.knownNodes = {stream: {} for stream in range(1, 4)}
|
|
|
|
|
2019-07-29 13:19:18 +02:00
|
|
|
@staticmethod
|
|
|
|
def _outdate_knownnodes():
|
|
|
|
with knownnodes.knownNodesLock:
|
|
|
|
for nodes in knownnodes.knownNodes.itervalues():
|
|
|
|
for node in nodes.itervalues():
|
|
|
|
node['lastseen'] -= 2419205 # older than 28 days
|
|
|
|
|
2018-10-03 17:42:12 +02:00
|
|
|
def test_knownnodes_pickle(self):
|
|
|
|
"""ensure that 3 nodes was imported for each stream"""
|
|
|
|
pickle_knownnodes()
|
|
|
|
self._wipe_knownnodes()
|
|
|
|
knownnodes.readKnownNodes()
|
|
|
|
for nodes in knownnodes.knownNodes.itervalues():
|
|
|
|
self_count = n = 0
|
|
|
|
for n, node in enumerate(nodes.itervalues()):
|
|
|
|
if node.get('self'):
|
|
|
|
self_count += 1
|
|
|
|
self.assertEqual(n - self_count, 2)
|
|
|
|
|
|
|
|
def test_knownnodes_default(self):
|
|
|
|
"""test adding default knownnodes if nothing loaded"""
|
2020-10-28 17:01:55 +01:00
|
|
|
cleanup(files=('knownnodes.dat',))
|
2018-10-03 17:42:12 +02:00
|
|
|
self._wipe_knownnodes()
|
|
|
|
knownnodes.readKnownNodes()
|
|
|
|
self.assertGreaterEqual(
|
|
|
|
len(knownnodes.knownNodes[1]), len(knownnodes.DEFAULT_NODES))
|
|
|
|
|
|
|
|
def test_0_cleaner(self):
|
|
|
|
"""test knownnodes starvation leading to IndexError in Asyncore"""
|
2019-07-29 13:19:18 +02:00
|
|
|
self._outdate_knownnodes()
|
2018-10-11 15:34:57 +02:00
|
|
|
# time.sleep(303) # singleCleaner wakes up every 5 min
|
|
|
|
knownnodes.cleanupKnownNodes()
|
2019-08-09 16:15:00 +02:00
|
|
|
self.assertTrue(knownnodes.knownNodes[1])
|
2018-10-03 17:42:12 +02:00
|
|
|
while True:
|
|
|
|
try:
|
|
|
|
thread, exc = excQueue.get(block=False)
|
|
|
|
except Queue.Empty:
|
|
|
|
return
|
|
|
|
if thread == 'Asyncore' and isinstance(exc, IndexError):
|
|
|
|
self.fail("IndexError because of empty knownNodes!")
|
|
|
|
|
2019-08-09 16:15:00 +02:00
|
|
|
def _initiate_bootstrap(self):
|
2019-07-29 13:19:18 +02:00
|
|
|
BMConfigParser().set('bitmessagesettings', 'dontconnect', 'true')
|
|
|
|
self._outdate_knownnodes()
|
2019-11-03 16:11:52 +01:00
|
|
|
knownnodes.addKnownNode(1, Peer('127.0.0.1', 8444), is_self=True)
|
2019-08-09 16:15:00 +02:00
|
|
|
knownnodes.cleanupKnownNodes()
|
|
|
|
time.sleep(2)
|
|
|
|
|
2020-01-30 15:49:34 +01:00
|
|
|
def _check_connection(self):
|
|
|
|
"""
|
|
|
|
Check if there is at least one outbound connection to remote host
|
|
|
|
with name not starting with "bootstrap" in 3 minutes,
|
|
|
|
fail otherwise.
|
|
|
|
"""
|
2019-08-09 16:15:00 +02:00
|
|
|
_started = time.time()
|
2019-07-29 13:19:18 +02:00
|
|
|
BMConfigParser().remove_option('bitmessagesettings', 'dontconnect')
|
|
|
|
proxy_type = BMConfigParser().safeGet(
|
|
|
|
'bitmessagesettings', 'socksproxytype')
|
|
|
|
if proxy_type == 'SOCKS5':
|
|
|
|
connection_base = Socks5BMConnection
|
|
|
|
elif proxy_type == 'SOCKS4a':
|
|
|
|
connection_base = Socks4aBMConnection
|
|
|
|
else:
|
|
|
|
connection_base = TCPConnection
|
|
|
|
for _ in range(180):
|
|
|
|
time.sleep(1)
|
|
|
|
for peer, con in BMConnectionPool().outboundConnections.iteritems():
|
|
|
|
if not peer.host.startswith('bootstrap'):
|
|
|
|
self.assertIsInstance(con, connection_base)
|
2019-08-09 16:15:00 +02:00
|
|
|
self.assertNotEqual(peer.host, '127.0.0.1')
|
2019-07-29 13:19:18 +02:00
|
|
|
return
|
2019-10-21 14:20:29 +02:00
|
|
|
self.fail(
|
|
|
|
'Failed to connect during %s sec' % (time.time() - _started))
|
|
|
|
|
2020-01-30 15:49:34 +01:00
|
|
|
def test_connection(self):
|
|
|
|
"""test connection to bootstrap servers"""
|
|
|
|
self._initiate_bootstrap()
|
|
|
|
for port in [8080, 8444]:
|
|
|
|
for item in socket.getaddrinfo(
|
|
|
|
'bootstrap%s.bitmessage.org' % port, 80):
|
|
|
|
try:
|
|
|
|
addr = item[4][0]
|
|
|
|
socket.inet_aton(item[4][0])
|
|
|
|
except (TypeError, socket.error):
|
|
|
|
continue
|
|
|
|
else:
|
|
|
|
knownnodes.addKnownNode(1, Peer(addr, port))
|
|
|
|
self._check_connection()
|
|
|
|
|
2019-10-21 14:20:29 +02:00
|
|
|
def test_bootstrap(self):
|
|
|
|
"""test bootstrapping"""
|
|
|
|
self._initiate_bootstrap()
|
2020-01-30 15:49:34 +01:00
|
|
|
self._check_connection()
|
2019-07-29 13:19:18 +02:00
|
|
|
|
2019-10-21 14:20:29 +02:00
|
|
|
@unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test')
|
|
|
|
def test_bootstrap_tor(self):
|
|
|
|
"""test bootstrapping with tor"""
|
|
|
|
self._initiate_bootstrap()
|
|
|
|
BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'stem')
|
|
|
|
start_proxyconfig()
|
2020-01-30 15:49:34 +01:00
|
|
|
self._check_connection()
|
2019-10-21 14:20:29 +02:00
|
|
|
|
|
|
|
@unittest.skipUnless(stem_version, 'No stem, skipping tor dependent test')
|
|
|
|
def test_onionservicesonly(self): # this should start after bootstrap
|
|
|
|
"""
|
|
|
|
set onionservicesonly, wait for 3 connections and check them all
|
|
|
|
are onions
|
|
|
|
"""
|
|
|
|
BMConfigParser().set('bitmessagesettings', 'socksproxytype', 'SOCKS5')
|
2019-11-14 13:32:15 +01:00
|
|
|
BMConfigParser().set('bitmessagesettings', 'onionservicesonly', 'true')
|
2019-10-24 21:35:32 +02:00
|
|
|
self._initiate_bootstrap()
|
|
|
|
BMConfigParser().remove_option('bitmessagesettings', 'dontconnect')
|
|
|
|
for _ in range(360):
|
|
|
|
time.sleep(1)
|
|
|
|
for n, peer in enumerate(BMConnectionPool().outboundConnections):
|
|
|
|
if n > 2:
|
|
|
|
return
|
2019-10-21 14:20:29 +02:00
|
|
|
if (
|
|
|
|
not peer.host.endswith('.onion')
|
|
|
|
and not peer.host.startswith('bootstrap')
|
|
|
|
):
|
2019-10-24 21:35:32 +02:00
|
|
|
self.fail(
|
|
|
|
'Found non onion hostname %s in outbound connections!'
|
|
|
|
% peer.host)
|
|
|
|
self.fail('Failed to connect to at least 3 nodes within 360 sec')
|
|
|
|
|
2020-05-15 12:49:59 +02:00
|
|
|
@staticmethod
|
|
|
|
def _decode_msg(data, pattern):
|
|
|
|
proto = BMProto()
|
|
|
|
proto.bm_proto_reset()
|
|
|
|
proto.payload = data[protocol.Header.size:]
|
|
|
|
return proto.decode_payload_content(pattern)
|
|
|
|
|
|
|
|
def test_version(self):
|
|
|
|
"""check encoding/decoding of the version message"""
|
|
|
|
# with single stream
|
|
|
|
msg = protocol.assembleVersionMessage('127.0.0.1', 8444, [1])
|
|
|
|
decoded = self._decode_msg(msg, "IQQiiQlsLv")
|
|
|
|
peer, _, ua, streams = self._decode_msg(msg, "IQQiiQlsLv")[4:]
|
2020-12-19 09:48:58 +01:00
|
|
|
self.assertEqual(
|
|
|
|
peer, Node(11 if state.dandelion else 3, '127.0.0.1', 8444))
|
2020-05-15 12:49:59 +02:00
|
|
|
self.assertEqual(ua, '/PyBitmessage:' + softwareVersion + '/')
|
|
|
|
self.assertEqual(streams, [1])
|
|
|
|
# with multiple streams
|
|
|
|
msg = protocol.assembleVersionMessage('127.0.0.1', 8444, [1, 2, 3])
|
|
|
|
decoded = self._decode_msg(msg, "IQQiiQlslv")
|
|
|
|
peer, _, ua = decoded[4:7]
|
|
|
|
streams = decoded[7:]
|
|
|
|
self.assertEqual(streams, [1, 2, 3])
|
|
|
|
|
2020-11-05 21:32:13 +01:00
|
|
|
def test_insert_method_msgid(self):
|
2020-11-04 16:09:29 +01:00
|
|
|
"""Test insert method of helper_sent module with message sending"""
|
2020-11-05 21:32:13 +01:00
|
|
|
fromAddress = 'BM-2cTrmD22fLRrumi3pPLg1ELJ6PdAaTRTdfg'
|
2020-11-17 20:36:05 +01:00
|
|
|
toAddress = 'BM-2cUGaEcGz9Zft1SPAo8FJtfzyADTpEgU9U'
|
2020-11-04 16:09:29 +01:00
|
|
|
message = 'test message'
|
|
|
|
subject = 'test subject'
|
2020-11-09 16:15:28 +01:00
|
|
|
result = helper_sent.insert(
|
2020-11-16 14:20:28 +01:00
|
|
|
toAddress=toAddress, fromAddress=fromAddress,
|
2020-12-23 20:42:18 +01:00
|
|
|
subject=subject, message=message
|
2020-11-12 21:15:01 +01:00
|
|
|
)
|
2020-11-16 14:20:28 +01:00
|
|
|
queryreturn = sqlQuery(
|
|
|
|
'''select msgid from sent where ackdata=?''', result)
|
2020-11-17 21:00:54 +01:00
|
|
|
self.assertNotEqual(queryreturn[0][0] if queryreturn else '', '')
|
2020-11-17 20:36:05 +01:00
|
|
|
|
|
|
|
column_type = sqlQuery(
|
|
|
|
'''select typeof(msgid) from sent where ackdata=?''', result)
|
|
|
|
self.assertEqual(column_type[0][0] if column_type else '', 'text')
|
2020-11-07 11:41:29 +01:00
|
|
|
|
2020-12-19 09:48:58 +01:00
|
|
|
def test_old_knownnodes_pickle(self):
|
|
|
|
"""Testing old(v.0.6.2) version knownnodes.dat file"""
|
|
|
|
try:
|
|
|
|
old_source_file = os.path.join(
|
|
|
|
os.path.abspath(os.path.dirname(__file__)), 'test_pattern', 'knownnodes.dat')
|
|
|
|
new_destination_file = os.path.join(state.appdata, 'knownnodes.dat')
|
|
|
|
shutil.copyfile(old_source_file, new_destination_file)
|
|
|
|
knownnodes.readKnownNodes()
|
|
|
|
except AttributeError as e:
|
|
|
|
self.fail('Failed to load knownnodes: %s' % e)
|
|
|
|
finally:
|
|
|
|
cleanup(files=('knownnodes.dat',))
|
|
|
|
|
2020-12-23 20:42:18 +01:00
|
|
|
@staticmethod
|
2021-01-06 07:57:35 +01:00
|
|
|
def delete_address_from_addressbook(address):
|
2021-01-05 12:25:02 +01:00
|
|
|
"""Clean up addressbook"""
|
|
|
|
sqlQuery('''delete from addressbook where address=?''', address)
|
2020-12-23 20:42:18 +01:00
|
|
|
|
|
|
|
def test_add_same_address_twice_in_addressbook(self):
|
|
|
|
"""checking same address is added twice in addressbook"""
|
|
|
|
self.assertTrue(helper_addressbook.insert(label='test1', address=self.addr))
|
|
|
|
self.assertFalse(helper_addressbook.insert(label='test1', address=self.addr))
|
2021-01-06 07:57:35 +01:00
|
|
|
self.delete_address_from_addressbook(self.addr)
|
2020-12-23 20:42:18 +01:00
|
|
|
|
|
|
|
def test_is_address_present_in_addressbook(self):
|
|
|
|
"""checking is address added in addressbook or not"""
|
|
|
|
helper_addressbook.insert(label='test1', address=self.addr)
|
|
|
|
queryreturn = sqlQuery('''select count(*) from addressbook where address=?''', self.addr)
|
2021-01-06 07:57:35 +01:00
|
|
|
self.assertEqual(queryreturn[0][0], 1)
|
|
|
|
self.delete_address_from_addressbook(self.addr)
|
2020-12-23 20:42:18 +01:00
|
|
|
|
|
|
|
def test_is_own_address_add_to_addressbook(self):
|
|
|
|
"""Checking own address adding in addressbook"""
|
2021-01-06 07:57:35 +01:00
|
|
|
from helper_addressGenerator import createAddressIfNeeded
|
2020-12-23 20:42:18 +01:00
|
|
|
try:
|
2021-01-06 07:57:35 +01:00
|
|
|
address = createAddressIfNeeded('test1')
|
|
|
|
self.assertFalse(helper_addressbook.insert(label='test', address=address))
|
2020-12-23 20:42:18 +01:00
|
|
|
except IndexError:
|
|
|
|
self.fail("Can't generate addresses")
|
|
|
|
|
2021-01-05 12:25:02 +01:00
|
|
|
def test_adding_two_same_case_sensitive_addresses(self):
|
|
|
|
"""Testing same case sensitive address store in addressbook"""
|
|
|
|
address1 = 'BM-2cVWtdUzPwF7UNGDrZftWuHWiJ6xxBpiSP'
|
|
|
|
address2 = 'BM-2CvwTDuZpWf7ungdRzFTwUhwIj6XXbPIsp'
|
|
|
|
self.assertTrue(helper_addressbook.insert(label='test1', address=address1))
|
|
|
|
self.assertTrue(helper_addressbook.insert(label='test2', address=address2))
|
2021-01-06 07:57:35 +01:00
|
|
|
self.delete_address_from_addressbook(address1)
|
|
|
|
self.delete_address_from_addressbook(address2)
|
2021-01-05 12:25:02 +01:00
|
|
|
|
2018-04-16 10:26:52 +02:00
|
|
|
|
2019-10-18 16:52:44 +02:00
|
|
|
def run():
|
2018-04-16 20:19:30 +02:00
|
|
|
"""Starts all tests defined in this module"""
|
2020-06-09 16:14:26 +02:00
|
|
|
loader = unittest.defaultTestLoader
|
2018-10-03 17:42:12 +02:00
|
|
|
loader.sortTestMethodsUsing = None
|
|
|
|
suite = loader.loadTestsFromTestCase(TestCore)
|
2020-06-09 16:14:26 +02:00
|
|
|
try:
|
|
|
|
import bitmessageqt.tests
|
|
|
|
except ImportError:
|
|
|
|
pass
|
|
|
|
else:
|
|
|
|
qt_tests = loader.loadTestsFromModule(bitmessageqt.tests)
|
|
|
|
suite.addTests(qt_tests)
|
2020-10-12 13:58:16 +02:00
|
|
|
|
|
|
|
def keep_exc(ex_cls, exc, tb): # pylint: disable=unused-argument
|
|
|
|
"""Own exception hook for test cases"""
|
|
|
|
excQueue.put(('tests', exc))
|
|
|
|
|
|
|
|
sys.excepthook = keep_exc
|
|
|
|
|
2018-04-16 10:26:52 +02:00
|
|
|
return unittest.TextTestRunner(verbosity=2).run(suite)
|