mirror of
https://github.com/aljazceru/python-teos.git
synced 2025-12-17 22:24:23 +01:00
Merge branch 'master' into chainmonitor
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# pisa-cli
|
# pisa_cli
|
||||||
|
|
||||||
`pisa-cli` is a command line interface to interact with the PISA server, written in Python3.
|
`pisa_cli` is a command line interface to interact with the PISA server, written in Python3.
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
Refer to [DEPENDENCIES.md](DEPENDENCIES.md)
|
Refer to [DEPENDENCIES.md](DEPENDENCIES.md)
|
||||||
@@ -11,7 +11,7 @@ Refer to [INSTALL.md](INSTALL.md)
|
|||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
python pisa-cli.py [global options] command [command options] [arguments]
|
python pisa_cli.py [global options] command [command options] [arguments]
|
||||||
|
|
||||||
#### Global options
|
#### Global options
|
||||||
|
|
||||||
@@ -54,7 +54,7 @@ The API will return a `text/plain` HTTP response code `200/OK` if the appointmen
|
|||||||
|
|
||||||
#### Usage
|
#### Usage
|
||||||
|
|
||||||
python pisa-cli add_appointment [command options] <appointment>/<path_to_appointment_file>
|
python pisa_cli add_appointment [command options] <appointment>/<path_to_appointment_file>
|
||||||
|
|
||||||
if `-f, --file` **is** specified, then the command expects a path to a json file instead of a json encoded
|
if `-f, --file` **is** specified, then the command expects a path to a json file instead of a json encoded
|
||||||
string as parameter.
|
string as parameter.
|
||||||
@@ -100,7 +100,7 @@ if `-f, --file` **is** specified, then the command expects a path to a json file
|
|||||||
|
|
||||||
#### Usage
|
#### Usage
|
||||||
|
|
||||||
python pisa-cli get_appointment <appointment_locator>
|
python pisa_cli get_appointment <appointment_locator>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -109,18 +109,18 @@ if `-f, --file` **is** specified, then the command expects a path to a json file
|
|||||||
Shows the list of commands or help about how to run a specific command.
|
Shows the list of commands or help about how to run a specific command.
|
||||||
|
|
||||||
#### Usage
|
#### Usage
|
||||||
python pisa-cli help
|
python pisa_cli help
|
||||||
|
|
||||||
or
|
or
|
||||||
|
|
||||||
python pisa-cli help command
|
python pisa_cli help command
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
1. Generate a new dummy appointment. **Note:** this appointment will never be fulfilled (it will eventually expire) since it does not corresopond to a valid transaction. However it can be used to interact with the PISA API.
|
1. Generate a new dummy appointment. **Note:** this appointment will never be fulfilled (it will eventually expire) since it does not corresopond to a valid transaction. However it can be used to interact with the PISA API.
|
||||||
|
|
||||||
```
|
```
|
||||||
python pisa-cli.py generate_dummy_appointment
|
python pisa_cli.py generate_dummy_appointment
|
||||||
```
|
```
|
||||||
|
|
||||||
That will create a json file that follows the appointment data structure filled with dummy data and store it in `dummy_appointment_data.json`.
|
That will create a json file that follows the appointment data structure filled with dummy data and store it in `dummy_appointment_data.json`.
|
||||||
@@ -128,7 +128,7 @@ or
|
|||||||
2. Send the appointment to the PISA API. Which will then start monitoring for matching transactions.
|
2. Send the appointment to the PISA API. Which will then start monitoring for matching transactions.
|
||||||
|
|
||||||
```
|
```
|
||||||
python pisa-cli.py add_appointment -f dummy_appointment_data.json
|
python pisa_cli.py add_appointment -f dummy_appointment_data.json
|
||||||
```
|
```
|
||||||
|
|
||||||
This returns a appointment locator that can be used to get updates about this appointment from PISA.
|
This returns a appointment locator that can be used to get updates about this appointment from PISA.
|
||||||
@@ -136,7 +136,7 @@ or
|
|||||||
3. Test that PISA is still watching the appointment by replacing the appointment locator received into the following command:
|
3. Test that PISA is still watching the appointment by replacing the appointment locator received into the following command:
|
||||||
|
|
||||||
```
|
```
|
||||||
python pisa-cli.py get_appointment <appointment_locator>
|
python pisa_cli.py get_appointment <appointment_locator>
|
||||||
```
|
```
|
||||||
|
|
||||||
## PISA API
|
## PISA API
|
||||||
|
|||||||
@@ -9,8 +9,8 @@ from getopt import getopt, GetoptError
|
|||||||
from requests import ConnectTimeout, ConnectionError
|
from requests import ConnectTimeout, ConnectionError
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
|
|
||||||
from apps.cli.blob import Blob
|
|
||||||
from apps.cli.help import help_add_appointment, help_get_appointment
|
from apps.cli.help import help_add_appointment, help_get_appointment
|
||||||
|
from apps.cli.blob import Blob
|
||||||
from apps.cli import (
|
from apps.cli import (
|
||||||
DEFAULT_PISA_API_SERVER,
|
DEFAULT_PISA_API_SERVER,
|
||||||
DEFAULT_PISA_API_PORT,
|
DEFAULT_PISA_API_PORT,
|
||||||
@@ -22,9 +22,8 @@ from apps.cli import (
|
|||||||
|
|
||||||
from common.logger import Logger
|
from common.logger import Logger
|
||||||
from common.appointment import Appointment
|
from common.appointment import Appointment
|
||||||
from common.constants import LOCATOR_LEN_HEX
|
|
||||||
from common.cryptographer import Cryptographer
|
from common.cryptographer import Cryptographer
|
||||||
from common.tools import check_sha256_hex_format
|
from common.tools import check_sha256_hex_format, compute_locator
|
||||||
|
|
||||||
|
|
||||||
HTTP_OK = 200
|
HTTP_OK = 200
|
||||||
@@ -46,11 +45,13 @@ def generate_dummy_appointment():
|
|||||||
"to_self_delay": 20,
|
"to_self_delay": 20,
|
||||||
}
|
}
|
||||||
|
|
||||||
print("Generating dummy appointment data:" "\n\n" + json.dumps(dummy_appointment_data, indent=4, sort_keys=True))
|
logger.info(
|
||||||
|
"Generating dummy appointment data:" "\n\n" + json.dumps(dummy_appointment_data, indent=4, sort_keys=True)
|
||||||
|
)
|
||||||
|
|
||||||
json.dump(dummy_appointment_data, open("dummy_appointment_data.json", "w"))
|
json.dump(dummy_appointment_data, open("dummy_appointment_data.json", "w"))
|
||||||
|
|
||||||
print("\nData stored in dummy_appointment_data.json")
|
logger.info("\nData stored in dummy_appointment_data.json")
|
||||||
|
|
||||||
|
|
||||||
# Loads and returns Pisa keys from disk
|
# Loads and returns Pisa keys from disk
|
||||||
@@ -61,11 +62,12 @@ def load_key_file_data(file_name):
|
|||||||
return key
|
return key
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
raise FileNotFoundError("File not found.")
|
logger.error("Client's key file not found. Please check your settings.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except IOError as e:
|
||||||
def compute_locator(tx_id):
|
logger.error("I/O error({}): {}".format(e.errno, e.strerror))
|
||||||
return tx_id[:LOCATOR_LEN_HEX]
|
return False
|
||||||
|
|
||||||
|
|
||||||
# Makes sure that the folder APPOINTMENTS_FOLDER_NAME exists, then saves the appointment and signature in it.
|
# Makes sure that the folder APPOINTMENTS_FOLDER_NAME exists, then saves the appointment and signature in it.
|
||||||
@@ -85,12 +87,81 @@ def save_signed_appointment(appointment, signature):
|
|||||||
|
|
||||||
|
|
||||||
def add_appointment(args):
|
def add_appointment(args):
|
||||||
appointment_data = None
|
# Get appointment data from user.
|
||||||
|
appointment_data = parse_add_appointment_args(args)
|
||||||
|
|
||||||
|
if appointment_data is None:
|
||||||
|
logger.error("The provided appointment JSON is empty")
|
||||||
|
return False
|
||||||
|
|
||||||
|
valid_txid = check_sha256_hex_format(appointment_data.get("tx_id"))
|
||||||
|
|
||||||
|
if not valid_txid:
|
||||||
|
logger.error("The provided txid is not valid")
|
||||||
|
return False
|
||||||
|
|
||||||
|
tx_id = appointment_data.get("tx_id")
|
||||||
|
tx = appointment_data.get("tx")
|
||||||
|
|
||||||
|
if None not in [tx_id, tx]:
|
||||||
|
appointment_data["locator"] = compute_locator(tx_id)
|
||||||
|
appointment_data["encrypted_blob"] = Cryptographer.encrypt(Blob(tx), tx_id)
|
||||||
|
|
||||||
|
else:
|
||||||
|
logger.error("Appointment data is missing some fields.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
appointment = Appointment.from_dict(appointment_data)
|
||||||
|
|
||||||
|
signature = get_appointment_signature(appointment)
|
||||||
|
hex_pk_der = get_pk()
|
||||||
|
|
||||||
|
if not (appointment and signature and hex_pk_der):
|
||||||
|
return False
|
||||||
|
|
||||||
|
data = {"appointment": appointment.to_dict(), "signature": signature, "public_key": hex_pk_der.decode("utf-8")}
|
||||||
|
|
||||||
|
appointment_json = json.dumps(data, sort_keys=True, separators=(",", ":"))
|
||||||
|
|
||||||
|
# Send appointment to the server.
|
||||||
|
add_appointment_endpoint = "http://{}:{}".format(pisa_api_server, pisa_api_port)
|
||||||
|
response_json = post_data_to_add_appointment_endpoint(add_appointment_endpoint, appointment_json)
|
||||||
|
|
||||||
|
if response_json is None:
|
||||||
|
return False
|
||||||
|
|
||||||
|
signature = response_json.get("signature")
|
||||||
|
# Check that the server signed the appointment as it should.
|
||||||
|
if signature is None:
|
||||||
|
logger.error("The response does not contain the signature of the appointment.")
|
||||||
|
return False
|
||||||
|
|
||||||
|
valid = check_signature(signature, appointment)
|
||||||
|
|
||||||
|
if not valid:
|
||||||
|
logger.error("The returned appointment's signature is invalid")
|
||||||
|
return False
|
||||||
|
|
||||||
|
logger.info("Appointment accepted and signed by Pisa")
|
||||||
|
# all good, store appointment and signature
|
||||||
|
try:
|
||||||
|
save_signed_appointment(appointment.to_dict(), signature)
|
||||||
|
|
||||||
|
except OSError as e:
|
||||||
|
logger.error("There was an error while saving the appointment", error=e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
# Parse arguments passed to add_appointment and handle them accordingly.
|
||||||
|
# Returns appointment data.
|
||||||
|
def parse_add_appointment_args(args):
|
||||||
use_help = "Use 'help add_appointment' for help of how to use the command"
|
use_help = "Use 'help add_appointment' for help of how to use the command"
|
||||||
|
|
||||||
if not args:
|
if not args:
|
||||||
logger.error("No appointment data provided. " + use_help)
|
logger.error("No appointment data provided. " + use_help)
|
||||||
return False
|
return None
|
||||||
|
|
||||||
arg_opt = args.pop(0)
|
arg_opt = args.pop(0)
|
||||||
|
|
||||||
@@ -102,7 +173,7 @@ def add_appointment(args):
|
|||||||
fin = args.pop(0)
|
fin = args.pop(0)
|
||||||
if not os.path.isfile(fin):
|
if not os.path.isfile(fin):
|
||||||
logger.error("Can't find file", filename=fin)
|
logger.error("Can't find file", filename=fin)
|
||||||
return False
|
return None
|
||||||
|
|
||||||
try:
|
try:
|
||||||
with open(fin) as f:
|
with open(fin) as f:
|
||||||
@@ -110,63 +181,19 @@ def add_appointment(args):
|
|||||||
|
|
||||||
except IOError as e:
|
except IOError as e:
|
||||||
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
||||||
return False
|
return None
|
||||||
else:
|
else:
|
||||||
appointment_data = json.loads(arg_opt)
|
appointment_data = json.loads(arg_opt)
|
||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
logger.error("Non-JSON encoded data provided as appointment. " + use_help)
|
logger.error("Non-JSON encoded data provided as appointment. " + use_help)
|
||||||
return False
|
return None
|
||||||
|
|
||||||
if not appointment_data:
|
return appointment_data
|
||||||
logger.error("The provided JSON is empty")
|
|
||||||
return False
|
|
||||||
|
|
||||||
valid_locator = check_sha256_hex_format(appointment_data.get("tx_id"))
|
|
||||||
|
|
||||||
if not valid_locator:
|
|
||||||
logger.error("The provided locator is not valid")
|
|
||||||
return False
|
|
||||||
|
|
||||||
add_appointment_endpoint = "http://{}:{}".format(pisa_api_server, pisa_api_port)
|
|
||||||
appointment = Appointment.from_dict(appointment_data)
|
|
||||||
|
|
||||||
try:
|
|
||||||
sk_der = load_key_file_data(CLI_PRIVATE_KEY)
|
|
||||||
cli_sk = Cryptographer.load_private_key_der(sk_der)
|
|
||||||
|
|
||||||
except ValueError:
|
|
||||||
logger.error("Failed to deserialize the public key. It might be in an unsupported format")
|
|
||||||
return False
|
|
||||||
|
|
||||||
except FileNotFoundError:
|
|
||||||
logger.error("Client's private key file not found. Please check your settings")
|
|
||||||
return False
|
|
||||||
|
|
||||||
except IOError as e:
|
|
||||||
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
|
||||||
return False
|
|
||||||
|
|
||||||
signature = Cryptographer.sign(appointment.serialize(), cli_sk)
|
|
||||||
|
|
||||||
try:
|
|
||||||
cli_pk_der = load_key_file_data(CLI_PUBLIC_KEY)
|
|
||||||
hex_pk_der = binascii.hexlify(cli_pk_der)
|
|
||||||
|
|
||||||
except FileNotFoundError:
|
|
||||||
logger.error("Client's public key file not found. Please check your settings")
|
|
||||||
return False
|
|
||||||
|
|
||||||
except IOError as e:
|
|
||||||
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
|
||||||
return False
|
|
||||||
|
|
||||||
# FIXME: Exceptions for hexlify need to be covered
|
|
||||||
|
|
||||||
data = {"appointment": appointment, "signature": signature, "public_key": hex_pk_der.decode("utf-8")}
|
|
||||||
|
|
||||||
appointment_json = json.dumps(data, sort_keys=True, separators=(",", ":"))
|
|
||||||
|
|
||||||
|
# Sends appointment data to add_appointment endpoint to be processed by the server.
|
||||||
|
def post_data_to_add_appointment_endpoint(add_appointment_endpoint, appointment_json):
|
||||||
logger.info("Sending appointment to PISA")
|
logger.info("Sending appointment to PISA")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -176,15 +203,15 @@ def add_appointment(args):
|
|||||||
|
|
||||||
except json.JSONDecodeError:
|
except json.JSONDecodeError:
|
||||||
logger.error("The response was not valid JSON")
|
logger.error("The response was not valid JSON")
|
||||||
return False
|
return None
|
||||||
|
|
||||||
except ConnectTimeout:
|
except ConnectTimeout:
|
||||||
logger.error("Can't connect to pisa API. Connection timeout")
|
logger.error("Can't connect to pisa API. Connection timeout")
|
||||||
return False
|
return None
|
||||||
|
|
||||||
except ConnectionError:
|
except ConnectionError:
|
||||||
logger.error("Can't connect to pisa API. Server cannot be reached")
|
logger.error("Can't connect to pisa API. Server cannot be reached")
|
||||||
return False
|
return None
|
||||||
|
|
||||||
if r.status_code != HTTP_OK:
|
if r.status_code != HTTP_OK:
|
||||||
if "error" not in response_json:
|
if "error" not in response_json:
|
||||||
@@ -196,14 +223,17 @@ def add_appointment(args):
|
|||||||
status_code=r.status_code,
|
status_code=r.status_code,
|
||||||
description=error,
|
description=error,
|
||||||
)
|
)
|
||||||
return False
|
return None
|
||||||
|
|
||||||
if "signature" not in response_json:
|
if "signature" not in response_json:
|
||||||
logger.error("The response does not contain the signature of the appointment")
|
logger.error("The response does not contain the signature of the appointment")
|
||||||
return False
|
return None
|
||||||
|
|
||||||
signature = response_json["signature"]
|
return response_json
|
||||||
# verify that the returned signature is valid
|
|
||||||
|
|
||||||
|
# Verify that the signature returned from the watchtower is valid.
|
||||||
|
def check_signature(signature, appointment):
|
||||||
try:
|
try:
|
||||||
pisa_pk_der = load_key_file_data(PISA_PUBLIC_KEY)
|
pisa_pk_der = load_key_file_data(PISA_PUBLIC_KEY)
|
||||||
pisa_pk = Cryptographer.load_public_key_der(pisa_pk_der)
|
pisa_pk = Cryptographer.load_public_key_der(pisa_pk_der)
|
||||||
@@ -212,7 +242,7 @@ def add_appointment(args):
|
|||||||
logger.error("Failed to deserialize the public key. It might be in an unsupported format")
|
logger.error("Failed to deserialize the public key. It might be in an unsupported format")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
is_sig_valid = Cryptographer.verify(appointment.serialize(), signature, pisa_pk)
|
return Cryptographer.verify(appointment.serialize(), signature, pisa_pk)
|
||||||
|
|
||||||
except FileNotFoundError:
|
except FileNotFoundError:
|
||||||
logger.error("Pisa's public key file not found. Please check your settings")
|
logger.error("Pisa's public key file not found. Please check your settings")
|
||||||
@@ -222,21 +252,6 @@ def add_appointment(args):
|
|||||||
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
||||||
return False
|
return False
|
||||||
|
|
||||||
if not is_sig_valid:
|
|
||||||
logger.error("The returned appointment's signature is invalid")
|
|
||||||
return False
|
|
||||||
|
|
||||||
logger.info("Appointment accepted and signed by Pisa")
|
|
||||||
# all good, store appointment and signature
|
|
||||||
try:
|
|
||||||
save_signed_appointment(appointment, signature)
|
|
||||||
|
|
||||||
except OSError as e:
|
|
||||||
logger.error("There was an error while saving the appointment", error=e)
|
|
||||||
return False
|
|
||||||
|
|
||||||
return True
|
|
||||||
|
|
||||||
|
|
||||||
def get_appointment(args):
|
def get_appointment(args):
|
||||||
if not args:
|
if not args:
|
||||||
@@ -260,8 +275,9 @@ def get_appointment(args):
|
|||||||
|
|
||||||
try:
|
try:
|
||||||
r = requests.get(url=get_appointment_endpoint + parameters, timeout=5)
|
r = requests.get(url=get_appointment_endpoint + parameters, timeout=5)
|
||||||
|
logger.info("Appointment response returned from server: " + str(r))
|
||||||
|
return True
|
||||||
|
|
||||||
print(json.dumps(r.json(), indent=4, sort_keys=True))
|
|
||||||
except ConnectTimeout:
|
except ConnectTimeout:
|
||||||
logger.error("Can't connect to pisa API. Connection timeout")
|
logger.error("Can't connect to pisa API. Connection timeout")
|
||||||
return False
|
return False
|
||||||
@@ -270,7 +286,47 @@ def get_appointment(args):
|
|||||||
logger.error("Can't connect to pisa API. Server cannot be reached")
|
logger.error("Can't connect to pisa API. Server cannot be reached")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
return True
|
|
||||||
|
def get_appointment_signature(appointment):
|
||||||
|
try:
|
||||||
|
sk_der = load_key_file_data(CLI_PRIVATE_KEY)
|
||||||
|
cli_sk = Cryptographer.load_private_key_der(sk_der)
|
||||||
|
|
||||||
|
signature = Cryptographer.sign(appointment.serialize(), cli_sk)
|
||||||
|
|
||||||
|
return signature
|
||||||
|
|
||||||
|
except ValueError:
|
||||||
|
logger.error("Failed to deserialize the public key. It might be in an unsupported format")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except FileNotFoundError:
|
||||||
|
logger.error("Client's private key file not found. Please check your settings")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except IOError as e:
|
||||||
|
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def get_pk():
|
||||||
|
try:
|
||||||
|
cli_pk_der = load_key_file_data(CLI_PUBLIC_KEY)
|
||||||
|
hex_pk_der = binascii.hexlify(cli_pk_der)
|
||||||
|
|
||||||
|
return hex_pk_der
|
||||||
|
|
||||||
|
except FileNotFoundError:
|
||||||
|
logger.error("Client's public key file not found. Please check your settings")
|
||||||
|
return False
|
||||||
|
|
||||||
|
except IOError as e:
|
||||||
|
logger.error("I/O error", errno=e.errno, error=e.strerror)
|
||||||
|
return False
|
||||||
|
|
||||||
|
except binascii.Error as e:
|
||||||
|
logger.error("Could not successfully encode public key as hex: ", e)
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
def show_usage():
|
def show_usage():
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import re
|
import re
|
||||||
|
from common.constants import LOCATOR_LEN_HEX
|
||||||
|
|
||||||
|
|
||||||
def check_sha256_hex_format(value):
|
def check_sha256_hex_format(value):
|
||||||
@@ -12,3 +13,15 @@ def check_sha256_hex_format(value):
|
|||||||
:mod:`bool`: Whether or not the value matches the format.
|
:mod:`bool`: Whether or not the value matches the format.
|
||||||
"""
|
"""
|
||||||
return isinstance(value, str) and re.match(r"^[0-9A-Fa-f]{64}$", value) is not None
|
return isinstance(value, str) and re.match(r"^[0-9A-Fa-f]{64}$", value) is not None
|
||||||
|
|
||||||
|
|
||||||
|
def compute_locator(tx_id):
|
||||||
|
"""
|
||||||
|
Computes an appointment locator given a transaction id.
|
||||||
|
Args:
|
||||||
|
tx_id (:obj:`str`): the transaction id used to compute the locator.
|
||||||
|
Returns:
|
||||||
|
(:obj:`str`): The computed locator.
|
||||||
|
"""
|
||||||
|
|
||||||
|
return tx_id[:LOCATOR_LEN_HEX]
|
||||||
|
|||||||
21
pisa/api.py
21
pisa/api.py
@@ -17,21 +17,22 @@ logger = Logger("API")
|
|||||||
|
|
||||||
|
|
||||||
class API:
|
class API:
|
||||||
def __init__(self, watcher):
|
def __init__(self, watcher, config):
|
||||||
self.watcher = watcher
|
self.watcher = watcher
|
||||||
|
self.config = config
|
||||||
|
|
||||||
def add_appointment(self):
|
def add_appointment(self):
|
||||||
"""
|
"""
|
||||||
Main endpoint of the Watchtower.
|
Main endpoint of the Watchtower.
|
||||||
|
|
||||||
The client sends requests (appointments) to this endpoint to request a job to the Watchtower. Requests must be json
|
The client sends requests (appointments) to this endpoint to request a job to the Watchtower. Requests must be
|
||||||
encoded and contain an ``appointment`` field and optionally a ``signature`` and ``public_key`` fields.
|
json encoded and contain an ``appointment`` field and optionally a ``signature`` and ``public_key`` fields.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:obj:`tuple`: A tuple containing the response (``json``) and response code (``int``). For accepted appointments,
|
:obj:`tuple`: A tuple containing the response (``json``) and response code (``int``). For accepted
|
||||||
the ``rcode`` is always 0 and the response contains the signed receipt. For rejected appointments, the ``rcode``
|
appointments, the ``rcode`` is always 0 and the response contains the signed receipt. For rejected
|
||||||
is a negative value and the response contains the error message. Error messages can be found at
|
appointments, the ``rcode`` is a negative value and the response contains the error message. Error messages
|
||||||
:mod:`Errors <pisa.errors>`.
|
can be found at :mod:`Errors <pisa.errors>`.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
remote_addr = request.environ.get("REMOTE_ADDR")
|
remote_addr = request.environ.get("REMOTE_ADDR")
|
||||||
@@ -41,7 +42,7 @@ class API:
|
|||||||
|
|
||||||
# Check content type once if properly defined
|
# Check content type once if properly defined
|
||||||
request_data = json.loads(request.get_json())
|
request_data = json.loads(request.get_json())
|
||||||
inspector = Inspector()
|
inspector = Inspector(self.config)
|
||||||
appointment = inspector.inspect(
|
appointment = inspector.inspect(
|
||||||
request_data.get("appointment"), request_data.get("signature"), request_data.get("public_key")
|
request_data.get("appointment"), request_data.get("signature"), request_data.get("public_key")
|
||||||
)
|
)
|
||||||
@@ -166,8 +167,8 @@ class API:
|
|||||||
"""
|
"""
|
||||||
Provides the block height of the Watchtower.
|
Provides the block height of the Watchtower.
|
||||||
|
|
||||||
This is a testing endpoint that (most likely) will be removed in production. Its purpose is to give information to
|
This is a testing endpoint that (most likely) will be removed in production. Its purpose is to give information
|
||||||
testers about the current block so they can define a dummy appointment without having to run a bitcoin node.
|
to testers about the current block so they can define a dummy appointment without having to run a bitcoin node.
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
:obj:`dict`: A json encoded dictionary containing the block height.
|
:obj:`dict`: A json encoded dictionary containing the block height.
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ from common.constants import LOCATOR_LEN_HEX
|
|||||||
from common.cryptographer import Cryptographer
|
from common.cryptographer import Cryptographer
|
||||||
|
|
||||||
from pisa import errors
|
from pisa import errors
|
||||||
import pisa.conf as conf
|
|
||||||
from common.logger import Logger
|
from common.logger import Logger
|
||||||
from common.appointment import Appointment
|
from common.appointment import Appointment
|
||||||
from pisa.block_processor import BlockProcessor
|
from pisa.block_processor import BlockProcessor
|
||||||
@@ -23,6 +22,9 @@ class Inspector:
|
|||||||
The :class:`Inspector` class is in charge of verifying that the appointment data provided by the user is correct.
|
The :class:`Inspector` class is in charge of verifying that the appointment data provided by the user is correct.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
|
def __init__(self, config):
|
||||||
|
self.config = config
|
||||||
|
|
||||||
def inspect(self, appointment_data, signature, public_key):
|
def inspect(self, appointment_data, signature, public_key):
|
||||||
"""
|
"""
|
||||||
Inspects whether the data provided by the user is correct.
|
Inspects whether the data provided by the user is correct.
|
||||||
@@ -221,8 +223,7 @@ class Inspector:
|
|||||||
|
|
||||||
return rcode, message
|
return rcode, message
|
||||||
|
|
||||||
@staticmethod
|
def check_to_self_delay(self, to_self_delay):
|
||||||
def check_to_self_delay(to_self_delay):
|
|
||||||
"""
|
"""
|
||||||
Checks if the provided ``to_self_delay`` is correct.
|
Checks if the provided ``to_self_delay`` is correct.
|
||||||
|
|
||||||
@@ -255,10 +256,10 @@ class Inspector:
|
|||||||
rcode = errors.APPOINTMENT_WRONG_FIELD_TYPE
|
rcode = errors.APPOINTMENT_WRONG_FIELD_TYPE
|
||||||
message = "wrong to_self_delay data type ({})".format(t)
|
message = "wrong to_self_delay data type ({})".format(t)
|
||||||
|
|
||||||
elif to_self_delay < conf.MIN_TO_SELF_DELAY:
|
elif to_self_delay < self.config.get("MIN_TO_SELF_DELAY"):
|
||||||
rcode = errors.APPOINTMENT_FIELD_TOO_SMALL
|
rcode = errors.APPOINTMENT_FIELD_TOO_SMALL
|
||||||
message = "to_self_delay too small. The to_self_delay should be at least {} (current: {})".format(
|
message = "to_self_delay too small. The to_self_delay should be at least {} (current: {})".format(
|
||||||
conf.MIN_TO_SELF_DELAY, to_self_delay
|
self.config.get("MIN_TO_SELF_DELAY"), to_self_delay
|
||||||
)
|
)
|
||||||
|
|
||||||
if message is not None:
|
if message is not None:
|
||||||
|
|||||||
@@ -2,12 +2,11 @@ from getopt import getopt
|
|||||||
from sys import argv, exit
|
from sys import argv, exit
|
||||||
from signal import signal, SIGINT, SIGQUIT, SIGTERM
|
from signal import signal, SIGINT, SIGQUIT, SIGTERM
|
||||||
|
|
||||||
from pisa.conf import DB_PATH
|
|
||||||
from common.logger import Logger
|
from common.logger import Logger
|
||||||
from pisa.api import API
|
from pisa.api import API
|
||||||
from pisa.watcher import Watcher
|
from pisa.watcher import Watcher
|
||||||
from pisa.builder import Builder
|
from pisa.builder import Builder
|
||||||
from pisa.conf import BTC_NETWORK, PISA_SECRET_KEY
|
import pisa.conf as conf
|
||||||
from pisa.db_manager import DBManager
|
from pisa.db_manager import DBManager
|
||||||
from pisa.chain_monitor import ChainMonitor
|
from pisa.chain_monitor import ChainMonitor
|
||||||
from pisa.block_processor import BlockProcessor
|
from pisa.block_processor import BlockProcessor
|
||||||
@@ -25,6 +24,53 @@ def handle_signals(signal_received, frame):
|
|||||||
exit(0)
|
exit(0)
|
||||||
|
|
||||||
|
|
||||||
|
def load_config(config):
|
||||||
|
"""
|
||||||
|
Looks through all of the config options to make sure they contain the right type of data and builds a config
|
||||||
|
dictionary.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
config (:obj:`module`): It takes in a config module object.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
:obj:`dict` A dictionary containing the config values.
|
||||||
|
"""
|
||||||
|
|
||||||
|
conf_dict = {}
|
||||||
|
|
||||||
|
conf_fields = {
|
||||||
|
"BTC_RPC_USER": {"value": config.BTC_RPC_USER, "type": str},
|
||||||
|
"BTC_RPC_PASSWD": {"value": config.BTC_RPC_PASSWD, "type": str},
|
||||||
|
"BTC_RPC_HOST": {"value": config.BTC_RPC_HOST, "type": str},
|
||||||
|
"BTC_RPC_PORT": {"value": config.BTC_RPC_PORT, "type": int},
|
||||||
|
"BTC_NETWORK": {"value": config.BTC_NETWORK, "type": str},
|
||||||
|
"FEED_PROTOCOL": {"value": config.FEED_PROTOCOL, "type": str},
|
||||||
|
"FEED_ADDR": {"value": config.FEED_ADDR, "type": str},
|
||||||
|
"FEED_PORT": {"value": config.FEED_PORT, "type": int},
|
||||||
|
"MAX_APPOINTMENTS": {"value": config.MAX_APPOINTMENTS, "type": int},
|
||||||
|
"EXPIRY_DELTA": {"value": config.EXPIRY_DELTA, "type": int},
|
||||||
|
"MIN_TO_SELF_DELAY": {"value": config.MIN_TO_SELF_DELAY, "type": int},
|
||||||
|
"SERVER_LOG_FILE": {"value": config.SERVER_LOG_FILE, "type": str},
|
||||||
|
"PISA_SECRET_KEY": {"value": config.PISA_SECRET_KEY, "type": str},
|
||||||
|
"CLIENT_LOG_FILE": {"value": config.CLIENT_LOG_FILE, "type": str},
|
||||||
|
"TEST_LOG_FILE": {"value": config.TEST_LOG_FILE, "type": str},
|
||||||
|
"DB_PATH": {"value": config.DB_PATH, "type": str},
|
||||||
|
}
|
||||||
|
|
||||||
|
for field in conf_fields:
|
||||||
|
value = conf_fields[field]["value"]
|
||||||
|
correct_type = conf_fields[field]["type"]
|
||||||
|
|
||||||
|
if (value is not None) and isinstance(value, correct_type):
|
||||||
|
conf_dict[field] = value
|
||||||
|
else:
|
||||||
|
err_msg = "{} variable in config is of the wrong type".format(field)
|
||||||
|
logger.error(err_msg)
|
||||||
|
raise ValueError(err_msg)
|
||||||
|
|
||||||
|
return conf_dict
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
logger.info("Starting PISA")
|
logger.info("Starting PISA")
|
||||||
|
|
||||||
@@ -37,15 +83,17 @@ if __name__ == "__main__":
|
|||||||
# FIXME: Leaving this here for future option/arguments
|
# FIXME: Leaving this here for future option/arguments
|
||||||
pass
|
pass
|
||||||
|
|
||||||
|
pisa_config = load_config(conf)
|
||||||
|
|
||||||
if not can_connect_to_bitcoind():
|
if not can_connect_to_bitcoind():
|
||||||
logger.error("Can't connect to bitcoind. Shutting down")
|
logger.error("Can't connect to bitcoind. Shutting down")
|
||||||
|
|
||||||
elif not in_correct_network(BTC_NETWORK):
|
elif not in_correct_network(pisa_config.get("BTC_NETWORK")):
|
||||||
logger.error("bitcoind is running on a different network, check conf.py and bitcoin.conf. Shutting down")
|
logger.error("bitcoind is running on a different network, check conf.py and bitcoin.conf. Shutting down")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
db_manager = DBManager(DB_PATH)
|
db_manager = DBManager(pisa_config.get("DB_PATH"))
|
||||||
|
|
||||||
# Create the chain monitor and start monitoring the chain
|
# Create the chain monitor and start monitoring the chain
|
||||||
chain_monitor = ChainMonitor()
|
chain_monitor = ChainMonitor()
|
||||||
@@ -54,10 +102,10 @@ if __name__ == "__main__":
|
|||||||
watcher_appointments_data = db_manager.load_watcher_appointments()
|
watcher_appointments_data = db_manager.load_watcher_appointments()
|
||||||
responder_trackers_data = db_manager.load_responder_trackers()
|
responder_trackers_data = db_manager.load_responder_trackers()
|
||||||
|
|
||||||
with open(PISA_SECRET_KEY, "rb") as key_file:
|
with open(pisa_config.get("PISA_SECRET_KEY"), "rb") as key_file:
|
||||||
secret_key_der = key_file.read()
|
secret_key_der = key_file.read()
|
||||||
|
|
||||||
watcher = Watcher(db_manager, chain_monitor, secret_key_der)
|
watcher = Watcher(db_manager, chain_monitor, secret_key_der, pisa_config)
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
||||||
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
||||||
|
|
||||||
@@ -103,7 +151,7 @@ if __name__ == "__main__":
|
|||||||
watcher.block_queue = Builder.build_block_queue(missed_blocks_watcher)
|
watcher.block_queue = Builder.build_block_queue(missed_blocks_watcher)
|
||||||
|
|
||||||
# Fire the API
|
# Fire the API
|
||||||
API(watcher).start()
|
API(watcher, config=pisa_config).start()
|
||||||
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error("An error occurred: {}. Shutting down".format(e))
|
logger.error("An error occurred: {}. Shutting down".format(e))
|
||||||
|
|||||||
@@ -467,9 +467,6 @@ class Responder:
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
# If the penalty transaction is missing, we need to reset the tracker.
|
# If the penalty transaction is missing, we need to reset the tracker.
|
||||||
# DISCUSS: Adding tracker back, should we flag it as retried?
|
|
||||||
# FIXME: Whether we decide to increase the retried counter or not, the current counter should be
|
|
||||||
# maintained. There is no way of doing so with the current approach. Update if required
|
|
||||||
self.handle_breach(
|
self.handle_breach(
|
||||||
tracker.locator,
|
tracker.locator,
|
||||||
uuid,
|
uuid,
|
||||||
|
|||||||
36
pisa/utils/zmq_subscriber.py
Normal file
36
pisa/utils/zmq_subscriber.py
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
import zmq
|
||||||
|
import binascii
|
||||||
|
from common.logger import Logger
|
||||||
|
from pisa.conf import FEED_PROTOCOL, FEED_ADDR, FEED_PORT
|
||||||
|
|
||||||
|
|
||||||
|
# ToDo: #7-add-async-back-to-zmq
|
||||||
|
class ZMQSubscriber:
|
||||||
|
""" Adapted from https://github.com/bitcoin/bitcoin/blob/master/contrib/zmq/zmq_sub.py"""
|
||||||
|
|
||||||
|
def __init__(self, config, parent):
|
||||||
|
self.zmqContext = zmq.Context()
|
||||||
|
self.zmqSubSocket = self.zmqContext.socket(zmq.SUB)
|
||||||
|
self.zmqSubSocket.setsockopt(zmq.RCVHWM, 0)
|
||||||
|
self.zmqSubSocket.setsockopt_string(zmq.SUBSCRIBE, "hashblock")
|
||||||
|
self.zmqSubSocket.connect(
|
||||||
|
"%s://%s:%s" % (config.get("FEED_PROTOCOL"), config.get("FEED_ADDR"), config.get("FEED_PORT"))
|
||||||
|
)
|
||||||
|
self.logger = Logger("ZMQSubscriber-{}".format(parent))
|
||||||
|
|
||||||
|
self.terminate = False
|
||||||
|
|
||||||
|
def handle(self, block_queue):
|
||||||
|
while not self.terminate:
|
||||||
|
msg = self.zmqSubSocket.recv_multipart()
|
||||||
|
|
||||||
|
# Terminate could have been set wile the thread was blocked in recv
|
||||||
|
if not self.terminate:
|
||||||
|
topic = msg[0]
|
||||||
|
body = msg[1]
|
||||||
|
|
||||||
|
if topic == b"hashblock":
|
||||||
|
block_hash = binascii.hexlify(body).decode("utf-8")
|
||||||
|
block_queue.put(block_hash)
|
||||||
|
|
||||||
|
self.logger.info("New block received via ZMQ", block_hash=block_hash)
|
||||||
@@ -3,13 +3,12 @@ from queue import Queue
|
|||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
|
||||||
from common.cryptographer import Cryptographer
|
from common.cryptographer import Cryptographer
|
||||||
from common.constants import LOCATOR_LEN_HEX
|
from common.tools import compute_locator
|
||||||
|
|
||||||
from common.logger import Logger
|
from common.logger import Logger
|
||||||
from pisa.cleaner import Cleaner
|
from pisa.cleaner import Cleaner
|
||||||
from pisa.responder import Responder
|
from pisa.responder import Responder
|
||||||
from pisa.block_processor import BlockProcessor
|
from pisa.block_processor import BlockProcessor
|
||||||
from pisa.conf import EXPIRY_DELTA, MAX_APPOINTMENTS
|
|
||||||
|
|
||||||
logger = Logger("Watcher")
|
logger = Logger("Watcher")
|
||||||
|
|
||||||
@@ -31,11 +30,13 @@ class Watcher:
|
|||||||
|
|
||||||
Args:
|
Args:
|
||||||
db_manager (:obj:`DBManager <pisa.db_manager>`): a ``DBManager`` instance to interact with the database.
|
db_manager (:obj:`DBManager <pisa.db_manager>`): a ``DBManager`` instance to interact with the database.
|
||||||
|
chain_monitor (:obj:`ChainMonitor <pisa.chain_monitor.ChainMonitor>`): a ``ChainMonitor`` instance used to track
|
||||||
|
new blocks received by ``bitcoind``.
|
||||||
sk_der (:obj:`bytes`): a DER encoded private key used to sign appointment receipts (signaling acceptance).
|
sk_der (:obj:`bytes`): a DER encoded private key used to sign appointment receipts (signaling acceptance).
|
||||||
|
config (:obj:`dict`): a dictionary containing all the configuration parameters. Used locally to retrieve
|
||||||
|
``MAX_APPOINTMENTS`` and ``EXPIRY_DELTA``.
|
||||||
responder (:obj:`Responder <pisa.responder.Responder>`): a ``Responder`` instance. If ``None`` is passed, a new
|
responder (:obj:`Responder <pisa.responder.Responder>`): a ``Responder`` instance. If ``None`` is passed, a new
|
||||||
instance is created. Populated instances are useful when bootstrapping the system from backed-up data.
|
instance is created. Populated instances are useful when bootstrapping the system from backed-up data.
|
||||||
max_appointments(:obj:`int`): the maximum amount of appointments that the :obj:`Watcher` will keep at any given
|
|
||||||
time. Defaults to ``MAX_APPOINTMENTS``.
|
|
||||||
|
|
||||||
|
|
||||||
Attributes:
|
Attributes:
|
||||||
@@ -46,44 +47,31 @@ class Watcher:
|
|||||||
asleep (:obj:`bool`): A flag that signals whether the :obj:`Watcher` is asleep or awake.
|
asleep (:obj:`bool`): A flag that signals whether the :obj:`Watcher` is asleep or awake.
|
||||||
block_queue (:obj:`Queue`): A queue used by the :obj:`Watcher` to receive block hashes from ``bitcoind``. It is
|
block_queue (:obj:`Queue`): A queue used by the :obj:`Watcher` to receive block hashes from ``bitcoind``. It is
|
||||||
populated by the :obj:`ChainMonitor <pisa.chain_monitor.ChainMonitor>`.
|
populated by the :obj:`ChainMonitor <pisa.chain_monitor.ChainMonitor>`.
|
||||||
max_appointments(:obj:`int`): the maximum amount of appointments that the :obj:`Watcher` will keep at any given
|
|
||||||
time.
|
|
||||||
chain_monitor (:obj:`ChainMonitor <pisa.chain_monitor.ChainMonitor>`): a ``ChainMonitor`` instance used to track
|
chain_monitor (:obj:`ChainMonitor <pisa.chain_monitor.ChainMonitor>`): a ``ChainMonitor`` instance used to track
|
||||||
new blocks received by ``bitcoind``.
|
new blocks received by ``bitcoind``.
|
||||||
|
config (:obj:`dict`): a dictionary containing all the configuration parameters. Used locally to retrieve
|
||||||
|
``MAX_APPOINTMENTS`` and ``EXPIRY_DELTA``.
|
||||||
db_manager (:obj:`DBManager <pisa.db_manager>`): A db manager instance to interact with the database.
|
db_manager (:obj:`DBManager <pisa.db_manager>`): A db manager instance to interact with the database.
|
||||||
|
signing_key (:mod:`EllipticCurvePrivateKey`): a private key used to sign accepted appointments.
|
||||||
|
|
||||||
Raises:
|
Raises:
|
||||||
ValueError: if `pisa_sk_file` is not found.
|
ValueError: if `pisa_sk_file` is not found.
|
||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, db_manager, chain_monitor, sk_der, responder=None, max_appointments=MAX_APPOINTMENTS):
|
def __init__(self, db_manager, chain_monitor, sk_der, config, responder=None):
|
||||||
self.appointments = dict()
|
self.appointments = dict()
|
||||||
self.locator_uuid_map = dict()
|
self.locator_uuid_map = dict()
|
||||||
self.asleep = True
|
self.asleep = True
|
||||||
self.block_queue = Queue()
|
self.block_queue = Queue()
|
||||||
self.max_appointments = max_appointments
|
|
||||||
self.chain_monitor = chain_monitor
|
self.chain_monitor = chain_monitor
|
||||||
|
self.config = config
|
||||||
self.db_manager = db_manager
|
self.db_manager = db_manager
|
||||||
self.signing_key = Cryptographer.load_private_key_der(sk_der)
|
self.signing_key = Cryptographer.load_private_key_der(sk_der)
|
||||||
|
|
||||||
if not isinstance(responder, Responder):
|
if not isinstance(responder, Responder):
|
||||||
self.responder = Responder(db_manager, chain_monitor)
|
self.responder = Responder(db_manager, chain_monitor)
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def compute_locator(tx_id):
|
|
||||||
"""
|
|
||||||
Computes an appointment locator given a transaction id.
|
|
||||||
|
|
||||||
Args:
|
|
||||||
tx_id (:obj:`str`): the transaction id used to compute the locator.
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
(:obj:`str`): The computed locator.
|
|
||||||
"""
|
|
||||||
|
|
||||||
return tx_id[:LOCATOR_LEN_HEX]
|
|
||||||
|
|
||||||
def add_appointment(self, appointment):
|
def add_appointment(self, appointment):
|
||||||
"""
|
"""
|
||||||
Adds a new appointment to the ``appointments`` dictionary if ``max_appointments`` has not been reached.
|
Adds a new appointment to the ``appointments`` dictionary if ``max_appointments`` has not been reached.
|
||||||
@@ -114,7 +102,7 @@ class Watcher:
|
|||||||
|
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if len(self.appointments) < self.max_appointments:
|
if len(self.appointments) < self.config.get("MAX_APPOINTMENTS"):
|
||||||
uuid = uuid4().hex
|
uuid = uuid4().hex
|
||||||
self.appointments[uuid] = appointment
|
self.appointments[uuid] = appointment
|
||||||
|
|
||||||
@@ -170,7 +158,7 @@ class Watcher:
|
|||||||
expired_appointments = [
|
expired_appointments = [
|
||||||
uuid
|
uuid
|
||||||
for uuid, appointment in self.appointments.items()
|
for uuid, appointment in self.appointments.items()
|
||||||
if block["height"] > appointment.end_time + EXPIRY_DELTA
|
if block["height"] > appointment.end_time + self.config.get("EXPIRY_DELTA")
|
||||||
]
|
]
|
||||||
|
|
||||||
Cleaner.delete_expired_appointment(
|
Cleaner.delete_expired_appointment(
|
||||||
@@ -225,7 +213,7 @@ class Watcher:
|
|||||||
found.
|
found.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
potential_locators = {Watcher.compute_locator(txid): txid for txid in txids}
|
potential_locators = {compute_locator(txid): txid for txid in txids}
|
||||||
|
|
||||||
# Check is any of the tx_ids in the received block is an actual match
|
# Check is any of the tx_ids in the received block is an actual match
|
||||||
intersection = set(self.locator_uuid_map.keys()).intersection(potential_locators.keys())
|
intersection = set(self.locator_uuid_map.keys()).intersection(potential_locators.keys())
|
||||||
|
|||||||
@@ -1,23 +1,41 @@
|
|||||||
import responses
|
import responses
|
||||||
import json
|
import json
|
||||||
|
import os
|
||||||
|
import shutil
|
||||||
from binascii import hexlify
|
from binascii import hexlify
|
||||||
|
|
||||||
from cryptography.hazmat.backends import default_backend
|
from cryptography.hazmat.backends import default_backend
|
||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import serialization
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
|
|
||||||
|
from common.appointment import Appointment
|
||||||
|
from common.cryptographer import Cryptographer
|
||||||
|
|
||||||
import apps.cli.pisa_cli as pisa_cli
|
import apps.cli.pisa_cli as pisa_cli
|
||||||
from test.apps.cli.unit.conftest import get_random_value_hex
|
from test.apps.cli.unit.conftest import get_random_value_hex
|
||||||
|
|
||||||
# TODO: should find a way of doing without this
|
|
||||||
from apps.cli.pisa_cli import build_appointment
|
|
||||||
|
|
||||||
# dummy keys for the tests
|
# dummy keys for the tests
|
||||||
pisa_sk = ec.generate_private_key(ec.SECP256K1, default_backend())
|
pisa_sk = ec.generate_private_key(ec.SECP256K1, default_backend())
|
||||||
pisa_pk = pisa_sk.public_key()
|
pisa_pk = pisa_sk.public_key()
|
||||||
|
|
||||||
other_sk = ec.generate_private_key(ec.SECP256K1, default_backend())
|
other_sk = ec.generate_private_key(ec.SECP256K1, default_backend())
|
||||||
|
|
||||||
|
pisa_sk_der = pisa_sk.private_bytes(
|
||||||
|
encoding=serialization.Encoding.DER,
|
||||||
|
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
||||||
|
encryption_algorithm=serialization.NoEncryption(),
|
||||||
|
)
|
||||||
|
pisa_pk_der = pisa_pk.public_bytes(
|
||||||
|
encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||||
|
)
|
||||||
|
|
||||||
|
other_sk_der = other_sk.private_bytes(
|
||||||
|
encoding=serialization.Encoding.DER,
|
||||||
|
format=serialization.PrivateFormat.TraditionalOpenSSL,
|
||||||
|
encryption_algorithm=serialization.NoEncryption(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
# Replace the key in the module with a key we control for the tests
|
# Replace the key in the module with a key we control for the tests
|
||||||
pisa_cli.pisa_public_key = pisa_pk
|
pisa_cli.pisa_public_key = pisa_pk
|
||||||
# Replace endpoint with dummy one
|
# Replace endpoint with dummy one
|
||||||
@@ -32,18 +50,47 @@ dummy_appointment_request = {
|
|||||||
"end_time": 50000,
|
"end_time": 50000,
|
||||||
"to_self_delay": 200,
|
"to_self_delay": 200,
|
||||||
}
|
}
|
||||||
dummy_appointment = build_appointment(**dummy_appointment_request)
|
|
||||||
|
|
||||||
# FIXME: USE CRYPTOGRAPHER
|
# This is the format appointment turns into once it hits "add_appointment"
|
||||||
|
dummy_appointment_full = {
|
||||||
|
"locator": get_random_value_hex(32),
|
||||||
|
"start_time": 1500,
|
||||||
|
"end_time": 50000,
|
||||||
|
"to_self_delay": 200,
|
||||||
|
"encrypted_blob": get_random_value_hex(120),
|
||||||
|
}
|
||||||
|
|
||||||
|
dummy_appointment = Appointment.from_dict(dummy_appointment_full)
|
||||||
|
|
||||||
|
|
||||||
def sign_appointment(sk, appointment):
|
def get_dummy_pisa_sk_der(*args):
|
||||||
data = json.dumps(appointment, sort_keys=True, separators=(",", ":")).encode("utf-8")
|
return pisa_sk_der
|
||||||
return hexlify(sk.sign(data, ec.ECDSA(hashes.SHA256()))).decode("utf-8")
|
|
||||||
|
|
||||||
|
|
||||||
def get_dummy_pisa_pk(der_data):
|
def get_dummy_pisa_pk_der(*args):
|
||||||
return pisa_pk
|
return pisa_pk_der
|
||||||
|
|
||||||
|
|
||||||
|
def get_dummy_hex_pk_der(*args):
|
||||||
|
return hexlify(get_dummy_pisa_pk_der())
|
||||||
|
|
||||||
|
|
||||||
|
def get_dummy_signature(*args):
|
||||||
|
sk = Cryptographer.load_private_key_der(pisa_sk_der)
|
||||||
|
return Cryptographer.sign(dummy_appointment.serialize(), sk)
|
||||||
|
|
||||||
|
|
||||||
|
def get_bad_signature(*args):
|
||||||
|
sk = Cryptographer.load_private_key_der(other_sk_der)
|
||||||
|
return Cryptographer.sign(dummy_appointment.serialize(), sk)
|
||||||
|
|
||||||
|
|
||||||
|
def valid_sig(*args):
|
||||||
|
return True
|
||||||
|
|
||||||
|
|
||||||
|
def invalid_sig(*args):
|
||||||
|
return False
|
||||||
|
|
||||||
|
|
||||||
@responses.activate
|
@responses.activate
|
||||||
@@ -51,10 +98,12 @@ def test_add_appointment(monkeypatch):
|
|||||||
# Simulate a request to add_appointment for dummy_appointment, make sure that the right endpoint is requested
|
# Simulate a request to add_appointment for dummy_appointment, make sure that the right endpoint is requested
|
||||||
# and the return value is True
|
# and the return value is True
|
||||||
|
|
||||||
# make sure the test uses the right dummy key instead of loading it from disk
|
# Make sure the test uses the dummy signature
|
||||||
monkeypatch.setattr(pisa_cli, "load_public_key", get_dummy_pisa_pk)
|
monkeypatch.setattr(pisa_cli, "get_appointment_signature", get_dummy_signature)
|
||||||
|
monkeypatch.setattr(pisa_cli, "get_pk", get_dummy_hex_pk_der)
|
||||||
|
monkeypatch.setattr(pisa_cli, "check_signature", valid_sig)
|
||||||
|
|
||||||
response = {"locator": dummy_appointment["locator"], "signature": sign_appointment(pisa_sk, dummy_appointment)}
|
response = {"locator": dummy_appointment.to_dict()["locator"], "signature": get_dummy_signature()}
|
||||||
|
|
||||||
request_url = "http://{}/".format(pisa_endpoint)
|
request_url = "http://{}/".format(pisa_endpoint)
|
||||||
responses.add(responses.POST, request_url, json=response, status=200)
|
responses.add(responses.POST, request_url, json=response, status=200)
|
||||||
@@ -72,12 +121,14 @@ def test_add_appointment_with_invalid_signature(monkeypatch):
|
|||||||
# Simulate a request to add_appointment for dummy_appointment, but sign with a different key,
|
# Simulate a request to add_appointment for dummy_appointment, but sign with a different key,
|
||||||
# make sure that the right endpoint is requested, but the return value is False
|
# make sure that the right endpoint is requested, but the return value is False
|
||||||
|
|
||||||
# make sure the test uses the right dummy key instead of loading it from disk
|
# Make sure the test uses the bad dummy signature
|
||||||
monkeypatch.setattr(pisa_cli, "load_public_key", get_dummy_pisa_pk)
|
monkeypatch.setattr(pisa_cli, "get_appointment_signature", get_bad_signature)
|
||||||
|
monkeypatch.setattr(pisa_cli, "get_pk", get_dummy_hex_pk_der)
|
||||||
|
monkeypatch.setattr(pisa_cli, "check_signature", invalid_sig)
|
||||||
|
|
||||||
response = {
|
response = {
|
||||||
"locator": dummy_appointment["locator"],
|
"locator": dummy_appointment.to_dict()["locator"],
|
||||||
"signature": sign_appointment(other_sk, dummy_appointment), # signing with a different key
|
"signature": get_bad_signature(), # Sign with a bad key
|
||||||
}
|
}
|
||||||
|
|
||||||
request_url = "http://{}/".format(pisa_endpoint)
|
request_url = "http://{}/".format(pisa_endpoint)
|
||||||
@@ -85,4 +136,141 @@ def test_add_appointment_with_invalid_signature(monkeypatch):
|
|||||||
|
|
||||||
result = pisa_cli.add_appointment([json.dumps(dummy_appointment_request)])
|
result = pisa_cli.add_appointment([json.dumps(dummy_appointment_request)])
|
||||||
|
|
||||||
assert not result
|
assert result is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_key_file_data():
|
||||||
|
# If file exists and has data in it, function should work.
|
||||||
|
with open("key_test_file", "w+b") as f:
|
||||||
|
f.write(pisa_sk_der)
|
||||||
|
|
||||||
|
appt_data = pisa_cli.load_key_file_data("key_test_file")
|
||||||
|
assert appt_data
|
||||||
|
|
||||||
|
os.remove("key_test_file")
|
||||||
|
|
||||||
|
# If file doesn't exist, function should fail.
|
||||||
|
appt_data = pisa_cli.load_key_file_data("nonexistent_file")
|
||||||
|
assert not appt_data
|
||||||
|
|
||||||
|
|
||||||
|
def test_save_signed_appointment(monkeypatch):
|
||||||
|
monkeypatch.setattr(pisa_cli, "APPOINTMENTS_FOLDER_NAME", "test_appointments")
|
||||||
|
|
||||||
|
pisa_cli.save_signed_appointment(dummy_appointment.to_dict(), get_dummy_signature())
|
||||||
|
|
||||||
|
# In folder "Appointments," grab all files and print them.
|
||||||
|
files = os.listdir("test_appointments")
|
||||||
|
|
||||||
|
found = False
|
||||||
|
for f in files:
|
||||||
|
if dummy_appointment.to_dict().get("locator") in f:
|
||||||
|
found = True
|
||||||
|
|
||||||
|
assert found
|
||||||
|
|
||||||
|
# If "appointments" directory doesn't exist, function should create it.
|
||||||
|
assert os.path.exists("test_appointments")
|
||||||
|
|
||||||
|
# Delete test directory once we're done.
|
||||||
|
shutil.rmtree("test_appointments")
|
||||||
|
|
||||||
|
|
||||||
|
def test_parse_add_appointment_args():
|
||||||
|
# If no args are passed, function should fail.
|
||||||
|
appt_data = pisa_cli.parse_add_appointment_args(None)
|
||||||
|
assert not appt_data
|
||||||
|
|
||||||
|
# If file doesn't exist, function should fail.
|
||||||
|
appt_data = pisa_cli.parse_add_appointment_args(["-f", "nonexistent_file"])
|
||||||
|
assert not appt_data
|
||||||
|
|
||||||
|
# If file exists and has data in it, function should work.
|
||||||
|
with open("appt_test_file", "w") as f:
|
||||||
|
json.dump(dummy_appointment_request, f)
|
||||||
|
|
||||||
|
appt_data = pisa_cli.parse_add_appointment_args(["-f", "appt_test_file"])
|
||||||
|
assert appt_data
|
||||||
|
|
||||||
|
os.remove("appt_test_file")
|
||||||
|
|
||||||
|
# If appointment json is passed in, function should work.
|
||||||
|
appt_data = pisa_cli.parse_add_appointment_args([json.dumps(dummy_appointment_request)])
|
||||||
|
assert appt_data
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_post_data_to_add_appointment_endpoint():
|
||||||
|
response = {
|
||||||
|
"locator": dummy_appointment.to_dict()["locator"],
|
||||||
|
"signature": Cryptographer.sign(dummy_appointment.serialize(), pisa_sk),
|
||||||
|
}
|
||||||
|
|
||||||
|
request_url = "http://{}/".format(pisa_endpoint)
|
||||||
|
responses.add(responses.POST, request_url, json=response, status=200)
|
||||||
|
|
||||||
|
response = pisa_cli.post_data_to_add_appointment_endpoint(request_url, json.dumps(dummy_appointment_request))
|
||||||
|
|
||||||
|
assert len(responses.calls) == 1
|
||||||
|
assert responses.calls[0].request.url == request_url
|
||||||
|
|
||||||
|
assert response
|
||||||
|
|
||||||
|
|
||||||
|
def test_check_signature(monkeypatch):
|
||||||
|
# Make sure the test uses the right dummy key instead of loading it from disk
|
||||||
|
monkeypatch.setattr(pisa_cli, "load_key_file_data", get_dummy_pisa_pk_der)
|
||||||
|
|
||||||
|
valid = pisa_cli.check_signature(get_dummy_signature(), dummy_appointment)
|
||||||
|
|
||||||
|
assert valid
|
||||||
|
|
||||||
|
valid = pisa_cli.check_signature(get_bad_signature(), dummy_appointment)
|
||||||
|
|
||||||
|
assert not valid
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_get_appointment():
|
||||||
|
# Response of get_appointment endpoint is an appointment with status added to it.
|
||||||
|
dummy_appointment_full["status"] = "being_watched"
|
||||||
|
response = dummy_appointment_full
|
||||||
|
|
||||||
|
request_url = "http://{}/".format(pisa_endpoint) + "get_appointment?locator={}".format(response.get("locator"))
|
||||||
|
responses.add(responses.GET, request_url, json=response, status=200)
|
||||||
|
|
||||||
|
result = pisa_cli.get_appointment([response.get("locator")])
|
||||||
|
|
||||||
|
assert len(responses.calls) == 1
|
||||||
|
assert responses.calls[0].request.url == request_url
|
||||||
|
|
||||||
|
assert result
|
||||||
|
|
||||||
|
|
||||||
|
@responses.activate
|
||||||
|
def test_get_appointment_err():
|
||||||
|
locator = get_random_value_hex(32)
|
||||||
|
|
||||||
|
# Test that get_appointment handles a connection error appropriately.
|
||||||
|
request_url = "http://{}/".format(pisa_endpoint) + "get_appointment?locator=".format(locator)
|
||||||
|
responses.add(responses.GET, request_url, body=ConnectionError())
|
||||||
|
|
||||||
|
assert not pisa_cli.get_appointment([locator])
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_appointment_signature(monkeypatch):
|
||||||
|
# Make sure the test uses the right dummy key instead of loading it from disk
|
||||||
|
monkeypatch.setattr(pisa_cli, "load_key_file_data", get_dummy_pisa_sk_der)
|
||||||
|
|
||||||
|
signature = pisa_cli.get_appointment_signature(dummy_appointment)
|
||||||
|
|
||||||
|
assert isinstance(signature, str)
|
||||||
|
|
||||||
|
|
||||||
|
def test_get_pk(monkeypatch):
|
||||||
|
# Make sure the test uses the right dummy key instead of loading it from disk
|
||||||
|
monkeypatch.setattr(pisa_cli, "load_key_file_data", get_dummy_pisa_pk_der)
|
||||||
|
|
||||||
|
pk = pisa_cli.get_pk()
|
||||||
|
|
||||||
|
assert isinstance(pk, bytes)
|
||||||
|
|||||||
@@ -12,11 +12,11 @@ from cryptography.hazmat.primitives import serialization
|
|||||||
|
|
||||||
from apps.cli.blob import Blob
|
from apps.cli.blob import Blob
|
||||||
from pisa.responder import TransactionTracker
|
from pisa.responder import TransactionTracker
|
||||||
from pisa.watcher import Watcher
|
|
||||||
from pisa.tools import bitcoin_cli
|
from pisa.tools import bitcoin_cli
|
||||||
from pisa.db_manager import DBManager
|
from pisa.db_manager import DBManager
|
||||||
from pisa.chain_monitor import ChainMonitor
|
from pisa.chain_monitor import ChainMonitor
|
||||||
from common.appointment import Appointment
|
from common.appointment import Appointment
|
||||||
|
from common.tools import compute_locator
|
||||||
|
|
||||||
from bitcoind_mock.utils import sha256d
|
from bitcoind_mock.utils import sha256d
|
||||||
from bitcoind_mock.transaction import TX
|
from bitcoind_mock.transaction import TX
|
||||||
@@ -115,7 +115,7 @@ def generate_dummy_appointment_data(real_height=True, start_time_offset=5, end_t
|
|||||||
encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
encoding=serialization.Encoding.DER, format=serialization.PublicFormat.SubjectPublicKeyInfo
|
||||||
)
|
)
|
||||||
|
|
||||||
locator = Watcher.compute_locator(dispute_txid)
|
locator = compute_locator(dispute_txid)
|
||||||
blob = Blob(dummy_appointment_data.get("tx"))
|
blob = Blob(dummy_appointment_data.get("tx"))
|
||||||
|
|
||||||
encrypted_blob = Cryptographer.encrypt(blob, dummy_appointment_data.get("tx_id"))
|
encrypted_blob = Cryptographer.encrypt(blob, dummy_appointment_data.get("tx_id"))
|
||||||
@@ -159,3 +159,26 @@ def generate_dummy_tracker():
|
|||||||
)
|
)
|
||||||
|
|
||||||
return TransactionTracker.from_dict(tracker_data)
|
return TransactionTracker.from_dict(tracker_data)
|
||||||
|
|
||||||
|
|
||||||
|
def get_config():
|
||||||
|
config = {
|
||||||
|
"BTC_RPC_USER": "username",
|
||||||
|
"BTC_RPC_PASSWD": "password",
|
||||||
|
"BTC_RPC_HOST": "localhost",
|
||||||
|
"BTC_RPC_PORT": 8332,
|
||||||
|
"BTC_NETWORK": "regtest",
|
||||||
|
"FEED_PROTOCOL": "tcp",
|
||||||
|
"FEED_ADDR": "127.0.0.1",
|
||||||
|
"FEED_PORT": 28332,
|
||||||
|
"MAX_APPOINTMENTS": 100,
|
||||||
|
"EXPIRY_DELTA": 6,
|
||||||
|
"MIN_TO_SELF_DELAY": 20,
|
||||||
|
"SERVER_LOG_FILE": "pisa.log",
|
||||||
|
"PISA_SECRET_KEY": "pisa_sk.der",
|
||||||
|
"CLIENT_LOG_FILE": "pisa.log",
|
||||||
|
"TEST_LOG_FILE": "test.log",
|
||||||
|
"DB_PATH": "appointments",
|
||||||
|
}
|
||||||
|
|
||||||
|
return config
|
||||||
|
|||||||
@@ -9,7 +9,6 @@ from pisa.api import API
|
|||||||
from pisa.watcher import Watcher
|
from pisa.watcher import Watcher
|
||||||
from pisa.tools import bitcoin_cli
|
from pisa.tools import bitcoin_cli
|
||||||
from pisa import HOST, PORT
|
from pisa import HOST, PORT
|
||||||
from pisa.conf import MAX_APPOINTMENTS
|
|
||||||
|
|
||||||
from test.pisa.unit.conftest import (
|
from test.pisa.unit.conftest import (
|
||||||
generate_block,
|
generate_block,
|
||||||
@@ -17,6 +16,7 @@ from test.pisa.unit.conftest import (
|
|||||||
get_random_value_hex,
|
get_random_value_hex,
|
||||||
generate_dummy_appointment_data,
|
generate_dummy_appointment_data,
|
||||||
generate_keypair,
|
generate_keypair,
|
||||||
|
get_config,
|
||||||
)
|
)
|
||||||
|
|
||||||
from common.constants import LOCATOR_LEN_BYTES
|
from common.constants import LOCATOR_LEN_BYTES
|
||||||
@@ -28,6 +28,8 @@ MULTIPLE_APPOINTMENTS = 10
|
|||||||
appointments = []
|
appointments = []
|
||||||
locator_dispute_tx_map = {}
|
locator_dispute_tx_map = {}
|
||||||
|
|
||||||
|
config = get_config()
|
||||||
|
|
||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def run_api(db_manager, chain_monitor):
|
def run_api(db_manager, chain_monitor):
|
||||||
@@ -38,11 +40,11 @@ def run_api(db_manager, chain_monitor):
|
|||||||
encryption_algorithm=serialization.NoEncryption(),
|
encryption_algorithm=serialization.NoEncryption(),
|
||||||
)
|
)
|
||||||
|
|
||||||
watcher = Watcher(db_manager, chain_monitor, sk_der)
|
watcher = Watcher(db_manager, chain_monitor, sk_der, get_config())
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
||||||
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
||||||
|
|
||||||
api_thread = Thread(target=API(watcher).start)
|
api_thread = Thread(target=API(watcher, config).start)
|
||||||
api_thread.daemon = True
|
api_thread.daemon = True
|
||||||
api_thread.start()
|
api_thread.start()
|
||||||
|
|
||||||
@@ -105,7 +107,7 @@ def test_request_multiple_appointments_same_locator(new_appt_data, n=MULTIPLE_AP
|
|||||||
|
|
||||||
|
|
||||||
def test_add_too_many_appointment(new_appt_data):
|
def test_add_too_many_appointment(new_appt_data):
|
||||||
for _ in range(MAX_APPOINTMENTS - len(appointments)):
|
for _ in range(config.get("MAX_APPOINTMENTS") - len(appointments)):
|
||||||
r = add_appointment(new_appt_data)
|
r = add_appointment(new_appt_data)
|
||||||
assert r.status_code == 200
|
assert r.status_code == 200
|
||||||
|
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ from pisa.responder import Responder
|
|||||||
from pisa.block_processor import BlockProcessor
|
from pisa.block_processor import BlockProcessor
|
||||||
from pisa.chain_monitor import ChainMonitor
|
from pisa.chain_monitor import ChainMonitor
|
||||||
|
|
||||||
from test.pisa.unit.conftest import get_random_value_hex, generate_block
|
from test.pisa.unit.conftest import get_random_value_hex, generate_block, get_config
|
||||||
|
|
||||||
|
|
||||||
def test_init(run_bitcoind):
|
def test_init(run_bitcoind):
|
||||||
@@ -30,7 +30,7 @@ def test_init(run_bitcoind):
|
|||||||
|
|
||||||
|
|
||||||
def test_attach_watcher(chain_monitor):
|
def test_attach_watcher(chain_monitor):
|
||||||
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None)
|
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None, config=get_config())
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
||||||
|
|
||||||
# booleans are not passed as reference in Python, so the flags need to be set separately
|
# booleans are not passed as reference in Python, so the flags need to be set separately
|
||||||
@@ -108,7 +108,7 @@ def test_monitor_chain_polling():
|
|||||||
chain_monitor = ChainMonitor()
|
chain_monitor = ChainMonitor()
|
||||||
chain_monitor.best_tip = BlockProcessor.get_best_block_hash()
|
chain_monitor.best_tip = BlockProcessor.get_best_block_hash()
|
||||||
|
|
||||||
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None)
|
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None, config=get_config())
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
||||||
|
|
||||||
# monitor_chain_polling runs until terminate if set
|
# monitor_chain_polling runs until terminate if set
|
||||||
@@ -168,7 +168,7 @@ def test_monitor_chain():
|
|||||||
# Not much to test here, this should launch two threads (one per monitor approach) and finish on terminate
|
# Not much to test here, this should launch two threads (one per monitor approach) and finish on terminate
|
||||||
chain_monitor = ChainMonitor()
|
chain_monitor = ChainMonitor()
|
||||||
|
|
||||||
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None)
|
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None, config=get_config())
|
||||||
responder = Responder(db_manager=None, chain_monitor=chain_monitor)
|
responder = Responder(db_manager=None, chain_monitor=chain_monitor)
|
||||||
chain_monitor.attach_responder(responder.block_queue, asleep=False)
|
chain_monitor.attach_responder(responder.block_queue, asleep=False)
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
||||||
@@ -198,7 +198,7 @@ def test_monitor_chain_single_update():
|
|||||||
# This test tests that if both threads try to add the same block to the queue, only the first one will make it
|
# This test tests that if both threads try to add the same block to the queue, only the first one will make it
|
||||||
chain_monitor = ChainMonitor()
|
chain_monitor = ChainMonitor()
|
||||||
|
|
||||||
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None)
|
watcher = Watcher(db_manager=None, chain_monitor=chain_monitor, sk_der=None, config=get_config())
|
||||||
responder = Responder(db_manager=None, chain_monitor=chain_monitor)
|
responder = Responder(db_manager=None, chain_monitor=chain_monitor)
|
||||||
chain_monitor.attach_responder(responder.block_queue, asleep=False)
|
chain_monitor.attach_responder(responder.block_queue, asleep=False)
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
chain_monitor.attach_watcher(watcher.block_queue, asleep=False)
|
||||||
|
|||||||
@@ -10,13 +10,13 @@ from common.appointment import Appointment
|
|||||||
from pisa.block_processor import BlockProcessor
|
from pisa.block_processor import BlockProcessor
|
||||||
from pisa.conf import MIN_TO_SELF_DELAY
|
from pisa.conf import MIN_TO_SELF_DELAY
|
||||||
|
|
||||||
from test.pisa.unit.conftest import get_random_value_hex, generate_dummy_appointment_data, generate_keypair
|
from test.pisa.unit.conftest import get_random_value_hex, generate_dummy_appointment_data, generate_keypair, get_config
|
||||||
|
|
||||||
from common.constants import LOCATOR_LEN_BYTES, LOCATOR_LEN_HEX
|
from common.constants import LOCATOR_LEN_BYTES, LOCATOR_LEN_HEX
|
||||||
from common.cryptographer import Cryptographer
|
from common.cryptographer import Cryptographer
|
||||||
|
|
||||||
|
|
||||||
inspector = Inspector()
|
inspector = Inspector(get_config())
|
||||||
APPOINTMENT_OK = (0, None)
|
APPOINTMENT_OK = (0, None)
|
||||||
|
|
||||||
NO_HEX_STRINGS = [
|
NO_HEX_STRINGS = [
|
||||||
@@ -126,21 +126,21 @@ def test_check_to_self_delay():
|
|||||||
# Right value, right format
|
# Right value, right format
|
||||||
to_self_delays = [MIN_TO_SELF_DELAY, MIN_TO_SELF_DELAY + 1, MIN_TO_SELF_DELAY + 1000]
|
to_self_delays = [MIN_TO_SELF_DELAY, MIN_TO_SELF_DELAY + 1, MIN_TO_SELF_DELAY + 1000]
|
||||||
for to_self_delay in to_self_delays:
|
for to_self_delay in to_self_delays:
|
||||||
assert Inspector.check_to_self_delay(to_self_delay) == APPOINTMENT_OK
|
assert inspector.check_to_self_delay(to_self_delay) == APPOINTMENT_OK
|
||||||
|
|
||||||
# to_self_delay too small
|
# to_self_delay too small
|
||||||
to_self_delays = [MIN_TO_SELF_DELAY - 1, MIN_TO_SELF_DELAY - 2, 0, -1, -1000]
|
to_self_delays = [MIN_TO_SELF_DELAY - 1, MIN_TO_SELF_DELAY - 2, 0, -1, -1000]
|
||||||
for to_self_delay in to_self_delays:
|
for to_self_delay in to_self_delays:
|
||||||
assert Inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_FIELD_TOO_SMALL
|
assert inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_FIELD_TOO_SMALL
|
||||||
|
|
||||||
# Empty field
|
# Empty field
|
||||||
to_self_delay = None
|
to_self_delay = None
|
||||||
assert Inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_EMPTY_FIELD
|
assert inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_EMPTY_FIELD
|
||||||
|
|
||||||
# Wrong data type
|
# Wrong data type
|
||||||
to_self_delays = WRONG_TYPES
|
to_self_delays = WRONG_TYPES
|
||||||
for to_self_delay in to_self_delays:
|
for to_self_delay in to_self_delays:
|
||||||
assert Inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_WRONG_FIELD_TYPE
|
assert inspector.check_to_self_delay(to_self_delay)[0] == APPOINTMENT_WRONG_FIELD_TYPE
|
||||||
|
|
||||||
|
|
||||||
def test_check_blob():
|
def test_check_blob():
|
||||||
|
|||||||
52
test/pisa/unit/test_pisad.py
Normal file
52
test/pisa/unit/test_pisad.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import pytest
|
||||||
|
from pathlib import Path
|
||||||
|
from shutil import copyfile
|
||||||
|
|
||||||
|
from pisa.pisad import load_config
|
||||||
|
|
||||||
|
test_conf_file_path = os.getcwd() + "/test/pisa/unit/test_conf.py"
|
||||||
|
|
||||||
|
|
||||||
|
def test_load_config():
|
||||||
|
# Copy the sample-conf.py file to use as a test config file.
|
||||||
|
copyfile(os.getcwd() + "/pisa/sample_conf.py", test_conf_file_path)
|
||||||
|
|
||||||
|
import test.pisa.unit.test_conf as conf
|
||||||
|
|
||||||
|
# If the file has all the correct fields and data, it should return a dict.
|
||||||
|
conf_dict = load_config(conf)
|
||||||
|
assert type(conf_dict) == dict
|
||||||
|
|
||||||
|
# Delete the file.
|
||||||
|
os.remove(test_conf_file_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_bad_load_config():
|
||||||
|
# Create a messed up version of the file that should throw an error.
|
||||||
|
with open(test_conf_file_path, "w") as f:
|
||||||
|
f.write('# bitcoind\nBTC_RPC_USER = 0000\nBTC_RPC_PASSWD = "password"\nBTC_RPC_HOST = 000')
|
||||||
|
|
||||||
|
import test.pisa.unit.test_conf as conf
|
||||||
|
|
||||||
|
importlib.reload(conf)
|
||||||
|
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
conf_dict = load_config(conf)
|
||||||
|
|
||||||
|
os.remove(test_conf_file_path)
|
||||||
|
|
||||||
|
|
||||||
|
def test_empty_load_config():
|
||||||
|
# Create an empty version of the file that should throw an error.
|
||||||
|
open(test_conf_file_path, "a")
|
||||||
|
|
||||||
|
import test.pisa.unit.test_conf as conf
|
||||||
|
|
||||||
|
importlib.reload(conf)
|
||||||
|
|
||||||
|
with pytest.raises(Exception):
|
||||||
|
conf_dict = load_config(conf)
|
||||||
|
|
||||||
|
os.remove(test_conf_file_path)
|
||||||
@@ -307,10 +307,8 @@ def test_do_watch(temp_db_manager, chain_monitor):
|
|||||||
bitcoin_cli().sendrawtransaction(tracker.penalty_rawtx)
|
bitcoin_cli().sendrawtransaction(tracker.penalty_rawtx)
|
||||||
broadcast_txs.append(tracker.penalty_txid)
|
broadcast_txs.append(tracker.penalty_txid)
|
||||||
|
|
||||||
print(responder.unconfirmed_txs)
|
|
||||||
# Mine a block
|
# Mine a block
|
||||||
generate_block()
|
generate_block()
|
||||||
print(responder.unconfirmed_txs)
|
|
||||||
|
|
||||||
# The transactions we sent shouldn't be in the unconfirmed transaction list anymore
|
# The transactions we sent shouldn't be in the unconfirmed transaction list anymore
|
||||||
assert not set(broadcast_txs).issubset(responder.unconfirmed_txs)
|
assert not set(broadcast_txs).issubset(responder.unconfirmed_txs)
|
||||||
|
|||||||
@@ -1,15 +1,24 @@
|
|||||||
import pytest
|
import pytest
|
||||||
from uuid import uuid4
|
from uuid import uuid4
|
||||||
from threading import Thread
|
from threading import Thread
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
from cryptography.hazmat.primitives import serialization
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
|
||||||
from pisa.watcher import Watcher
|
from pisa.watcher import Watcher
|
||||||
from pisa.responder import Responder
|
from pisa.responder import Responder
|
||||||
from pisa.tools import bitcoin_cli
|
from pisa.tools import bitcoin_cli
|
||||||
from test.pisa.unit.conftest import generate_blocks, generate_dummy_appointment, get_random_value_hex, generate_keypair
|
|
||||||
from pisa.chain_monitor import ChainMonitor
|
from pisa.chain_monitor import ChainMonitor
|
||||||
|
|
||||||
|
from test.pisa.unit.conftest import (
|
||||||
|
generate_blocks,
|
||||||
|
generate_dummy_appointment,
|
||||||
|
get_random_value_hex,
|
||||||
|
generate_keypair,
|
||||||
|
get_config,
|
||||||
|
)
|
||||||
from pisa.conf import EXPIRY_DELTA, MAX_APPOINTMENTS
|
from pisa.conf import EXPIRY_DELTA, MAX_APPOINTMENTS
|
||||||
|
|
||||||
|
from common.tools import compute_locator
|
||||||
from common.cryptographer import Cryptographer
|
from common.cryptographer import Cryptographer
|
||||||
|
|
||||||
|
|
||||||
@@ -29,7 +38,7 @@ sk_der = signing_key.private_bytes(
|
|||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def watcher(db_manager, chain_monitor):
|
def watcher(db_manager, chain_monitor):
|
||||||
watcher = Watcher(db_manager, chain_monitor, sk_der)
|
watcher = Watcher(db_manager, chain_monitor, sk_der, get_config())
|
||||||
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
chain_monitor.attach_watcher(watcher.block_queue, watcher.asleep)
|
||||||
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
chain_monitor.attach_responder(watcher.responder.block_queue, watcher.responder.asleep)
|
||||||
|
|
||||||
@@ -43,7 +52,7 @@ def txids():
|
|||||||
|
|
||||||
@pytest.fixture(scope="module")
|
@pytest.fixture(scope="module")
|
||||||
def locator_uuid_map(txids):
|
def locator_uuid_map(txids):
|
||||||
return {Watcher.compute_locator(txid): uuid4().hex for txid in txids}
|
return {compute_locator(txid): uuid4().hex for txid in txids}
|
||||||
|
|
||||||
|
|
||||||
def create_appointments(n):
|
def create_appointments(n):
|
||||||
@@ -67,12 +76,12 @@ def create_appointments(n):
|
|||||||
def test_init(run_bitcoind, watcher):
|
def test_init(run_bitcoind, watcher):
|
||||||
assert isinstance(watcher.appointments, dict) and len(watcher.appointments) == 0
|
assert isinstance(watcher.appointments, dict) and len(watcher.appointments) == 0
|
||||||
assert isinstance(watcher.locator_uuid_map, dict) and len(watcher.locator_uuid_map) == 0
|
assert isinstance(watcher.locator_uuid_map, dict) and len(watcher.locator_uuid_map) == 0
|
||||||
assert isinstance(watcher.chain_monitor, ChainMonitor)
|
|
||||||
assert watcher.block_queue.empty()
|
|
||||||
assert watcher.asleep is True
|
assert watcher.asleep is True
|
||||||
|
assert watcher.block_queue.empty()
|
||||||
assert watcher.max_appointments == MAX_APPOINTMENTS
|
assert isinstance(watcher.chain_monitor, ChainMonitor)
|
||||||
assert type(watcher.responder) is Responder
|
assert isinstance(watcher.config, dict)
|
||||||
|
assert isinstance(watcher.signing_key, ec.EllipticCurvePrivateKey)
|
||||||
|
assert isinstance(watcher.responder, Responder)
|
||||||
|
|
||||||
|
|
||||||
def test_add_appointment(watcher):
|
def test_add_appointment(watcher):
|
||||||
@@ -199,7 +208,7 @@ def test_filter_valid_breaches(watcher):
|
|||||||
|
|
||||||
dummy_appointment, _ = generate_dummy_appointment()
|
dummy_appointment, _ = generate_dummy_appointment()
|
||||||
dummy_appointment.encrypted_blob.data = encrypted_blob
|
dummy_appointment.encrypted_blob.data = encrypted_blob
|
||||||
dummy_appointment.locator = Watcher.compute_locator(dispute_txid)
|
dummy_appointment.locator = compute_locator(dispute_txid)
|
||||||
uuid = uuid4().hex
|
uuid = uuid4().hex
|
||||||
|
|
||||||
appointments = {uuid: dummy_appointment}
|
appointments = {uuid: dummy_appointment}
|
||||||
|
|||||||
Reference in New Issue
Block a user