Commit c337a501 authored by Vincent Texier's avatar Vincent Texier

[enh] #94 check-format and format tests and examples folders

parent e2bb658c
Pipeline #5850 passed with stages
in 4 minutes and 17 seconds
......@@ -26,7 +26,11 @@ pylint:
# check format
check-format:
black --check duniterpy
black --check tests
black --check examples
# format code
format:
black duniterpy
black tests
black examples
\ No newline at end of file
......@@ -17,7 +17,9 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
def get_identity_document(
current_block: dict, uid: str, salt: str, password: str
) -> Identity:
"""
Get an Identity document
......@@ -30,7 +32,7 @@ def get_identity_document(current_block: dict, uid: str, salt: str, password: st
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
timestamp = BlockUID(current_block["number"], current_block["hash"])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
......@@ -38,11 +40,11 @@ def get_identity_document(current_block: dict, uid: str, salt: str, password: st
# create identity document
identity = Identity(
version=10,
currency=current_block['currency'],
currency=current_block["currency"],
pubkey=key.pubkey,
uid=uid,
ts=timestamp,
signature=None
signature=None,
)
# sign document
......
......@@ -3,7 +3,7 @@ from duniterpy.key import SigningKey
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
......
......@@ -3,13 +3,15 @@ import sys
from duniterpy.key import SigningKey
if __name__ == '__main__':
if __name__ == "__main__":
if len(sys.argv) < 2:
print("""
print(
"""
Usage:
python decrypt_message.py ENCRYPTED_MESSAGE_FILEPATH
""")
"""
)
# capture encrypted message filepath argument
signed_message_path = sys.argv[1]
......@@ -24,12 +26,12 @@ if __name__ == '__main__':
signing_key_instance = SigningKey.from_credentials(salt, password)
# open encrypted message file
with open(signed_message_path, 'rb') as file_handler:
with open(signed_message_path, "rb") as file_handler:
encrypted_message = file_handler.read()
# Decrypt the message!
try:
message = signing_key_instance.decrypt_seal(encrypted_message).decode('utf-8')
message = signing_key_instance.decrypt_seal(encrypted_message).decode("utf-8")
print("Decrypted message:")
except ValueError as error:
message = str(error)
......
......@@ -2,13 +2,15 @@ import sys
from duniterpy.key import VerifyingKey
if __name__ == '__main__':
if __name__ == "__main__":
if len(sys.argv) < 2:
print("""
print(
"""
Usage:
python verify_signed_message.py SIGNED_MESSAGE_FILEPATH
""")
"""
)
# capture signed message filepath argument
signed_message_path = sys.argv[1]
......@@ -17,13 +19,13 @@ if __name__ == '__main__':
pubkeyBase58 = input("Enter public key of the message issuer: ")
# open signed message file
with open(signed_message_path, 'rb') as file_handler:
with open(signed_message_path, "rb") as file_handler:
signed_message = file_handler.read()
# Verify the message!
verifier = VerifyingKey(pubkeyBase58)
try:
message = verifier.get_verified_data(signed_message).decode('utf-8')
message = verifier.get_verified_data(signed_message).decode("utf-8")
print("Signature valid for this message:")
except ValueError as error:
message = str(error)
......
......@@ -2,20 +2,28 @@ from duniterpy.key import AsciiArmor
# CONFIG #######################################
CLEARTEXT_AA_MESSAGE_PATH = '/tmp/duniter_cleartext_aa_message.txt'
CLEARTEXT_AA_MESSAGE_PATH = "/tmp/duniter_cleartext_aa_message.txt"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# Ask public key of the issuer
pubkeyBase58 = input("Enter public key of the message issuer: ")
# Load cleartext ascii armor message from a file
with open(CLEARTEXT_AA_MESSAGE_PATH, 'r') as file_handler:
with open(CLEARTEXT_AA_MESSAGE_PATH, "r") as file_handler:
ascii_armor_block = file_handler.read()
print("Cleartext Ascii Armor Message loaded from file ./{0}".format(CLEARTEXT_AA_MESSAGE_PATH))
print(
"Cleartext Ascii Armor Message loaded from file ./{0}".format(
CLEARTEXT_AA_MESSAGE_PATH
)
)
result = AsciiArmor.parse(ascii_armor_block, None, [pubkeyBase58])
print('------------- MESSAGE ------------\n' + result['message']['content'] + '----------------------------------')
print(
"------------- MESSAGE ------------\n"
+ result["message"]["content"]
+ "----------------------------------"
)
print(result)
......@@ -4,11 +4,11 @@ from duniterpy.key import AsciiArmor, SigningKey
# CONFIG #######################################
ENCRYPTED_AA_MESSAGE_PATH = '/tmp/duniter_aa_encrypted_message.txt'
ENCRYPTED_AA_MESSAGE_PATH = "/tmp/duniter_aa_encrypted_message.txt"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# Ask public key of the recipient
pubkeyBase58 = input("Enter public key of the message issuer: ")
......@@ -22,9 +22,13 @@ if __name__ == '__main__':
signing_key = SigningKey.from_credentials(salt, password)
# Load ascii armor encrypted message from a file
with open(ENCRYPTED_AA_MESSAGE_PATH, 'r') as file_handler:
with open(ENCRYPTED_AA_MESSAGE_PATH, "r") as file_handler:
ascii_armor_block = file_handler.read()
print("Encrypted Ascii Armor Message loaded from file {0}".format(ENCRYPTED_AA_MESSAGE_PATH))
print(
"Encrypted Ascii Armor Message loaded from file {0}".format(
ENCRYPTED_AA_MESSAGE_PATH
)
)
print(AsciiArmor.parse(ascii_armor_block, signing_key, [pubkeyBase58]))
......@@ -47,25 +47,21 @@ async def main():
"duniter": {
"type": "object",
"properties": {
"software": {
"type": "string"
},
"version": {
"type": "string",
},
"forkWindowSize": {
"type": "number"
}
"software": {"type": "string"},
"version": {"type": "string"},
"forkWindowSize": {"type": "number"},
},
"required": ["software", "version"]
},
"required": ["software", "version"],
}
},
"required": ["duniter"]
"required": ["duniter"],
}
# Get the node summary infos (direct REST GET request)
print("\nCall direct get on node/summary")
response = await client.get('node/summary', rtype=RESPONSE_AIOHTTP, schema=summary_schema)
response = await client.get(
"node/summary", rtype=RESPONSE_AIOHTTP, schema=summary_schema
)
print(response)
# Close client aiohttp session
......
......@@ -26,12 +26,14 @@ async def main():
# Get the current node (direct REST GET request)
print("\nGET g1-test/block/current/_source:")
response = await client.get('g1-test/block/current/_source')
response = await client.get("g1-test/block/current/_source")
print(response)
# Get the node number 2 with only selected fields (direct REST GET request)
print("\nGET g1-test/block/2/_source:")
response = await client.get('g1-test/block/2/_source', {'_source': 'number,hash,dividend,membersCount'})
response = await client.get(
"g1-test/block/2/_source", {"_source": "number,hash,dividend,membersCount"}
)
print(response)
# Close client aiohttp session
......@@ -45,7 +47,7 @@ async def main():
# Get the profil of a public key (direct REST GET request)
print("\nGET user/profile/{0}/_source:".format(pubkey))
response = await client.get('user/profile/{0}/_source'.format(pubkey.strip(' \n')))
response = await client.get("user/profile/{0}/_source".format(pubkey.strip(" \n")))
print(response)
# Close client aiohttp session
......
......@@ -44,14 +44,21 @@ ewif_password = getpass.getpass("Enter an encryption password: ")
signer.save_ewif_file(PRIVATE_KEY_FILE_PATH, ewif_password)
# document saved
print("Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
try:
# load private keys from file
loaded_signer = SigningKey.from_ewif_file(PRIVATE_KEY_FILE_PATH, ewif_password) # type: SigningKey
loaded_signer = SigningKey.from_ewif_file(
PRIVATE_KEY_FILE_PATH, ewif_password
) # type: SigningKey
# check public key from file
print("Public key %s loaded from file %s" % (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Public key %s loaded from file %s"
% (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
except IOError as error:
print(error)
......
......@@ -41,14 +41,19 @@ if signer.pubkey != pubkey:
signer.save_pubsec_file(PRIVATE_KEY_FILE_PATH)
# document saved
print("Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
try:
# load private keys from file
loaded_signer = SigningKey.from_pubsec_file(PRIVATE_KEY_FILE_PATH)
# check public key from file
print("Public key %s loaded from file %s" % (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Public key %s loaded from file %s"
% (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
except IOError as error:
print(error)
......
......@@ -41,14 +41,19 @@ if signer.pubkey != pubkey:
signer.save_wif_file(PRIVATE_KEY_FILE_PATH)
# document saved
print("Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Private key for public key %s saved in %s" % (signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
try:
# load private keys from file
loaded_signer = SigningKey.from_wif_file(PRIVATE_KEY_FILE_PATH) # type: SigningKey
# check public key from file
print("Public key %s loaded from file %s" % (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH))
print(
"Public key %s loaded from file %s"
% (loaded_signer.pubkey, PRIVATE_KEY_FILE_PATH)
)
except IOError as error:
print(error)
......
......@@ -2,11 +2,11 @@ from duniterpy.key import PublicKey
# CONFIG #######################################
ENCRYPTED_MESSAGE_FILENAME = '/tmp/duniter_encrypted_message.bin'
ENCRYPTED_MESSAGE_FILENAME = "/tmp/duniter_encrypted_message.bin"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# Ask public key of the recipient
pubkeyBase58 = input("Enter public key of the message recipient: ")
......@@ -18,7 +18,7 @@ if __name__ == '__main__':
encrypted_message = pubkey_instance.encrypt_seal(message)
# Save encrypted message in a file
with open(ENCRYPTED_MESSAGE_FILENAME, 'wb') as file_handler:
with open(ENCRYPTED_MESSAGE_FILENAME, "wb") as file_handler:
file_handler.write(encrypted_message)
print("Encrypted message saved in file ./{0}".format(ENCRYPTED_MESSAGE_FILENAME))
......@@ -6,11 +6,11 @@ from duniterpy.key import SigningKey
# CONFIG #######################################
SIGNED_MESSAGE_FILENAME = '/tmp/duniter_signed_message.bin'
SIGNED_MESSAGE_FILENAME = "/tmp/duniter_signed_message.bin"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
......@@ -27,7 +27,7 @@ if __name__ == '__main__':
# Sign the message, the signed string is the message itself plus the
# signature
signed_message = key.sign(bytes(message, 'utf-8')) # type: bytes
signed_message = key.sign(bytes(message, "utf-8")) # type: bytes
# To create a verifier pass in the verify key:
veri = libnacl.sign.Verifier(key.hex_vk())
......@@ -35,7 +35,7 @@ if __name__ == '__main__':
verified = veri.verify(signed_message)
# save signed message in a file
with open(SIGNED_MESSAGE_FILENAME, 'wb') as file_handler:
with open(SIGNED_MESSAGE_FILENAME, "wb") as file_handler:
file_handler.write(signed_message)
print("Signed message saved in file ./{0}".format(SIGNED_MESSAGE_FILENAME))
......@@ -7,11 +7,11 @@ from duniterpy.key import AsciiArmor, SigningKey
# CONFIG #######################################
CLEARTEXT_AA_MESSAGE_PATH = '/tmp/duniter_cleartext_aa_message.txt'
CLEARTEXT_AA_MESSAGE_PATH = "/tmp/duniter_cleartext_aa_message.txt"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# prompt hidden user entry
salt = getpass.getpass("Enter your passphrase (salt): ")
......@@ -29,10 +29,16 @@ if __name__ == '__main__':
comment = "generated by Duniterpy {0}".format(__version__)
# Dash escape the message and sign it
aa_cleartext_message = AsciiArmor.create(message, None, [signing_key], None, signatures_comment=comment)
aa_cleartext_message = AsciiArmor.create(
message, None, [signing_key], None, signatures_comment=comment
)
# Save cleartext ascii armor message in a file
with open(CLEARTEXT_AA_MESSAGE_PATH, 'w') as file_handler:
with open(CLEARTEXT_AA_MESSAGE_PATH, "w") as file_handler:
file_handler.write(aa_cleartext_message)
print("Cleartext Ascii Armor Message saved in file ./{0}".format(CLEARTEXT_AA_MESSAGE_PATH))
print(
"Cleartext Ascii Armor Message saved in file ./{0}".format(
CLEARTEXT_AA_MESSAGE_PATH
)
)
......@@ -5,11 +5,11 @@ from duniterpy.key import AsciiArmor, SigningKey
# CONFIG #######################################
ENCRYPTED_AA_MESSAGE_PATH = '/tmp/duniter_aa_encrypted_message.txt'
ENCRYPTED_AA_MESSAGE_PATH = "/tmp/duniter_aa_encrypted_message.txt"
################################################
if __name__ == '__main__':
if __name__ == "__main__":
# Ask public key of the recipient
pubkeyBase58 = input("Enter public key of the message recipient: ")
......@@ -29,11 +29,20 @@ if __name__ == '__main__':
comment = "generated by Duniterpy {0}".format(__version__)
# Encrypt the message, only the recipient secret key will be able to decrypt the message
encrypted_message = AsciiArmor.create(message, pubkeyBase58, [signing_key], message_comment=comment,
signatures_comment=comment)
encrypted_message = AsciiArmor.create(
message,
pubkeyBase58,
[signing_key],
message_comment=comment,
signatures_comment=comment,
)
# Save encrypted message in a file
with open(ENCRYPTED_AA_MESSAGE_PATH, 'w') as file_handler:
with open(ENCRYPTED_AA_MESSAGE_PATH, "w") as file_handler:
file_handler.write(encrypted_message)
print("Encrypted Ascii Armor Message saved in file {0}".format(ENCRYPTED_AA_MESSAGE_PATH))
print(
"Encrypted Ascii Armor Message saved in file {0}".format(
ENCRYPTED_AA_MESSAGE_PATH
)
)
......@@ -27,7 +27,9 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
# WARNING : Hide this file in a safe and secure place
# If one day you forget your credentials,
# you'll have to use your private key instead
REVOCATION_DOCUMENT_FILE_PATH = os.path.join(home_path, "duniter_account_revocation_document.txt")
REVOCATION_DOCUMENT_FILE_PATH = os.path.join(
home_path, "duniter_account_revocation_document.txt"
)
# Current protocol version
PROTOCOL_VERSION = 10
......@@ -36,7 +38,9 @@ PROTOCOL_VERSION = 10
################################################
async def get_identity_document(client: Client, current_block: dict, pubkey: str) -> Optional[Identity]:
async def get_identity_document(
client: Client, current_block: dict, pubkey: str
) -> Optional[Identity]:
"""
Get the identity document of the pubkey
......@@ -51,9 +55,9 @@ async def get_identity_document(client: Client, current_block: dict, pubkey: str
identity = None
# parse results
for result in lookup_data['results']:
for result in lookup_data["results"]:
if result["pubkey"] == pubkey:
uids = result['uids']
uids = result["uids"]
uid_data = uids[0]
# capture data
timestamp = BlockUID.from_str(uid_data["meta"]["timestamp"])
......@@ -63,18 +67,20 @@ async def get_identity_document(client: Client, current_block: dict, pubkey: str
# return self-certification document
identity = Identity(
version=10,
currency=current_block['currency'],
currency=current_block["currency"],
pubkey=pubkey,
uid=uid,
ts=timestamp,
signature=signature
signature=signature,
)
break
return identity
def get_signed_raw_revocation_document(identity: Identity, salt: str, password: str) -> str:
def get_signed_raw_revocation_document(
identity: Identity, salt: str, password: str
) -> str:
"""
Generate account revocation document for given identity
......@@ -131,10 +137,12 @@ async def main():
exit(1)
# get the revoke document
revocation_signed_raw_document = get_signed_raw_revocation_document(identity, salt, password)
revocation_signed_raw_document = get_signed_raw_revocation_document(
identity, salt, password
)
# save revoke document in a file
fp = open(REVOCATION_DOCUMENT_FILE_PATH, 'w')
fp = open(REVOCATION_DOCUMENT_FILE_PATH, "w")
fp.write(revocation_signed_raw_document)
fp.close()
......
......@@ -18,7 +18,9 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################
async def get_identity_document(client: Client, current_block: dict, pubkey: str) -> Optional[Identity]:
async def get_identity_document(
client: Client, current_block: dict, pubkey: str
) -> Optional[Identity]:
"""
Get the identity document of the pubkey
......@@ -33,9 +35,9 @@ async def get_identity_document(client: Client, current_block: dict, pubkey: str
identity = None
# parse results
for result in lookup_data['results']:
for result in lookup_data["results"]:
if result["pubkey"] == pubkey:
uids = result['uids']
uids = result["uids"]
uid_data = uids[0]
# capture data
timestamp = BlockUID.from_str(uid_data["meta"]["timestamp"])
......@@ -45,18 +47,20 @@ async def get_identity_document(client: Client, current_block: dict, pubkey: str
# return self-certification document
identity = Identity(
version=10,
currency=current_block['currency'],
currency=current_block["currency"],
pubkey=pubkey,
uid=uid,
ts=timestamp,
signature=signature
signature=signature,
)
break
return identity
def get_certification_document(current_block: dict, self_cert_document: Identity, from_pubkey: str) -> Certification:
def get_certification_document(
current_block: dict, self_cert_document: Identity, from_pubkey: str
) -> Certification:
"""
Create and return a Certification document
......@@ -67,9 +71,14 @@ def get_certification_document(current_block: dict, self_cert_document: Identity
:rtype: Certification
"""
# construct Certification Document
return Certification(version=10, currency=current_block['currency'], pubkey_from=from_pubkey,
identity=self_cert_document,
timestamp=BlockUID(current_block['number'], current_block['hash']), signature="")
return Certification(
version=10,
currency=current_block["currency"],
pubkey_from=from_pubkey,
identity=self_cert_document,
timestamp=BlockUID(current_block["number"], current_block["hash"]),
signature="",
)
async def main():
......
......@@ -17,7 +17,9 @@ BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
################################################
def get_identity_document(current_block: dict, uid: str, salt: str, password: str) -> Identity:
def get_identity_document(
current_block: dict, uid: str, salt: str, password: str
) -> Identity:
"""
Get an Identity document
......@@ -30,7 +32,7 @@ def get_identity_document(current_block: dict, uid: str, salt: str, password: st
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
timestamp = BlockUID(current_block["number"], current_block["hash"])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
......@@ -38,11 +40,11 @@ def get_identity_document(current_block: dict, uid: str, salt: str, password: st
# create identity document
identity = Identity(
version=10,
currency=current_block['currency'],
currency=current_block["currency"],
pubkey=key.pubkey,
uid=uid,
ts=timestamp,
signature=None
signature=None,
)
# sign document
......@@ -51,8 +53,13 @@ def get_identity_document(current_block: dict, uid: str, salt: str, password: st
return identity
def get_membership_document(membership_type: str, current_block: dict, identity: Identity, salt: str,
password: str) -> Membership:
def get_membership_document(
membership_type: str,
current_block: dict,
identity: Identity,
salt: str,
password: str,
) -> Membership:
"""
Get a Membership document
......@@ -66,7 +73,7 @@ def get_membership_document(membership_type: str, current_block: dict, identity:
"""
# get current block BlockStamp
timestamp = BlockUID(current_block['number'], current_block['hash'])
timestamp = BlockUID(current_block["number"], current_block["hash"])
# create keys from credentials
key = SigningKey.from_credentials(salt, password)
......@@ -74,12 +81,12 @@ def get_membership_document(membership_type: str, current_block: dict, identity:
# create identity document
membership = Membership(
version=10,
currency=current_block['currency'],
currency=current_block["currency"],
issuer=key.pubkey,
membership_ts=timestamp,
membership_type=membership_type,
uid=identity.uid,
identity_ts=identity.timestamp
identity_ts=identity.timestamp,
)
# sign document
......
......@@ -4,7 +4,12 @@ import getpass
from duniterpy.api import bma
from duniterpy.api.client import Client
from duniterpy.documents import BlockUID, Transaction
from duniterpy.documents.transaction import InputSource, OutputSource, Unlock, SIGParameter
from duniterpy.documents.transaction import (
InputSource,
OutputSource,
Unlock,
SIGParameter,
)
from duniterpy.key import SigningKey
# CONFIG #######################################
......@@ -21,7 +26,9 @@ TRANSACTION_VERSION = 10
################################################
def get_transaction_document(current_block: dict, source: dict, from_pubkey: str, to_pubkey: str) -> Transaction:
def get_transaction_document(
current_block: dict, source: dict, from_pubkey: str, to_pubkey: str
) -> Transaction:
"""
Return a Transaction document
......@@ -35,18 +42,16 @@ def get_transaction_document(current_block: dict, source: dict, from_pubkey: str
# list of inputs (sources)
inputs = [
InputSource(
amount=source['amount'],
base=source['base'],
source=source['type'],
origin_id=source['identifier'],
index=source['noffset']
amount=source["amount"],
base=source["base"],
source=source["type"],
origin_id=source["identifier"],
index=source["noffset"],
)
]
# list of issuers of the inputs
issuers = [
from_pubkey
]
issuers = [from_pubkey]