1import hashlib
2import pprint
3import requests
4import sys
5
6# The base URL of the notary service API.
7base_url = 'https://eu2-cloud.acronis.com/api/notary/v2'
8
9
10def calculate_file_hash(file_path):
11 """Calculates the SHA-256 hash value of file contents."""
12
13 with open(file_path, 'rb') as fd:
14 sha256 = hashlib.sha256()
15 chunk = fd.read(128 * sha256.block_size)
16 while chunk:
17 sha256.update(chunk)
18 chunk = fd.read(128 * sha256.block_size)
19 return sha256.hexdigest()
20
21
22def verify(file_path, certificate_id):
23 """
24 Verifies if a file is notarized by calculating its hash and checking if
25 this hash was written to the Ethereum blockchain during a specific notarization
26 process designated by the notarization certificate ID.
27 """
28
29 # Create the meta object with the file name and calculated hash value.
30 file_hash_data = {
31 'hash': calculate_file_hash(file_path),
32 'certificate_hash': certificate_id,
33 }
34
35 # Post the object to the notary service.
36 try:
37 response = requests.post(f'{base_url}/hashes/verify', json=file_hash_data)
38 except requests.ConnectionError:
39 print('No connection to the notary service.',
40 'Try again later or contact your service administrator.')
41 return
42
43 # Check for errors.
44 status_code = response.status_code
45 if status_code == 404:
46 print('This file has never been notarized.')
47 return
48 if status_code != 200:
49 print(response.status_code, response.reason)
50 return
51
52 # Convert the JSON text that the response body contains to an object,
53 # and then fetch the notarization certificate.
54 certificate = response.json()['certificates'][0]
55
56 if not certificate['txid']:
57 print('The file notarization is in progress.')
58 return
59
60 print('The file is notarized.')
61 pprint.pprint(certificate)
62
63
64if __name__ == '__main__':
65 verify(sys.argv[1], sys.argv[2])