Skip to content
This repository was archived by the owner on Sep 26, 2022. It is now read-only.

Commit 7cfa294

Browse files
authored
Merge pull request #228 from bigspider/173-hardcoded-strings
Avoid hardcoded strings
2 parents 8ade615 + 3e0bb3c commit 7cfa294

13 files changed

Lines changed: 76 additions & 62 deletions

File tree

common/appointment.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,12 @@
1-
import struct
1+
from enum import Enum
2+
3+
4+
class AppointmentStatus(str, Enum):
5+
"""Represents all the possible states of an appointment in the system, or in a response to a client request."""
6+
7+
NOT_FOUND = "not_found"
8+
BEING_WATCHED = "being_watched"
9+
DISPUTE_RESPONDED = "dispute_responded"
210

311

412
class Appointment:

contrib/client/test/test_teos_client.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99

1010
import common.receipts as receipts
1111
from common.tools import compute_locator, is_compressed_pk
12-
from common.appointment import Appointment
12+
from common.appointment import Appointment, AppointmentStatus
1313
from common.cryptographer import Cryptographer
1414
from common.exceptions import InvalidParameter, InvalidKey, TowerResponseError
1515

@@ -247,7 +247,7 @@ def test_get_appointment():
247247
# Response of get_appointment endpoint is an appointment with status added to it.
248248
response = {
249249
"locator": dummy_appointment_dict.get("locator"),
250-
"status": "being_watched",
250+
"status": AppointmentStatus.BEING_WATCHED,
251251
"appointment": dummy_appointment_dict,
252252
}
253253

teos/api.py

Lines changed: 10 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,17 @@
33
from waitress import serve as wsgi_serve
44
from flask import Flask, request, jsonify
55

6+
67
import common.errors as errors
8+
from common.appointment import AppointmentStatus
9+
from common.exceptions import InvalidParameter
10+
from common.constants import HTTP_OK, HTTP_BAD_REQUEST, HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND
711
from teos.inspector import Inspector, InspectionFailed
812
from teos.protobuf.user_pb2 import RegisterRequest
913
from teos.protobuf.tower_services_pb2_grpc import TowerServicesStub
1014
from teos.protobuf.appointment_pb2 import Appointment, AddAppointmentRequest, GetAppointmentRequest
1115

12-
from common.exceptions import InvalidParameter
1316
from teos.logger import setup_logging, get_logger
14-
from common.constants import HTTP_OK, HTTP_BAD_REQUEST, HTTP_SERVICE_UNAVAILABLE, HTTP_NOT_FOUND
1517

1618

1719
# NOTCOVERED: not sure how to monkey patch this one. May be related to #77
@@ -257,9 +259,11 @@ def get_appointment(self):
257259
A ``status`` flag is added to the data provided by either the :obj:`Watcher <teos.watcher.Watcher>` or the
258260
:obj:`Responder <teos.responder.Responder>` that signals the status of the appointment.
259261
260-
- Appointments hold by the :obj:`Watcher <teos.watcher.Watcher>` are flagged as ``being_watched``.
261-
- Appointments hold by the :obj:`Responder <teos.responder.Responder>` are flagged as ``dispute_triggered``.
262-
- Unknown appointments are flagged as ``not_found``.
262+
- Appointments held by the :obj:`Watcher <teos.watcher.Watcher>` are flagged as
263+
``AppointmentStatus.BEING_WATCHED``.
264+
- Appointments held by the :obj:`Responder <teos.responder.Responder>` are flagged as
265+
``AppointmentStatus.DISPUTE_RESPONDED``.
266+
- Unknown appointments are flagged as ``AppointmentStatus.NOT_FOUND``.
263267
"""
264268

265269
# Getting the real IP if the server is behind a reverse proxy
@@ -299,6 +303,6 @@ def get_appointment(self):
299303

300304
except (InspectionFailed, grpc.RpcError):
301305
rcode = HTTP_NOT_FOUND
302-
response = {"locator": locator, "status": "not_found"}
306+
response = {"locator": locator, "status": AppointmentStatus.NOT_FOUND}
303307

304308
return jsonify(response), rcode

teos/chain_monitor.py

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,8 @@ class ChainMonitor:
3232
detected.
3333
Finally, once the ``terminate`` method is called, the ``status`` is changed to ``ChainMonitorStatus.TERMINATED``,
3434
the chain monitor stops monitoring the chain and no receiving queue will be notified about new blocks (including
35-
any block that is currently in the internal queue). A final ``"END"`` message is sent to all the subscribers.
35+
any block that is currently in the internal queue). A final ``ChainMonitor.END_MESSAGE`` is sent to all the
36+
subscribers.
3637
3738
Args:
3839
receiving_queues (:obj:`list`): a list of :obj:`Queue` objects that will be notified when the chain_monitor is
@@ -53,6 +54,8 @@ class ChainMonitor:
5354
``ChainMonitorStatus.LISTENING``, ``ChainMonitorStatus.ACTIVE`` or ``ChainMonitorStatus.TERMINATED``.
5455
"""
5556

57+
END_MESSAGE = "END"
58+
5659
def __init__(self, receiving_queues, block_processor, bitcoind_feed_params):
5760
self.logger = get_logger(component=ChainMonitor.__name__)
5861
self.last_tips = []
@@ -151,7 +154,7 @@ def notify_subscribers(self):
151154

152155
while self.status != ChainMonitorStatus.TERMINATED:
153156
message = self.queue.get()
154-
# A special "END" message is added to the queue after the status is set to TERMINATED
157+
# A special ChainMonitor.END_MESSAGE is added to the queue after the status is set to TERMINATED
155158
# In all the other cases, message is a block_hash
156159
with self.lock:
157160
for rec_queue in self.receiving_queues:
@@ -164,7 +167,7 @@ def monitor_chain(self):
164167
and creates two threads, one per each monitoring approach (``zmq`` and ``polling``).
165168
166169
Raises:
167-
:obj:`RuntimeError`: if the ``status`` was not ``ChainMonitor.IDLE`` when the method was called.
170+
:obj:`RuntimeError`: if the ``status`` was not ``ChainMonitorStatus.IDLE`` when the method was called.
168171
"""
169172

170173
if self.status != ChainMonitorStatus.IDLE:
@@ -183,7 +186,7 @@ def activate(self):
183186
is added to the internal queue.
184187
185188
Raises:
186-
:obj:`RuntimeError`: if the ``status`` was not ``ChainMonitor.LISTENING`` when the method was called.
189+
:obj:`RuntimeError`: if the ``status`` was not ``ChainMonitorStatus.LISTENING`` when the method was called.
187190
"""
188191

189192
if self.status != ChainMonitorStatus.LISTENING:
@@ -195,9 +198,9 @@ def activate(self):
195198

196199
def terminate(self):
197200
"""
198-
Changes the ``status`` of the :obj:`ChainMonitor` to terminated and sends the "END" message to the internal
199-
queue. All the threads will stop as soon as possible.
201+
Changes the ``status`` of the :obj:`ChainMonitor` to terminated and sends the ``ChainMonitor.END_MESSAGE``
202+
message to the internal queue. All the threads will stop as soon as possible.
200203
"""
201204

202205
self.status = ChainMonitorStatus.TERMINATED
203-
self.queue.put("END")
206+
self.queue.put(ChainMonitor.END_MESSAGE)

teos/internal_api.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from google.protobuf.struct_pb2 import Struct
55

66
from teos.logger import get_logger
7-
from common.appointment import Appointment
7+
from common.appointment import Appointment, AppointmentStatus
88
from common.exceptions import InvalidParameter
99

1010
from teos.protobuf.appointment_pb2 import (
@@ -122,7 +122,7 @@ def get_appointment(self, request, context):
122122
with self.rw_lock.gen_rlock():
123123
try:
124124
data, status = self.watcher.get_appointment(request.locator, request.signature)
125-
if status == "being_watched":
125+
if status == AppointmentStatus.BEING_WATCHED:
126126
data = AppointmentData(
127127
appointment=AppointmentProto(
128128
locator=data.get("locator"),

teos/responder.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
from threading import Thread
33

44
from teos.cleaner import Cleaner
5-
5+
from teos.chain_monitor import ChainMonitor
66
from teos.logger import get_logger
77
from common.constants import IRREVOCABLY_RESOLVED
88

@@ -148,7 +148,7 @@ def __init__(self, db_manager, gatekeeper, carrier, block_processor):
148148
def awake(self):
149149
"""
150150
Starts a new thread to monitor the blockchain to make sure triggered appointments get enough depth.
151-
The thread will run until the :obj:`ChainMonitor` adds the ``"END"`` message to the queue.
151+
The thread will run until the :obj:`ChainMonitor` adds the ``ChainMonitor.END_MESSAGE`` to the queue.
152152
153153
Returns:
154154
:obj:`Thread <multithreading.Thread>`: The thread object that was just created and is already running.
@@ -273,8 +273,8 @@ def do_watch(self):
273273
while True:
274274
block_hash = self.block_queue.get()
275275

276-
# When the ChainMonitor is stopped, a final "END" message is sent
277-
if block_hash == "END":
276+
# When the ChainMonitor is stopped, a final ChainMonitor.END_MESSAGE is sent
277+
if block_hash == ChainMonitor.END_MESSAGE:
278278
break
279279

280280
block = self.block_processor.get_block(block_hash)

teos/watcher.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55

66
from teos.logger import get_logger
77
import common.receipts as receipts
8+
from common.appointment import AppointmentStatus
89
from common.tools import compute_locator
9-
from common.exceptions import BasicException
10-
from common.exceptions import EncryptionError
10+
from common.exceptions import BasicException, EncryptionError, InvalidParameter, SignatureError
1111
from common.cryptographer import Cryptographer, hash_160
12-
from common.exceptions import InvalidParameter, SignatureError
1312

1413
from teos.cleaner import Cleaner
14+
from teos.chain_monitor import ChainMonitor
1515
from teos.extended_appointment import ExtendedAppointment
1616
from teos.block_processor import InvalidTransactionFormat
1717

@@ -251,7 +251,7 @@ def n_responder_trackers(self):
251251
def awake(self):
252252
"""
253253
Starts a new thread to monitor the blockchain for channel breaches. The thread will run until the
254-
:obj:`ChainMonitor` adds the ``"END"`` message to the queue.
254+
:obj:`ChainMonitor` adds ``ChainMonitor.END_MESSAGE`` to the queue.
255255
256256
Returns:
257257
:obj:`Thread <multithreading.Thread>`: The thread object that was just created and is already running.
@@ -289,8 +289,8 @@ def get_appointment(self, locator, user_signature):
289289
user_signature (:obj:`str`): the signature of the request by the user.
290290
291291
Returns:
292-
:obj:`tuple`: A tuple containing the appointment data and the status (either ``"being_watched"`` or
293-
``"dispute_responded"``).
292+
:obj:`tuple`: A tuple containing the appointment data and the status, either
293+
``AppointmentStatus.BEING_WATCHED`` or ``AppointmentStatus.DISPUTE_RESPONDED``
294294
295295
Raises:
296296
:obj:`AppointmentNotFound`: if the appointment is not found in the tower.
@@ -302,10 +302,10 @@ def get_appointment(self, locator, user_signature):
302302

303303
if uuid in self.appointments:
304304
appointment_data = self.db_manager.load_watcher_appointment(uuid)
305-
status = "being_watched"
305+
status = AppointmentStatus.BEING_WATCHED
306306
elif uuid in self.responder.trackers:
307307
appointment_data = self.db_manager.load_responder_tracker(uuid)
308-
status = "dispute_responded"
308+
status = AppointmentStatus.DISPUTE_RESPONDED
309309
else:
310310
raise AppointmentNotFound("Cannot find {}".format(locator))
311311

@@ -452,8 +452,8 @@ def do_watch(self):
452452
while True:
453453
block_hash = self.block_queue.get()
454454

455-
# When the ChainMonitor is stopped, a final "END" message is sent
456-
if block_hash == "END":
455+
# When the ChainMonitor is stopped, a final ChainMonitor.END_MESSAGE message is sent
456+
if block_hash == ChainMonitor.END_MESSAGE:
457457
break
458458

459459
block = self.block_processor.get_block(block_hash)
@@ -661,7 +661,7 @@ def get_registered_user_ids(self):
661661

662662
def get_user_info(self, user_id):
663663
"""
664-
Returns the data hold by the tower about the user given an ``user_id``.
664+
Returns the data held by the tower about the user given an ``user_id``.
665665
666666
Args:
667667
user_id (:obj:`str`): the id of the requested user.

test/common/unit/test_appointment.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import struct
21
import pytest
32

43
from common.appointment import Appointment

test/teos/e2e/test_basic_e2e.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import common.receipts as receipts
1010
from common.exceptions import TowerResponseError
1111
from common.tools import compute_locator
12-
from common.appointment import Appointment
12+
from common.appointment import Appointment, AppointmentStatus
1313
from common.cryptographer import Cryptographer
1414

1515
from teos.cli.teos_cli import RPCClient
@@ -106,7 +106,7 @@ def test_appointment_life_cycle(run_bitcoind):
106106

107107
# Get the information from the tower to check that it matches
108108
appointment_info = get_appointment_info(locator)
109-
assert appointment_info.get("status") == "being_watched"
109+
assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
110110
assert appointment_info.get("locator") == locator
111111
assert appointment_info.get("appointment") == appointment.to_dict()
112112

@@ -121,7 +121,7 @@ def test_appointment_life_cycle(run_bitcoind):
121121
# Trigger a breach and check again
122122
generate_block_with_transactions(commitment_tx)
123123
appointment_info = get_appointment_info(locator)
124-
assert appointment_info.get("status") == "dispute_responded"
124+
assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED
125125
assert appointment_info.get("locator") == locator
126126
appointments_in_watcher -= 1
127127
appointments_in_responder += 1
@@ -230,7 +230,7 @@ def test_appointment_malformed_penalty(run_bitcoind):
230230

231231
# Get the information from the tower to check that it matches
232232
appointment_info = get_appointment_info(locator)
233-
assert appointment_info.get("status") == "being_watched"
233+
assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
234234
assert appointment_info.get("locator") == locator
235235
assert appointment_info.get("appointment") == appointment.to_dict()
236236

@@ -298,7 +298,7 @@ def test_two_identical_appointments(run_bitcoind):
298298
# The last appointment should have made it to the Responder
299299
appointment_info = get_appointment_info(locator)
300300

301-
assert appointment_info.get("status") == "dispute_responded"
301+
assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED
302302
assert appointment_info.get("appointment").get("penalty_rawtx") == penalty_tx
303303

304304

@@ -325,9 +325,9 @@ def test_two_identical_appointments(run_bitcoind):
325325
#
326326
# # Check that we can get it from both users
327327
# appointment_info = get_appointment_info(locator)
328-
# assert appointment_info.get("status") == "being_watched"
328+
# assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
329329
# appointment_info = get_appointment_info(locator, sk=tmp_user_sk)
330-
# assert appointment_info.get("status") == "being_watched"
330+
# assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
331331
#
332332
# # Broadcast the commitment transaction and mine a block
333333
# generate_block_with_transactions(commitment_tx)
@@ -344,7 +344,7 @@ def test_two_identical_appointments(run_bitcoind):
344344
#
345345
# appointment_info = appointment_info if appointment_info is None else appointment_dup_info
346346
#
347-
# assert appointment_info.get("status") == "dispute_responded"
347+
# assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED
348348
# assert appointment_info.get("appointment").get("penalty_rawtx") == penalty_tx
349349

350350

@@ -385,7 +385,7 @@ def test_two_appointment_same_locator_different_penalty_different_users(run_bitc
385385
appointment_info = appointment2_info
386386
appointment1_data = appointment2_data
387387

388-
assert appointment_info.get("status") == "dispute_responded"
388+
assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED
389389
assert appointment_info.get("locator") == appointment1_data.get("locator")
390390
assert appointment_info.get("appointment").get("penalty_tx") == appointment1_data.get("penalty_tx")
391391

@@ -402,7 +402,7 @@ def test_add_appointment_trigger_on_cache(run_bitcoind):
402402
# Send the data to the tower and request it back. It should have gone straightaway to the Responder
403403
appointment = teos_client.create_appointment(appointment_data)
404404
add_appointment(appointment)
405-
assert get_appointment_info(locator).get("status") == "dispute_responded"
405+
assert get_appointment_info(locator).get("status") == AppointmentStatus.DISPUTE_RESPONDED
406406

407407

408408
def test_add_appointment_invalid_trigger_on_cache(run_bitcoind):
@@ -483,15 +483,15 @@ def test_appointment_shutdown_teos_trigger_back_online(run_bitcoind):
483483
# Check that the appointment is still in the Watcher
484484
appointment_info = get_appointment_info(locator)
485485

486-
assert appointment_info.get("status") == "being_watched"
486+
assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
487487
assert appointment_info.get("appointment") == appointment.to_dict()
488488

489489
# Trigger appointment after restart
490490
generate_block_with_transactions(commitment_tx)
491491

492492
# The appointment should have been moved to the Responder
493493
appointment_info = get_appointment_info(locator)
494-
assert appointment_info.get("status") == "dispute_responded"
494+
assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED
495495

496496

497497
def test_appointment_shutdown_teos_trigger_while_offline(run_bitcoind):
@@ -509,7 +509,7 @@ def test_appointment_shutdown_teos_trigger_while_offline(run_bitcoind):
509509

510510
# Check that the appointment is still in the Watcher
511511
appointment_info = get_appointment_info(locator)
512-
assert appointment_info.get("status") == "being_watched"
512+
assert appointment_info.get("status") == AppointmentStatus.BEING_WATCHED
513513
assert appointment_info.get("appointment") == appointment.to_dict()
514514

515515
# Shutdown and trigger
@@ -525,4 +525,4 @@ def test_appointment_shutdown_teos_trigger_while_offline(run_bitcoind):
525525

526526
# The appointment should have been moved to the Responder
527527
appointment_info = get_appointment_info(locator)
528-
assert appointment_info.get("status") == "dispute_responded"
528+
assert appointment_info.get("status") == AppointmentStatus.DISPUTE_RESPONDED

0 commit comments

Comments
 (0)