"""
Unit tests for stem.descriptor.server_descriptor.
"""

import datetime
import io
import tarfile
import unittest

import stem.descriptor.server_descriptor
import stem.exit_policy
import stem.prereq
import stem.version
import stem.util.str_tools

from stem.descriptor.server_descriptor import RelayDescriptor, BridgeDescriptor

from test.mocking import (
  get_relay_server_descriptor,
  get_bridge_server_descriptor,
  CRYPTO_BLOB,
)

from test.unit.descriptor import get_resource

try:
  # added in python 3.3
  from unittest.mock import Mock, patch
except ImportError:
  from mock import Mock, patch

TARFILE_FINGERPRINTS = set([
  u'B6D83EC2D9E18B0A7A33428F8CFA9C536769E209',
  u'E0BD57A11F00041A9789577C53A1B784473669E4',
  u'1F43EE37A0670301AD9CB555D94AFEC2C89FDE86',
])


class TestServerDescriptor(unittest.TestCase):
  def test_with_tarfile_path(self):
    """
    Fetch server descriptors via parse_file() for a tarfile path.
    """

    descriptors = list(stem.descriptor.parse_file(get_resource('descriptor_archive.tar')))
    self.assertEqual(3, len(descriptors))

    fingerprints = set([desc.fingerprint for desc in descriptors])
    self.assertEqual(TARFILE_FINGERPRINTS, fingerprints)

  def test_with_tarfile_object(self):
    """
    Fetch server descriptors via parse_file() for a tarfile object.
    """

    # TODO: When dropping python 2.6 support we can go back to using the 'with'
    # keyword here.

    tar_file = tarfile.open(get_resource('descriptor_archive.tar'))
    descriptors = list(stem.descriptor.parse_file(tar_file))
    self.assertEqual(3, len(descriptors))

    fingerprints = set([desc.fingerprint for desc in descriptors])
    self.assertEqual(TARFILE_FINGERPRINTS, fingerprints)
    tar_file.close()

  def test_metrics_descriptor(self):
    """
    Parses and checks our results against a server descriptor from metrics.
    """

    descriptor_file = open(get_resource('example_descriptor'), 'rb')

    expected_family = set([
      '$0CE3CFB1E9CC47B63EA8869813BF6FAB7D4540C1',
      '$1FD187E8F69A9B74C9202DC16A25B9E7744AB9F6',
      '$74FB5EFA6A46DE4060431D515DC9A790E6AD9A7C',
      '$77001D8DA9BF445B0F81AA427A675F570D222E6A',
      '$B6D83EC2D9E18B0A7A33428F8CFA9C536769E209',
      '$D2F37F46182C23AB747787FD657E680B34EAF892',
      '$E0BD57A11F00041A9789577C53A1B784473669E4',
      '$E5E3E9A472EAF7BE9682B86E92305DB4C71048EF',
    ])

    expected_onion_key = """-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAJv5IIWQ+WDWYUdyA/0L8qbIkEVH/cwryZWoIaPAzINfrw1WfNZGtBmg
skFtXhOHHqTRN4GPPrZsAIUOQGzQtGb66IQgT4tO/pj+P6QmSCCdTfhvGfgTCsC+
WPi4Fl2qryzTb3QO5r5x7T8OsG2IBUET1bLQzmtbC560SYR49IvVAgMBAAE=
-----END RSA PUBLIC KEY-----"""

    expected_signing_key = """-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBAKwvOXyztVKnuYvpTKt+nS3XIKeO8dVungi8qGoeS+6gkR6lDtGfBTjd
uE9UIkdAl9zi8/1Ic2wsUNHE9jiS0VgeupITGZY8YOyMJJ/xtV1cqgiWhq1dUYaq
51TOtUogtAPgXPh4J+V8HbFFIcCzIh3qCO/xXo+DSHhv7SSif1VpAgMBAAE=
-----END RSA PUBLIC KEY-----"""

    expected_signature = """-----BEGIN SIGNATURE-----
dskLSPz8beUW7bzwDjR6EVNGpyoZde83Ejvau+5F2c6cGnlu91fiZN3suE88iE6e
758b9ldq5eh5mapb8vuuV3uO+0Xsud7IEOqfxdkmk0GKnUX8ouru7DSIUzUL0zqq
Qlx9HNCqCY877ztFRC624ja2ql6A2hBcuoYMbkHjcQ4=
-----END SIGNATURE-----"""

    desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))
    self.assertEquals('caerSidi', desc.nickname)
    self.assertEquals('A7569A83B5706AB1B1A9CB52EFF7D2D32E4553EB', desc.fingerprint)
    self.assertEquals('71.35.133.197', desc.address)
    self.assertEquals(9001, desc.or_port)
    self.assertEquals(None, desc.socks_port)
    self.assertEquals(None, desc.dir_port)
    self.assertEquals(b'Tor 0.2.1.30 on Linux x86_64', desc.platform)
    self.assertEquals(stem.version.Version('0.2.1.30'), desc.tor_version)
    self.assertEquals('Linux x86_64', desc.operating_system)
    self.assertEquals(588217, desc.uptime)
    self.assertEquals(datetime.datetime(2012, 3, 1, 17, 15, 27), desc.published)
    self.assertEquals(b'www.atagar.com/contact', desc.contact)
    self.assertEquals(['1', '2'], desc.link_protocols)
    self.assertEquals(['1'], desc.circuit_protocols)
    self.assertEquals(False, desc.hibernating)
    self.assertEquals(False, desc.allow_single_hop_exits)
    self.assertEquals(False, desc.extra_info_cache)
    self.assertEquals('D225B728768D7EA4B5587C13A7A9D22EBBEE6E66', desc.extra_info_digest)
    self.assertEquals(['2'], desc.hidden_service_dir)
    self.assertEquals(expected_family, desc.family)
    self.assertEquals(153600, desc.average_bandwidth)
    self.assertEquals(256000, desc.burst_bandwidth)
    self.assertEquals(104590, desc.observed_bandwidth)
    self.assertEquals(stem.exit_policy.ExitPolicy('reject *:*'), desc.exit_policy)
    self.assertEquals(expected_onion_key, desc.onion_key)
    self.assertEquals(expected_signing_key, desc.signing_key)
    self.assertEquals(expected_signature, desc.signature)
    self.assertEquals([], desc.get_unrecognized_lines())
    self.assertEquals('2C7B27BEAB04B4E2459D89CA6D5CD1CC5F95A689', desc.digest())

  def test_metrics_descriptor_multiple(self):
    """
    Parses and checks our results against a server descriptor from metrics.
    """

    with open(get_resource('metrics_server_desc_multiple'), 'rb') as descriptor_file:
      descriptors = list(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))

      self.assertEquals(2, len(descriptors))

      self.assertEquals('anonion', descriptors[0].nickname)
      self.assertEquals('9A5EC5BB866517E53962AF4D3E776536694B069E', descriptors[0].fingerprint)

      self.assertEquals('Unnamed', descriptors[1].nickname)
      self.assertEquals('5366F1D198759F8894EA6E5FF768C667F59AFD24', descriptors[1].fingerprint)

  def test_old_descriptor(self):
    """
    Parses a relay server descriptor from 2005.
    """

    descriptor_file = open(get_resource('old_descriptor'), 'rb')

    desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))
    self.assertEquals('krypton', desc.nickname)
    self.assertEquals('3E2F63E2356F52318B536A12B6445373808A5D6C', desc.fingerprint)
    self.assertEquals('212.37.39.59', desc.address)
    self.assertEquals(8000, desc.or_port)
    self.assertEquals(None, desc.socks_port)
    self.assertEquals(None, desc.dir_port)
    self.assertEquals(b'Tor 0.1.0.14 on FreeBSD i386', desc.platform)
    self.assertEquals(stem.version.Version('0.1.0.14'), desc.tor_version)
    self.assertEquals('FreeBSD i386', desc.operating_system)
    self.assertEquals(64820, desc.uptime)
    self.assertEquals(datetime.datetime(2005, 12, 16, 18, 1, 3), desc.published)
    self.assertEquals(None, desc.contact)
    self.assertEquals(None, desc.link_protocols)
    self.assertEquals(None, desc.circuit_protocols)
    self.assertEquals(True, desc.hibernating)
    self.assertEquals(False, desc.allow_single_hop_exits)
    self.assertEquals(False, desc.extra_info_cache)
    self.assertEquals(None, desc.extra_info_digest)
    self.assertEquals(None, desc.hidden_service_dir)
    self.assertEquals(set(), desc.family)
    self.assertEquals(102400, desc.average_bandwidth)
    self.assertEquals(10485760, desc.burst_bandwidth)
    self.assertEquals(0, desc.observed_bandwidth)
    self.assertEquals(datetime.datetime(2005, 12, 16, 18, 0, 48), desc.read_history_end)
    self.assertEquals(900, desc.read_history_interval)
    self.assertEquals(datetime.datetime(2005, 12, 16, 18, 0, 48), desc.write_history_end)
    self.assertEquals(900, desc.write_history_interval)
    self.assertEquals([], desc.get_unrecognized_lines())

    # The read-history and write-history lines are pretty long so just checking
    # the initial contents for the line and parsed values.

    read_values_start = [20774, 489973, 510022, 511163, 20949]
    self.assertEquals(read_values_start, desc.read_history_values[:5])

    write_values_start = [81, 8848, 8927, 8927, 83, 8848, 8931, 8929, 81, 8846]
    self.assertEquals(write_values_start, desc.write_history_values[:10])

  def test_non_ascii_descriptor(self):
    """
    Parses a descriptor with non-ascii content.
    """

    descriptor_file = open(get_resource('non-ascii_descriptor'), 'rb')

    expected_contact = b'1024D/04D2E818 L\xc3\xa9na\xc3\xafc Huard <lenaic dot huard AT laposte dot net>'

    desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))
    self.assertEquals('Coruscant', desc.nickname)
    self.assertEquals('0B9821545C48E496AEED9ECC0DB506C49FF8158D', desc.fingerprint)
    self.assertEquals('88.182.161.122', desc.address)
    self.assertEquals(9001, desc.or_port)
    self.assertEquals(None, desc.socks_port)
    self.assertEquals(9030, desc.dir_port)
    self.assertEquals(b'Tor 0.2.3.25 on Linux', desc.platform)
    self.assertEquals(stem.version.Version('0.2.3.25'), desc.tor_version)
    self.assertEquals('Linux', desc.operating_system)
    self.assertEquals(259738, desc.uptime)
    self.assertEquals(datetime.datetime(2013, 5, 18, 11, 16, 19), desc.published)
    self.assertEquals(expected_contact, desc.contact)
    self.assertEquals(['1', '2'], desc.link_protocols)
    self.assertEquals(['1'], desc.circuit_protocols)
    self.assertEquals(False, desc.hibernating)
    self.assertEquals(False, desc.allow_single_hop_exits)
    self.assertEquals(False, desc.extra_info_cache)
    self.assertEquals('56403D838DE152421CD401B8E57DAD4483A3D56B', desc.extra_info_digest)
    self.assertEquals(['2'], desc.hidden_service_dir)
    self.assertEquals(set(), desc.family)
    self.assertEquals(102400, desc.average_bandwidth)
    self.assertEquals(204800, desc.burst_bandwidth)
    self.assertEquals(122818, desc.observed_bandwidth)
    self.assertEquals(stem.exit_policy.ExitPolicy('reject *:*'), desc.exit_policy)
    self.assertEquals([], desc.get_unrecognized_lines())

    # Make sure that we can get a string representation for this descriptor
    # (having non-unicode content risks a UnicodeEncodeError)...
    #
    # https://trac.torproject.org/8265

    self.assertTrue(isinstance(str(desc), str))

  def test_cr_in_contact_line(self):
    """
    Parses a descriptor with a huge contact line containing anomalous carriage
    returns ('\r' entries).
    """

    descriptor_file = open(get_resource('cr_in_contact_line'), 'rb')
    desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))

    self.assertEquals('pogonip', desc.nickname)
    self.assertEquals('6DABD62BC65D4E6FE620293157FC76968DAB9C9B', desc.fingerprint)
    self.assertEquals('75.5.248.48', desc.address)

    # the contact info block is huge so just checking the start and end,
    # including some of the embedded carriage returns

    contact_start = b'jie1 at pacbell dot net -----BEGIN PGP PUBLIC KEY BLOCK-----\rVersion:'
    contact_end = b'YFRk3NhCY=\r=Xaw3\r-----END PGP PUBLIC KEY BLOCK-----'

    self.assertTrue(desc.contact.startswith(contact_start))
    self.assertTrue(desc.contact.endswith(contact_end))

  def test_negative_uptime(self):
    """
    Parses a descriptor where we are tolerant of a negative uptime, and another
    where we shouldn't be.
    """

    descriptor_file = open(get_resource('negative_uptime'), 'rb')
    desc = next(stem.descriptor.parse_file(descriptor_file, 'server-descriptor 1.0'))

    self.assertEquals('TipTor', desc.nickname)
    self.assertEquals('137962D4931DBF08A24E843288B8A155D6D2AEDD', desc.fingerprint)
    self.assertEquals('62.99.247.83', desc.address)

    # modify the relay version so it's after when the negative uptime bug
    # should appear

    descriptor_contents = str(desc).replace('Tor 0.1.1.25', 'Tor 0.1.2.7')
    self.assertRaises(ValueError, stem.descriptor.server_descriptor.RelayDescriptor, descriptor_contents)

  def test_bridge_descriptor(self):
    """
    Parses a bridge descriptor.
    """

    descriptor_file = open(get_resource('bridge_descriptor'), 'rb')

    expected_family = set([
      '$CE396C72A3D0880F74C064FEA79D68C15BD380B9',
      '$AB8B00C00B1347BA80A88E548FAC9EDF701D7D0E',
      '$8C8A470D7C23151665A7B84E75E89FCC205A3304',
    ])

    desc = next(stem.descriptor.parse_file(descriptor_file, 'bridge-server-descriptor 1.0'))
    self.assertEquals('Unnamed', desc.nickname)
    self.assertEquals('AE54E28ED069CDF45F3009F963EE3B3D6FA26A2E', desc.fingerprint)
    self.assertEquals('10.45.227.253', desc.address)
    self.assertEquals(9001, desc.or_port)
    self.assertEquals(None, desc.socks_port)
    self.assertEquals(None, desc.dir_port)
    self.assertEquals(b'Tor 0.2.3.12-alpha (git-800942b4176ca31c) on Linux x86_64', desc.platform)
    self.assertEquals(stem.version.Version('0.2.3.12-alpha'), desc.tor_version)
    self.assertEquals('Linux x86_64', desc.operating_system)
    self.assertEquals(186, desc.uptime)
    self.assertEquals(datetime.datetime(2012, 3, 22, 17, 34, 38), desc.published)
    self.assertEquals(b'somebody', desc.contact)
    self.assertEquals(['1', '2'], desc.link_protocols)
    self.assertEquals(['1'], desc.circuit_protocols)
    self.assertEquals(False, desc.hibernating)
    self.assertEquals(False, desc.allow_single_hop_exits)
    self.assertEquals(False, desc.extra_info_cache)
    self.assertEquals('134F81F7A0D270B85FCD481DD10CEA34BA7B15C9', desc.extra_info_digest)
    self.assertEquals(['2'], desc.hidden_service_dir)
    self.assertEquals(expected_family, desc.family)
    self.assertEquals(409600, desc.average_bandwidth)
    self.assertEquals(819200, desc.burst_bandwidth)
    self.assertEquals(5120, desc.observed_bandwidth)
    self.assertEquals(stem.exit_policy.ExitPolicy('reject *:*'), desc.exit_policy)
    self.assertEquals('006FD96BA35E7785A6A3B8B75FE2E2435A13BDB4', desc.digest())
    self.assertEquals([], desc.get_unrecognized_lines())

  def test_minimal_relay_descriptor(self):
    """
    Basic sanity check that we can parse a relay server descriptor with minimal
    attributes.
    """

    desc = get_relay_server_descriptor()

    self.assertEquals('caerSidi', desc.nickname)
    self.assertEquals('71.35.133.197', desc.address)
    self.assertEquals(None, desc.fingerprint)
    self.assertTrue(CRYPTO_BLOB in desc.onion_key)

  def test_with_opt(self):
    """
    Includes an 'opt <keyword> <value>' entry.
    """

    desc = get_relay_server_descriptor({'opt': 'contact www.atagar.com/contact/'})
    self.assertEquals(b'www.atagar.com/contact/', desc.contact)

  def test_unrecognized_line(self):
    """
    Includes unrecognized content in the descriptor.
    """

    desc = get_relay_server_descriptor({'pepperjack': 'is oh so tasty!'})
    self.assertEquals(['pepperjack is oh so tasty!'], desc.get_unrecognized_lines())

  def test_proceeding_line(self):
    """
    Includes a line prior to the 'router' entry.
    """

    desc_text = b'hibernate 1\n' + get_relay_server_descriptor(content = True)
    self._expect_invalid_attr(desc_text)

  def test_trailing_line(self):
    """
    Includes a line after the 'router-signature' entry.
    """

    desc_text = get_relay_server_descriptor(content = True) + b'\nhibernate 1'
    self._expect_invalid_attr(desc_text)

  def test_nickname_missing(self):
    """
    Constructs with a malformed router entry.
    """

    desc_text = get_relay_server_descriptor({'router': ' 71.35.133.197 9001 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'nickname')

  def test_nickname_too_long(self):
    """
    Constructs with a nickname that is an invalid length.
    """

    desc_text = get_relay_server_descriptor({'router': 'saberrider2008ReallyLongNickname 71.35.133.197 9001 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'nickname', 'saberrider2008ReallyLongNickname')

  def test_nickname_invalid_char(self):
    """
    Constructs with an invalid relay nickname.
    """

    desc_text = get_relay_server_descriptor({'router': '$aberrider2008 71.35.133.197 9001 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'nickname', '$aberrider2008')

  def test_address_malformed(self):
    """
    Constructs with an invalid ip address.
    """

    desc_text = get_relay_server_descriptor({'router': 'caerSidi 371.35.133.197 9001 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'address', '371.35.133.197')

  def test_port_too_high(self):
    """
    Constructs with an ORPort that is too large.
    """

    desc_text = get_relay_server_descriptor({'router': 'caerSidi 71.35.133.197 900001 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'or_port', 900001)

  def test_port_malformed(self):
    """
    Constructs with an ORPort that isn't numeric.
    """

    desc_text = get_relay_server_descriptor({'router': 'caerSidi 71.35.133.197 900a1 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'or_port')

  def test_port_newline(self):
    """
    Constructs with a newline replacing the ORPort.
    """

    desc_text = get_relay_server_descriptor({'router': 'caerSidi 71.35.133.197 \n 0 0'}, content = True)
    self._expect_invalid_attr(desc_text, 'or_port')

  def test_platform_empty(self):
    """
    Constructs with an empty platform entry.
    """

    desc_text = get_relay_server_descriptor({'platform': ''}, content = True)
    desc = RelayDescriptor(desc_text, validate = False)
    self.assertEquals(b'', desc.platform)

    # does the same but with 'platform ' replaced with 'platform'
    desc_text = desc_text.replace(b'platform ', b'platform')
    desc = RelayDescriptor(desc_text, validate = False)
    self.assertEquals(b'', desc.platform)

  def test_platform_for_node_tor(self):
    """
    Parse a platform line belonging to a node-Tor relay.
    """

    desc = get_relay_server_descriptor({'platform': 'node-Tor 0.1.0 on Linux x86_64'})
    self.assertEquals(b'node-Tor 0.1.0 on Linux x86_64', desc.platform)
    self.assertEquals(stem.version.Version('0.1.0'), desc.tor_version)
    self.assertEquals('Linux x86_64', desc.operating_system)

  def test_protocols_no_circuit_versions(self):
    """
    Constructs with a protocols line without circuit versions.
    """

    desc_text = get_relay_server_descriptor({'opt': 'protocols Link 1 2'}, content = True)
    self._expect_invalid_attr(desc_text, 'circuit_protocols')

  @patch('stem.descriptor.server_descriptor.RelayDescriptor._verify_digest', Mock())
  def test_published_leap_year(self):
    """
    Constructs with a published entry for a leap year, and when the date is
    invalid.
    """

    desc_text = get_relay_server_descriptor({'published': '2011-02-29 04:03:19'}, content = True)
    self._expect_invalid_attr(desc_text, 'published')

    desc_text = get_relay_server_descriptor({'published': '2012-02-29 04:03:19'}, content = True)
    expected_published = datetime.datetime(2012, 2, 29, 4, 3, 19)
    self.assertEquals(expected_published, RelayDescriptor(desc_text).published)

  def test_published_no_time(self):
    """
    Constructs with a published entry without a time component.
    """

    desc_text = get_relay_server_descriptor({'published': '2012-01-01'}, content = True)
    self._expect_invalid_attr(desc_text, 'published')

  def test_read_and_write_history(self):
    """
    Parses a read-history and write-history entry. This is now a deprecated
    field for relay server descriptors but is still found in archives and
    extra-info descriptors.
    """

    for field in ('read-history', 'write-history'):
      value = '2005-12-16 18:00:48 (900 s) 81,8848,8927,8927,83,8848'
      desc = get_relay_server_descriptor({'opt %s' % field: value})

      if field == 'read-history':
        attr = (desc.read_history_end, desc.read_history_interval, desc.read_history_values)
      else:
        attr = (desc.write_history_end, desc.write_history_interval, desc.write_history_values)

      expected_end = datetime.datetime(2005, 12, 16, 18, 0, 48)
      expected_values = [81, 8848, 8927, 8927, 83, 8848]

      self.assertEquals(expected_end, attr[0])
      self.assertEquals(900, attr[1])
      self.assertEquals(expected_values, attr[2])

  def test_read_history_empty(self):
    """
    Parses a read-history with an empty value.
    """

    value = '2005-12-17 01:23:11 (900 s) '
    desc = get_relay_server_descriptor({'opt read-history': value})
    self.assertEquals(datetime.datetime(2005, 12, 17, 1, 23, 11), desc.read_history_end)
    self.assertEquals(900, desc.read_history_interval)
    self.assertEquals([], desc.read_history_values)

  @patch('stem.descriptor.server_descriptor.RelayDescriptor._verify_digest', Mock())
  def test_annotations(self):
    """
    Checks that content before a descriptor are parsed as annotations.
    """

    desc_text = b'@pepperjack very tasty\n@mushrooms not so much\n'
    desc_text += get_relay_server_descriptor(content = True)
    desc_text += b'\ntrailing text that should be invalid, ho hum'

    # running _parse_file should provide an iterator with a single descriptor
    desc_iter = stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_text))
    self.assertRaises(ValueError, list, desc_iter)

    desc_text = b'@pepperjack very tasty\n@mushrooms not so much\n'
    desc_text += get_relay_server_descriptor(content = True)
    desc_iter = stem.descriptor.server_descriptor._parse_file(io.BytesIO(desc_text))

    desc_entries = list(desc_iter)
    self.assertEquals(1, len(desc_entries))
    desc = desc_entries[0]

    self.assertEquals('caerSidi', desc.nickname)
    self.assertEquals(b'@pepperjack very tasty', desc.get_annotation_lines()[0])
    self.assertEquals(b'@mushrooms not so much', desc.get_annotation_lines()[1])
    self.assertEquals({b'@pepperjack': b'very tasty', b'@mushrooms': b'not so much'}, desc.get_annotations())
    self.assertEquals([], desc.get_unrecognized_lines())

  def test_duplicate_field(self):
    """
    Constructs with a field appearing twice.
    """

    desc_text = get_relay_server_descriptor({'<replace>': ''}, content = True)
    desc_text = desc_text.replace(b'<replace>', b'contact foo\ncontact bar')
    self._expect_invalid_attr(desc_text, 'contact', b'foo')

  def test_missing_required_attr(self):
    """
    Test making a descriptor with a missing required attribute.
    """

    for attr in stem.descriptor.server_descriptor.REQUIRED_FIELDS:
      desc_text = get_relay_server_descriptor(exclude = [attr], content = True)
      self.assertRaises(ValueError, RelayDescriptor, desc_text)

      # check that we can still construct it without validation
      desc = RelayDescriptor(desc_text, validate = False)

      # for one of them checks that the corresponding values are None
      if attr == 'router':
        self.assertEquals(None, desc.nickname)
        self.assertEquals(None, desc.address)
        self.assertEquals(None, desc.or_port)
        self.assertEquals(None, desc.socks_port)
        self.assertEquals(None, desc.dir_port)

  def test_fingerprint_invalid(self):
    """
    Checks that, with a correctly formed fingerprint, we'll fail validation if
    it doesn't match the hash of our signing key.
    """

    fingerprint = '4F0C 867D F0EF 6816 0568 C826 838F 482C EA7C FE45'
    desc_text = get_relay_server_descriptor({'opt fingerprint': fingerprint}, content = True)
    self._expect_invalid_attr(desc_text, 'fingerprint', fingerprint.replace(' ', ''))

  def test_ipv6_policy(self):
    """
    Checks a 'ipv6-policy' line.
    """

    expected = stem.exit_policy.MicroExitPolicy('accept 22-23,53,80,110')
    desc = get_relay_server_descriptor({'ipv6-policy': 'accept 22-23,53,80,110'})
    self.assertEquals(expected, desc.exit_policy_v6)

  def test_ntor_onion_key(self):
    """
    Checks a 'ntor-onion-key' line.
    """

    desc = get_relay_server_descriptor({'ntor-onion-key': 'Od2Sj3UXFyDjwESLXk6fhatqW9z/oBL/vAKJ+tbDqUU='})
    self.assertEquals('Od2Sj3UXFyDjwESLXk6fhatqW9z/oBL/vAKJ+tbDqUU=', desc.ntor_onion_key)

  def test_minimal_bridge_descriptor(self):
    """
    Basic sanity check that we can parse a descriptor with minimal attributes.
    """

    desc = get_bridge_server_descriptor()

    self.assertEquals('Unnamed', desc.nickname)
    self.assertEquals('10.45.227.253', desc.address)
    self.assertEquals(None, desc.fingerprint)
    self.assertEquals('006FD96BA35E7785A6A3B8B75FE2E2435A13BDB4', desc.digest())

    # check that we don't have crypto fields
    self.assertRaises(AttributeError, getattr, desc, 'onion_key')
    self.assertRaises(AttributeError, getattr, desc, 'signing_key')
    self.assertRaises(AttributeError, getattr, desc, 'signature')

  def test_bridge_unsanitized(self):
    """
    Targeted check that individual unsanitized attributes will be detected.
    """

    unsanitized_attr = [
      {'router': 'Unnamed 75.45.227.253 9001 0 0'},
      {'contact': 'Damian'},
      {'or-address': '71.35.133.197:9001'},
      {'or-address': '[12ab:2e19:3bcf::02:9970]:9001'},
      {'onion-key': '\n-----BEGIN RSA PUBLIC KEY-----%s-----END RSA PUBLIC KEY-----' % CRYPTO_BLOB},
      {'signing-key': '\n-----BEGIN RSA PUBLIC KEY-----%s-----END RSA PUBLIC KEY-----' % CRYPTO_BLOB},
      {'router-signature': '\n-----BEGIN SIGNATURE-----%s-----END SIGNATURE-----' % CRYPTO_BLOB},
    ]

    for attr in unsanitized_attr:
      desc = get_bridge_server_descriptor(attr)
      self.assertFalse(desc.is_scrubbed())

  def test_bridge_unsanitized_relay(self):
    """
    Checks that parsing a normal relay descriptor as a bridge will fail due to
    its unsanatized content.
    """

    desc_text = get_relay_server_descriptor({'router-digest': '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB4'}, content = True)
    desc = BridgeDescriptor(desc_text)
    self.assertFalse(desc.is_scrubbed())

  def test_router_digest(self):
    """
    Constructs with a router-digest line with both valid and invalid contents.
    """

    # checks with valid content

    router_digest = '068A2E28D4C934D9490303B7A645BA068DCA0504'
    desc = get_bridge_server_descriptor({'router-digest': router_digest})
    self.assertEquals(router_digest, desc.digest())

    # checks when missing

    desc_text = get_bridge_server_descriptor(exclude = ['router-digest'], content = True)
    self.assertRaises(ValueError, BridgeDescriptor, desc_text)

    # check that we can still construct it without validation
    desc = BridgeDescriptor(desc_text, validate = False)
    self.assertEquals(None, desc.digest())

    # checks with invalid content

    test_values = (
      '',
      '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB44',
      '006FD96BA35E7785A6A3B8B75FE2E2435A13BDB',
      '006FD96BA35E7785A6A3B8B75FE2E2435A13BDBH',
    )

    for value in test_values:
      desc_text = get_bridge_server_descriptor({'router-digest': value}, content = True)
      self.assertRaises(ValueError, BridgeDescriptor, desc_text)

      desc = BridgeDescriptor(desc_text, validate = False)
      self.assertEquals(value, desc.digest())

  def test_or_address_v4(self):
    """
    Constructs a bridge descriptor with a sanatized IPv4 or-address entry.
    """

    desc = get_bridge_server_descriptor({'or-address': '10.45.227.253:9001'})
    self.assertEquals([('10.45.227.253', 9001, False)], desc.or_addresses)

  def test_or_address_v6(self):
    """
    Constructs a bridge descriptor with a sanatized IPv6 or-address entry.
    """

    desc = get_bridge_server_descriptor({'or-address': '[fd9f:2e19:3bcf::02:9970]:9001'})
    self.assertEquals([('fd9f:2e19:3bcf::02:9970', 9001, True)], desc.or_addresses)

  def test_or_address_multiple(self):
    """
    Constructs a bridge descriptor with multiple or-address entries and multiple ports.
    """

    desc_text = b'\n'.join((get_bridge_server_descriptor(content = True),
                            b'or-address 10.45.227.253:9001',
                            b'or-address [fd9f:2e19:3bcf::02:9970]:443'))

    expected_or_addresses = [
      ('10.45.227.253', 9001, False),
      ('fd9f:2e19:3bcf::02:9970', 443, True),
    ]

    desc = BridgeDescriptor(desc_text)
    self.assertEquals(expected_or_addresses, desc.or_addresses)

  def _expect_invalid_attr(self, desc_text, attr = None, expected_value = None):
    """
    Asserts that construction will fail due to desc_text having a malformed
    attribute. If an attr is provided then we check that it matches an expected
    value when we're constructed without validation.
    """

    self.assertRaises(ValueError, RelayDescriptor, desc_text)
    desc = RelayDescriptor(desc_text, validate = False)

    if attr:
      # check that the invalid attribute matches the expected value when
      # constructed without validation

      self.assertEquals(expected_value, getattr(desc, attr))
    else:
      # check a default attribute
      self.assertEquals('caerSidi', desc.nickname)
