def test_anybody_can_verify(): """ In the last example, we used the lower-level Crypto API to verify the signature. Here, we show that anybody can do it without needing to directly access Crypto. """ # Alice can sign by default, by dint of her _default_crypto_powerups. alice = Alice(federated_only=True, start_learning_now=False) # So, our story is fairly simple: an everyman meets Alice. somebody = Character(start_learning_now=False, federated_only=True) # Alice signs a message. message = b"A message for all my friends who can only verify and not sign." signature = alice.stamp(message) # Our everyman can verify it. somebody.verify_from(alice, message, signature) # Of course, verification fails with any fake message with pytest.raises(InvalidSignature): fake = b"McLovin 892 Momona St. Honolulu, HI 96820" somebody.verify_from(alice, fake, signature) # Signature verification also works when Alice is not living with our # everyman in the same process, and he only knows her by her public key alice_pubkey_bytes = bytes(alice.stamp) hearsay_alice = Character.from_public_keys({SigningPower: alice_pubkey_bytes}) somebody.verify_from(hearsay_alice, message, signature) hearsay_alice = Character.from_public_keys(verifying_key=alice_pubkey_bytes) somebody.verify_from(hearsay_alice, message, signature) alice.disenchant()
def generate_owner_policy_public_key(self, max_days): self.ursula = Ursula.from_seed_and_stake_info( seed_uri=self.URSULA_SEEDNODE_URI, federated_only=True, minimum_stake=0) policy_end_datetime = maya.now() + datetime.timedelta(days=max_days) self.ALICE = Alice(network_middleware=RestMiddleware(), known_nodes=[self.ursula], learn_on_same_thread=True, federated_only=True) policy_pubkey = self.ALICE.get_policy_pubkey_from_label(self.label) return policy_pubkey
def from_bytes(cls, arrangement_as_bytes): # Still unclear how to arrive at the correct number of bytes to represent a deposit. See #148. alice_pubkey_sig, id, expiration_bytes = cls.splitter( arrangement_as_bytes) expiration = maya.parse(expiration_bytes.decode()) alice = Alice.from_public_keys({SigningPower: alice_pubkey_sig}) return cls(alice=alice, id=id, expiration=expiration)
def test_characters_use_keystore(temp_dir_path): keystore = Keystore.generate(password=INSECURE_DEVELOPMENT_PASSWORD, keystore_dir=temp_dir_path) keystore.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) alice = Alice(federated_only=True, start_learning_now=False, keystore=keystore) Bob(federated_only=True, start_learning_now=False, keystore=keystore) Ursula(federated_only=True, start_learning_now=False, keystore=keystore, rest_host=LOOPBACK_ADDRESS, rest_port=12345, db_filepath=tempfile.mkdtemp(), domain=TEMPORARY_DOMAIN) alice.disenchant( ) # To stop Alice's publication threadpool. TODO: Maybe only start it at first enactment?
def test_characters_use_keyring(tmpdir): keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS, password=INSECURE_DEVELOPMENT_PASSWORD, encrypting=True, rest=False, keyring_root=tmpdir) keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) a = Alice(federated_only=True, start_learning_now=False, keyring=keyring) Bob(federated_only=True, start_learning_now=False, keyring=keyring) Ursula(federated_only=True, start_learning_now=False, keyring=keyring, rest_host='127.0.0.1', rest_port=12345, db_filepath=tempfile.mkdtemp()) a.disenchant( ) # To stop Alice's publication threadpool. TODO: Maybe only start it at first enactment?
def from_bytes(cls, arrangement_as_bytes): alice_verifying_key, arrangement_id, expiration_bytes = cls.splitter( arrangement_as_bytes) expiration = maya.MayaDT.from_iso8601( iso8601_string=expiration_bytes.decode()) alice = Alice.from_public_keys(verifying_key=alice_verifying_key) return cls(alice=alice, arrangement_id=arrangement_id, expiration=expiration)
def from_bytes(cls, arrangement_as_bytes): # TODO #148 - Still unclear how to arrive at the correct number of bytes to represent a deposit. alice_verifying_key, arrangement_id, expiration_bytes = cls.splitter( arrangement_as_bytes) expiration = maya.parse(expiration_bytes.decode()) alice = Alice.from_public_keys(verifying_key=alice_verifying_key) return cls(alice=alice, arrangement_id=arrangement_id, expiration=expiration)
def test_anybody_can_verify(): """ In the last example, we used the lower-level Crypto API to verify the signature. Here, we show that anybody can do it without needing to directly access Crypto. """ # Alice can sign by default, by dint of her _default_crypto_powerups. alice = Alice(federated_only=True, start_learning_now=False) # So, our story is fairly simple: an everyman meets Alice. somebody = Character(start_learning_now=False, federated_only=True) # Alice signs a message. message = b"A message for all my friends who can only verify and not sign." signature = alice.stamp(message) # Our everyman can verify it. cleartext = somebody.verify_from(alice, message, signature, decrypt=False) assert cleartext is constants.NO_DECRYPTION_PERFORMED
async def onRequestBuy(event): SEEDNODE_URI = os.getenv("SEEDNODE_URI") ursula = Ursula.from_seed_and_stake_info(seed_uri="localhost:11500", federated_only=True, minimum_stake=0) NEW_PASSWORD = "******" try: keyring = NucypherKeyring.generate( checksum_address='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9', password=NEW_PASSWORD, # used to encrypt nucypher private keys keyring_root="//home/ghard/.local/share/nucypher/keyring") except: # Restore an existing Alice keyring keyring = NucypherKeyring( account='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9') keyring.unlock(password=NEW_PASSWORD) alice = Alice(keyring=keyring, known_nodes=[ursula], federated_only=True, learn_on_same_thread=True, domain=TEMPORARY_DOMAIN) user = event.args["buyer"] keys = masterfile_contract.functions.userKeys(user).call() print(user) print(keys) bob = Bob.from_public_keys(verifying_key=keys[0], encrypting_key=keys[1], federated_only=True) policy = alice.grant(bob, label=(str(event.args["tokenId"]) + os.urandom(4).hex()).encode(), m=2, n=3, expiration=maya.now() + timedelta(days=5)) policy.treasure_map_publisher.block_until_complete() print("done")
def test_characters_use_keyring(tmpdir): keyring = NucypherKeyring.generate(checksum_address=FEDERATED_ADDRESS, password=INSECURE_DEVELOPMENT_PASSWORD, encrypting=True, rest=False, keyring_root=tmpdir) keyring.unlock(password=INSECURE_DEVELOPMENT_PASSWORD) Alice(federated_only=True, start_learning_now=False, keyring=keyring) Bob(federated_only=True, start_learning_now=False, keyring=keyring) Ursula(federated_only=True, start_learning_now=False, keyring=keyring, rest_host='127.0.0.1', rest_port=12345)
ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI, federated_only=True, minimum_stake=0) # Here are our Policy details. policy_end_datetime = maya.now() + datetime.timedelta(days=5) m, n = 2, 3 label = b"secret/files/and/stuff" ###################################### # Alice, the Authority of the Policy # ###################################### ALICE = Alice(network_middleware=RestMiddleware(), domains={TEMPORARY_DOMAIN}, known_nodes=[ursula], learn_on_same_thread=True, federated_only=True) # Alice can get the public key even before creating the policy. # From this moment on, any Data Source that knows the public key # can encrypt data originally intended for Alice, but that can be shared with # any Bob that Alice grants access. policy_pubkey = ALICE.get_policy_encrypting_key_from_label(label) BOB = Bob(known_nodes=[ursula], domains={TEMPORARY_DOMAIN}, network_middleware=RestMiddleware(), federated_only=True, start_learning_now=True, learn_on_same_thread=True)
federated_only=True, minimum_stake=0) # Here are our Policy details. policy_end_datetime = maya.now() + datetime.timedelta(days=5) m, n = 2, 3 label = b"secret/files/and/stuff" sendMessage(encodeMessage("Label: {}".format(label.decode('ascii')))) sendMessage( encodeMessage("policy_end_datetime: {}".format(policy_end_datetime))) ###################################### # Alice, the Authority of the Policy # ###################################### ALICE = Alice(network_middleware=RestMiddleware(), known_nodes=[ursula], learn_on_same_thread=True, federated_only=True) # Alice can get the public key even before creating the policy. # From this moment on, any Data Source that knows the public key # can encrypt data originally intended for Alice, but that can be shared with # any Bob that Alice grants access. policy_pubkey = ALICE.get_policy_pubkey_from_label(label) BOB = Bob(known_nodes=[ursula], network_middleware=RestMiddleware(), federated_only=True, start_learning_now=True, learn_on_same_thread=True) ALICE.start_learning_loop(now=True)
os.mkdir(CRUFTSPACE) os.mkdir(CERTIFICATE_DIR) ursula_seed_node = SeednodeMetadata( checksum_address="0x154d9c2062a2Fd6f1a4eE827308634547ce84810", rest_host="18.184.168.218", rest_port=9151) ######### # Alice # ######### ALICE = Alice( network_middleware=RestMiddleware(), seed_nodes=[ursula_seed_node], learn_on_same_thread=True, federated_only=True, known_certificates_dir=CERTIFICATE_DIR, ) # Here are our Policy details. policy_end_datetime = maya.now() + datetime.timedelta(days=5) m = 2 n = 3 label = b"secret/files/and/stuff" # Alice grants to Bob. BOB = Bob(seed_nodes=[ursula_seed_node], network_middleware=RestMiddleware(), federated_only=True, start_learning_now=True,
# Setup and unlock alice's ethereum wallet. # WARNING: Never give your mainnet password or mnemonic phrase to anyone. # Do not use mainnet keys, create a dedicated software wallet to use for this demo. wallet = Signer.from_signer_uri(SIGNER_URI) password = os.environ.get('DEMO_ALICE_PASSWORD') or getpass( f"Enter password to unlock Alice's wallet ({ALICE_ADDRESS[:8]}): ") wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's payment method. payment_method = SubscriptionManagerPayment(network=L2_NETWORK, eth_provider=L2_PROVIDER) # This is Alicia. alicia = Alice(checksum_address=ALICE_ADDRESS, signer=wallet, domain=L1_NETWORK, eth_provider_uri=L1_PROVIDER, payment_method=payment_method) # Alice puts her public key somewhere for Bob to find later... alice_verifying_key = alicia.stamp.as_umbral_pubkey() # Let's get to learn about the NuCypher network alicia.start_learning_loop(now=True) # At this point, Alicia is fully operational and can create policies. # The Policy Label is a bytestring that categorizes the data that Alicia wants to share. # Note: we add some random chars to create different policies, only for demonstration purposes label = "heart-data-❤️-" + os.urandom(4).hex() label = label.encode()
class Buyer(ETHAccount): """ The person who pays for the book and receives content """ balance = 100 def __init__(self, eth_pk_bytes, character): self.account = Account.create(eth_pk_bytes) self.character = character author = Author( b"Author's ETH account", Alice( network_middleware=RestMiddleware(), known_nodes=(URSULA, ), federated_only=True, known_certificates_dir=CERTIFICATE_DIR, )) author.character.start_learning_loop(now=True) book = Book(author) first_buyer = Buyer( b"First Buyer's ETH account", Bob(known_nodes=(URSULA, ), federated_only=True, known_certificates_dir=CERTIFICATE_DIR)) book_store_delivery = BookStoreDelivery(book) book_store_contract = BookStoreEthContract( book, author, 10, book_store_delivery.deliver_purchase) author_public_key, policy_public_key, data_source_public_key, label, kit = first_buyer.send_eth_to( book_store_contract, 10)
# Bob the BUIDLer ## ##################### # First there was Bob. bob = Bob(federated_only=True, domain=TEMPORARY_DOMAIN, known_nodes=[ursula]) # Bob gives his public keys to alice. verifying_key = bob.public_keys(SigningPower) encrypting_key = bob.public_keys(DecryptingPower) ###################################### # Alice, the Authority of the Policy # ###################################### alice = Alice(federated_only=True, domain=TEMPORARY_DOMAIN, known_nodes=[ursula]) # Start node discovery and wait until 8 nodes are known in case # the fleet isn't fully spun up yet, as sometimes happens on CI. alice.start_learning_loop(now=True) alice.block_until_number_of_known_nodes_is(8, timeout=30, learn_on_this_thread=True) # Alice can get the public key even before creating the policy. # From this moment on, any Data Source that knows the public key # can encrypt data originally intended for Alice, but that can be shared with # any Bob that Alice grants access. policy_public_key = alice.get_policy_encrypting_key_from_label(label)
###################################### # Connect to the ethereum provider. connect_web3_provider(eth_provider_uri=ETH_PROVIDER_URI) # Setup and unlock alice's ethereum wallet. # WARNING: Never give your mainnet password or mnemonic phrase to anyone. # Do not use mainnet keys, create a dedicated software wallet to use for this demo. wallet = Signer.from_signer_uri(SIGNER_URI) password = os.environ.get('DEMO_ALICE_PASSWORD') or getpass( f"Enter password to unlock {ALICE_ADDRESS[:8]}: ") wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice. alice = Alice(checksum_address=ALICE_ADDRESS, signer=wallet, domain=TESTNET, eth_provider_uri=ETH_PROVIDER_URI) # Alice puts her public key somewhere for Bob to find later... alice_verifying_key = bytes(alice.stamp) # Alice can get the policy's public key even before creating the policy. label = b"secret/files/42" policy_public_key = alice.get_policy_encrypting_key_from_label(label) # From this moment on, anyone that knows the public key # can encrypt data originally intended for Alice, but that # can be shared with any Bob that Alice grants access. # Alice already knows Bob's public keys from a side-channel. remote_bob = Bob.from_public_keys(encrypting_key=encrypting_key,
try: keyring = NucypherKeyring.generate( checksum_address='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9', password=NEW_PASSWORD, # used to encrypt nucypher private keys keyring_root="//home/ghard/.local/share/nucypher/keyring") except: # Restore an existing Alice keyring keyring = NucypherKeyring( account='0xf61DBAbF5Ac0A3F99e91b663A590cF4cB58563D9') keyring.unlock(password=NEW_PASSWORD) alice = Alice(keyring=keyring, known_nodes=[ursula], federated_only=True, learn_on_same_thread=True, domain=TEMPORARY_DOMAIN) alice_sig_pubkey = alice.stamp size = 128, 128 formats = {"JPEG": ".jpg", "PNG": ".png", "GIF": ".gif"} formatsReversed = {".jpg": "JPEG", ".png": "PNG", ".gif": "GIF"} base_uri = "https://hub.textile.io/ipns/" + BUCKET_ID + "/" # Web 3 initiation from web3 import Web3, HTTPProvider, eth
f.seek(0) teacher_bytes = binascii.unhexlify(f.read()) URSULA = Ursula.from_bytes(teacher_bytes, federated_only=True) print("DDRM: Will learn from {}".format(URSULA)) SHARED_CRUFTSPACE = "{}/nucypher/examples/examples-runtime-cruft".format(os.path.dirname(os.path.abspath(__file__))) CRUFTSPACE = "{}/drm".format(SHARED_CRUFTSPACE) CERTIFICATE_DIR = "{}/certs".format(CRUFTSPACE) shutil.rmtree(CRUFTSPACE, ignore_errors=True) os.mkdir(CRUFTSPACE) os.mkdir(CERTIFICATE_DIR) URSULA.save_certificate_to_disk(CERTIFICATE_DIR) print("DDRM: Instantiating the stream author") author = Author(network_middleware=RestMiddleware(), known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR, ) print("DDRM: Author instantiated {}".format(author)) author.start_learning_loop(now=True) print("DDRM: Instantiating raw unprotected stream to keep in secret") raw_stream = RawStream(author) print("DDRM: Raw unprotected stream instantiated {}".format(raw_stream)) print("DDRM: Encyphering the stream for publishing") protected_stream = PublicEdekProtectedStream(raw_stream) print("DDRM: Stream encrypted and published {}".format(protected_stream)) print("DDRM: Instantiating the Subscriber") subscriber = Subscriber(known_nodes=(URSULA,), federated_only=True, known_certificates_dir=CERTIFICATE_DIR) print("DDRM: Subscriber instantiated {}".format(subscriber))
bob_proxy_account = w3.eth.contract(address=bob_proxy_account_address, abi=proxy_account_interface['abi']) # Enrico deploys a ProxyAccount w3.eth.defaultAccount = enrico_eth_address enrico_proxy_account_address = deploy_contract(w3, proxy_account_interface) enrico_proxy_account = w3.eth.contract(address=enrico_proxy_account_address, abi=proxy_account_interface['abi']) ###################################### # Alice, the Authority of the Policy # ###################################### alice = Alice(network_middleware=RestMiddleware(), domains={TEMPORARY_DOMAIN}, known_nodes=[ursula], learn_on_same_thread=True, federated_only=True) # store public keys on chain w3.eth.defaultAccount = alice_eth_address alice_nucypher_decrypting_pub_key = alice.public_keys( DecryptingPower).to_bytes() tx_hash = alice_proxy_account.functions.setData( nucypher_decrypting_key, alice_nucypher_decrypting_pub_key).transact() w3.eth.waitForTransactionReceipt(tx_hash) alice_nucypher_signing_pub_key = alice.public_keys(SigningPower).to_bytes() tx_hash = alice_proxy_account.functions.setData( nucypher_signing_key, alice_nucypher_signing_pub_key).transact() w3.eth.waitForTransactionReceipt(tx_hash) #########################
########## # LABELS # ########## print("Creating labels") label_A = b"electronic/health/data/A" label_D = b"electronic/health/data/D" ###################################### # Alice, the Authority of the Policy # ###################################### print("Starting Alice, a patient seeking to be matched to a trial") ALICE = Alice(network_middleware=RestMiddleware(), domains={TEMPORARY_DOMAIN}, known_nodes=[ursula], learn_on_same_thread=True, federated_only=True) ########################## # Alice gets policy keys # ########################## policy_pubkey_A = ALICE.get_policy_encrypting_key_from_label(label_A) policy_pubkey_D = ALICE.get_policy_encrypting_key_from_label(label_D) ###################################### # Creating our data consumers/Bobs # ###################################### print( "Starting Bob researchers looking for patients to participate in their trials."
# Alice, the Authority of the Policy # ###################################### # Connect to the ethereum provider. connect_web3_provider(provider_uri=PROVIDER_URI) # Setup and unlock alice's ethereum wallet. # WARNING: Never give your mainnet password or mnemonic phrase to anyone. # Do not use mainnet keys, create a dedicated software wallet to use for this demo. wallet = Signer.from_signer_uri(SIGNER_URI) password = os.environ.get('DEMO_ALICE_PASSWORD') or getpass( f"Enter password to unlock {ALICE_ADDRESS[:8]}: ") wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice. alice = Alice(checksum_address=ALICE_ADDRESS, signer=wallet, domain=TESTNET) # Alice puts her public key somewhere for Bob to find later... alice_verifying_key = bytes(alice.stamp) # Alice can get the policy's public key even before creating the policy. label = b"secret/files/42" policy_public_key = alice.get_policy_encrypting_key_from_label(label) # From this moment on, anyone that knows the public key # can encrypt data originally intended for Alice, but that # can be shared with any Bob that Alice grants access. # Alice already knows Bob's public keys from a side-channel. remote_bob = Bob.from_public_keys(encrypting_key=encrypting_key, verifying_key=verifying_key)
def make_alice_control(drone_alice: Alice, teacher_node: Ursula): alice_control = Flask("alice-control") teacher_node.verify_node(drone_alice.network_middleware) drone_alice.remember_node(teacher_node) drone_alice.start_learning_loop(now=True) @alice_control.route("/create_policy", methods=['PUT']) def create_policy(): """ Character control endpoint for creating a policy and making arrangements with Ursulas. This is an unfinished API endpoint. You are probably looking for grant. """ # TODO: Needs input cleansing and validation # TODO: Provide more informative errors try: request_data = json.loads(request.data) bob_pubkey = bytes.fromhex(request_data['bob_encrypting_key']) label = b64decode(request_data['label']) # TODO: Do we change this to something like "threshold" m, n = request_data['m'], request_data['n'] federated_only = True # const for now bob = Bob.from_public_keys( { DecryptingPower: bob_pubkey, SigningPower: None }, federated_only=True) except (KeyError, JSONDecodeError) as e: return Response(str(e), status=400) new_policy = drone_alice.create_policy(bob, label, m, n, federated=federated_only) # TODO: Serialize the policy return Response('Policy created!', status=200) @alice_control.route("/grant", methods=['PUT']) def grant(): """ Character control endpoint for policy granting. """ # TODO: Needs input cleansing and validation # TODO: Provide more informative errors try: request_data = json.loads(request.data) bob_pubkey = bytes.fromhex(request_data['bob_encrypting_key']) label = b64decode(request_data['label']) # TODO: Do we change this to something like "threshold" m, n = request_data['m'], request_data['n'] expiration_time = maya.MayaDT.from_iso8601( request_data['expiration_time']) federated_only = True # const for now bob = Bob.from_public_keys( { DecryptingPower: bob_pubkey, SigningPower: None }, federated_only=True) except (KeyError, JSONDecodeError) as e: return Response(str(e), status=400) new_policy = drone_alice.grant(bob, label, m=m, n=n, expiration=expiration_time) # TODO: Serialize the policy response_data = { 'result': { 'treasure_map': b64encode(bytes(new_policy.treasure_map)).decode(), } } return Response(json.dumps(response_data), status=200) return alice_control
with open(teacher_metadata_path, "r") as f: f.seek(0) teacher_bytes = binascii.unhexlify(f.read()) URSULA = Ursula.from_bytes(teacher_bytes, federated_only=True) print("Will learn from {}".format(URSULA)) URSULA.save_certificate_to_disk(CERTIFICATE_DIR) ######### # Alice # ######### ALICE = Alice(network_middleware=RestMiddleware(), known_nodes=(URSULA,), federated_only=True, always_be_learning=True, known_certificates_dir=CERTIFICATE_DIR, ) # Here are our Policy details. policy_end_datetime = maya.now() + datetime.timedelta(days=5) m = 2 n = 3 label = b"secret/files/and/stuff" # Alice grants to Bob. BOB = Bob(known_nodes=(URSULA,), federated_only=True, always_be_learning=True, known_certificates_dir=CERTIFICATE_DIR) ALICE.start_learning_loop(now=True)
# Setup and unlock alice's ethereum wallet. # WARNING: Never give your mainnet password or mnemonic phrase to anyone. # Do not use mainnet keys, create a dedicated software wallet to use for this demo. wallet = Signer.from_signer_uri(SIGNER_URI) password = os.environ.get('DEMO_ALICE_PASSWORD') or getpass( f"Enter password to unlock Alice's wallet ({ALICE_ADDRESS[:8]}): ") wallet.unlock_account(account=ALICE_ADDRESS, password=password) # This is Alice's payment method. payment_method = SubscriptionManagerPayment(network=L2_NETWORK, eth_provider=L2_PROVIDER) # This is Alice. alice = Alice(checksum_address=ALICE_ADDRESS, signer=wallet, domain=L1_NETWORK, eth_provider_uri=L1_PROVIDER, payment_method=payment_method) # Alice puts her public key somewhere for Bob to find later... alice_verifying_key = alice.stamp.as_umbral_pubkey() print("\n************** Grant **************\n") # Alice can get the policy's public key even before creating the policy. label = b"secret/files/42" policy_public_key = alice.get_policy_encrypting_key_from_label(label) # From this moment on, anyone that knows the public key # can encrypt data originally intended for Alice, but that # can be shared with any Bob that Alice grants access.
class Client(object): URSULA_SEEDNODE_URI = "" def __init__(self, ursula_url): self.URSULA_SEEDNODE_URI = ursula_url # todo : customise ipfs host self.ipfs = ipfsapi.connect("https://ipfs.infura.io", 5001) random_name = fake.name() self.label = random_name.encode() self.m = 2 self.n = 3 def node_info(self): return self.ipfs.id() def generate_recipient_keys(self): enc_privkey = UmbralPrivateKey.gen_key() sig_privkey = UmbralPrivateKey.gen_key() recipient_privkeys = { 'enc': enc_privkey.to_bytes().hex(), 'sig': sig_privkey.to_bytes().hex(), } enc_pubkey = enc_privkey.get_pubkey() sig_pubkey = sig_privkey.get_pubkey() recipient_pubkeys = { 'enc': enc_pubkey.to_bytes().hex(), 'sig': sig_pubkey.to_bytes().hex() } return recipient_privkeys, recipient_pubkeys def generate_owner_policy_public_key(self, max_days): self.ursula = Ursula.from_seed_and_stake_info( seed_uri=self.URSULA_SEEDNODE_URI, federated_only=True, minimum_stake=0) policy_end_datetime = maya.now() + datetime.timedelta(days=max_days) self.ALICE = Alice(network_middleware=RestMiddleware(), known_nodes=[self.ursula], learn_on_same_thread=True, federated_only=True) policy_pubkey = self.ALICE.get_policy_pubkey_from_label(self.label) return policy_pubkey def uploadFile(self, filename, policy_pubkey): data_source = Enrico(policy_encrypting_key=policy_pubkey) data_source_public_key = bytes(data_source.stamp) file = open(filename, "r").read() encoded = base64.b64encode(file.encode()) encrypt_message, _signature = data_source.encrypt_message(encoded) kit_bytes = encrypt_message.to_bytes() try: os.mkdir("./tmp") except Exception as e: logging.info("temp folder exist") temp = open('./tmp/' + filename, 'wb') temp.write(kit_bytes) temp.close() res = self.ipfs.add('./tmp/' + filename) receipt_info = { "data_source_public_key": data_source_public_key.hex(), "hash_key": res['Hash'] } return receipt_info def authorize(self, recipient_pubkeys, max_days=5): powers_and_material = { DecryptingPower: UmbralPublicKey.from_bytes(bytes.fromhex( recipient_pubkeys["enc"])), SigningPower: UmbralPublicKey.from_bytes(bytes.fromhex(recipient_pubkeys["sig"])) } recipient = Bob.from_public_keys( powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=max_days) m, n = self.m, self.n self.ALICE.start_learning_loop(now=True) policy = self.ALICE.grant(recipient, self.label, m=m, n=n, expiration=policy_end_datetime) alices_pubkey = bytes(self.ALICE.stamp) policy_info = { "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": alices_pubkey, "label": self.label.decode("utf-8") } return policy_info def downloadFile(self, downloadFilename, recipient_privkeys, receipt, policy_info): hash = receipt['hash_key'] input = self.ipfs.cat(hash) ursula = Ursula.from_seed_and_stake_info( seed_uri=self.URSULA_SEEDNODE_URI, federated_only=True, minimum_stake=0) bob_enc_keypair = DecryptingKeypair( private_key=UmbralPrivateKey.from_bytes( bytes.fromhex(recipient_privkeys["enc"]))) bob_sig_keypair = SigningKeypair( private_key=UmbralPrivateKey.from_bytes( bytes.fromhex(recipient_privkeys["sig"]))) enc_power = DecryptingPower(keypair=bob_enc_keypair) sig_power = SigningPower(keypair=bob_sig_keypair) power_ups = [enc_power, sig_power] authorizedRecipient = Bob( is_me=True, federated_only=True, crypto_power_ups=power_ups, start_learning_now=True, abort_on_learning_error=True, known_nodes=[ursula], save_metadata=False, network_middleware=RestMiddleware(), ) policy_pubkey = UmbralPublicKey.from_bytes( bytes.fromhex(policy_info["policy_pubkey"])) enrico_as_understood = Enrico.from_public_keys( { SigningPower: UmbralPublicKey.from_bytes( bytes.fromhex(receipt['data_source_public_key'])) }, #{SigningPower: data_source_public_key}, policy_encrypting_key=policy_pubkey) alice_pubkey_restored = UmbralPublicKey.from_bytes( (policy_info['alice_sig_pubkey'])) authorizedRecipient.join_policy(policy_info['label'].encode(), alice_pubkey_restored) kit = UmbralMessageKit.from_bytes(input) delivered_cleartexts = authorizedRecipient.retrieve( message_kit=kit, data_source=enrico_as_understood, alice_verifying_key=alice_pubkey_restored, label=(policy_info['label'].encode())) #delivered_cleartexts = authorizedRecipient.retrieve(message_kit=kit,data_source=data_source,alice_verifying_key=alice_pubkey_restored, label=(policy_info['label'].encode()) ) data = base64.b64decode(delivered_cleartexts[0]) output = open('./' + downloadFilename, 'wb') output.write(data) output.close()