def create_policy(self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, first_period_reward: int = None) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.create_policy( bob=bob, label=label, m=m, n=n, expiration=expiration, value=value, first_period_reward=first_period_reward) response_data = { 'label': new_policy.label, 'policy_encrypting_key': new_policy.public_key } return response_data
def assignPolicyToSubscriber(subsriber, sub_uuid, event_uuid, publicEnc, publicSign): label = event_uuid.encode() m, n = 1, 1 subenc = UmbralPublicKey.from_bytes(bytes.fromhex(publicEnc)) subsig = UmbralPublicKey.from_bytes(bytes.fromhex(publicSign)) ourCurrentSubscriber = Bob.from_public_keys(verifying_key=subsig, encrypting_key=subenc, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=5) print("Creating access policy for the Doctor...") policy = alicia.grant(bob=ourCurrentSubscriber, label=label, m=m, n=n, expiration=policy_end_datetime) print("Done!") print(ourCurrentSubscriber) policy_info = { "policy_pub_key": policy.public_key.to_bytes().hex(), "policy_sig_key": bytes(alicia.stamp).hex(), "label": label.decode("utf-8"), } return policy_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 from_rest_payload(cls, arrangement_id, rest_payload, ursula_pubkey_bytes, alice_address): payload_splitter = BytestringSplitter(Signature) + key_splitter payload_elements = payload_splitter(rest_payload, msgpack_remainder=True) signature, bob_pubkey_sig, (tasks_bytes, blockhash) = payload_elements # TODO: check freshness of blockhash? # Check receipt receipt_bytes = b"wo:" + ursula_pubkey_bytes + msgpack.dumps(tasks_bytes) if not signature.verify(receipt_bytes, bob_pubkey_sig): raise InvalidSignature() tasks = [] for task_bytes in tasks_bytes: task = cls.Task.from_bytes(task_bytes) tasks.append(task) # Each task signature has to match the original specification specification = task.get_specification(ursula_pubkey_bytes, alice_address, blockhash) if not task.signature.verify(specification, bob_pubkey_sig): raise InvalidSignature() bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob=bob, arrangement_id=arrangement_id, tasks=tasks, alice_address=alice_address, blockhash=blockhash, receipt_signature=signature)
def grant_access_policy(label, bob_pubkeys): ''' Alicia creates a policy granting access to Bob. The policy is sent to the NuCypher network. ''' alicia = get_alice() label = label.encode() # We create a view of the Bob who's going to be granted access. active_listener = Bob.from_public_keys(verifying_key=bob_pubkeys['sig'], encrypting_key=bob_pubkeys['enc'], federated_only=True) print("Creating access policy for the Listener...") # Policy expiration date policy_end_datetime = maya.now() + datetime.timedelta(days=5) # m-out-of-n: This means Alicia splits the re-encryption key in 2 pieces and # she requires Bob to seek collaboration of at least 1 Ursulas m, n = 1, 2 policy = alicia.grant(bob=active_listener, label=label, m=m, n=n, expiration=policy_end_datetime) print(json.dumps({ "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": bytes(alicia.stamp).hex(), "label": label.decode(), }))
def grant( self, bob_encrypting_key: PublicKey, bob_verifying_key: PublicKey, label: bytes, threshold: int, shares: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.implementer.grant(bob=bob, label=label, threshold=threshold, shares=shares, value=value, rate=rate, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, # For the users of this interface, Publisher is always the same as Alice, # so we are only returning the Alice's key. 'alice_verifying_key': self.implementer.stamp.as_umbral_pubkey() } return response_data
def create_policy( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, federated_only: bool = True, # TODO: Default for now ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key, federated_only=federated_only) new_policy = self.character.create_policy(bob, label, m, n, federated=federated_only) response_data = { 'label': new_policy.label, 'policy_encrypting_key': new_policy.public_key } return response_data
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)
def _mock_ursula_reencrypts(ursula): delegating_privkey = SecretKey.random() capsule, _ciphertext = encrypt(delegating_privkey.public_key(), b'unused') signing_privkey = SecretKey.random() signing_pubkey = signing_privkey.public_key() signer = Signer(signing_privkey) priv_key_bob = SecretKey.random() pub_key_bob = priv_key_bob.public_key() kfrags = generate_kfrags(delegating_sk=delegating_privkey, signer=signer, receiving_pk=pub_key_bob, threshold=2, num_kfrags=4, sign_delegating_key=False, sign_receiving_key=False) ursula_pubkey = ursula.stamp.as_umbral_pubkey() alice_address = canonical_address_from_umbral_key(signing_pubkey) blockhash = bytes(32) specification = b''.join((bytes(capsule), bytes(ursula_pubkey), bytes(ursula.decentralized_identity_evidence), alice_address, blockhash)) bobs_signer = Signer(priv_key_bob) task_signature = bytes(bobs_signer.sign(specification)) cfrag = reencrypt(capsule, kfrags[0]) cfrag_signature = ursula.stamp(bytes(cfrag)) bob = Bob.from_public_keys(verifying_key=pub_key_bob) return WorkOrder.PRETask(capsule, task_signature, cfrag, cfrag_signature)
def grant( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, federated_only: bool = True # TODO: Default for now ) -> dict: from nucypher.characters.lawful import Bob # Operate bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key, federated_only=federated_only) new_policy = self.character.grant(bob, label, m=m, n=n, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp } return response_data
def from_rest_payload(cls, arrangement_id, rest_payload): # TODO: Use JSON instead? This is a mess. payload_splitter = BytestringSplitter(Signature) + key_splitter signature, bob_pubkey_sig, remainder = payload_splitter( rest_payload, msgpack_remainder=True) receipt_bytes, *remainder = remainder packed_capsules, packed_signatures, *remainder = remainder alice_address, alice_address_signature = remainder alice_address_signature = Signature.from_bytes(alice_address_signature) if not alice_address_signature.verify(alice_address, bob_pubkey_sig): raise cls.NotFromBob() capsules, capsule_signatures = list(), list() for capsule_bytes, capsule_signature in zip( msgpack.loads(packed_capsules), msgpack.loads(packed_signatures)): capsules.append( Capsule.from_bytes(capsule_bytes, params=default_params())) capsule_signature = Signature.from_bytes(capsule_signature) capsule_signatures.append(capsule_signature) if not capsule_signature.verify(capsule_bytes, bob_pubkey_sig): raise cls.NotFromBob() verified = signature.verify(receipt_bytes, bob_pubkey_sig) if not verified: raise cls.NotFromBob() bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob, arrangement_id, capsules, capsule_signatures, alice_address, alice_address_signature, receipt_bytes, signature)
def grant(self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.grant(bob=bob, label=label, m=m, n=n, value=value, rate=rate, expiration=expiration, discover_on_this_thread=True) new_policy.publishing_mutex.block_until_success_is_reasonably_likely() response_data = {'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp} return response_data
def grant( self, bob_encrypting_key: bytes, bob_verifying_key: bytes, label: bytes, m: int, n: int, expiration: maya.MayaDT, value: int = None, rate: int = None, ) -> dict: from nucypher.characters.lawful import Bob bob = Bob.from_public_keys(encrypting_key=bob_encrypting_key, verifying_key=bob_verifying_key) new_policy = self.character.grant(bob=bob, label=label, m=m, n=n, value=value, rate=rate, expiration=expiration) response_data = { 'treasure_map': new_policy.treasure_map, 'policy_encrypting_key': new_policy.public_key, 'alice_verifying_key': new_policy.alice.stamp } return response_data
def reencrypt(): from nucypher.characters.lawful import Bob # TODO: Cache & Optimize reenc_request = ReencryptionRequest.from_bytes(request.data) hrac = reenc_request.hrac bob = Bob.from_public_keys(verifying_key=reenc_request.bob_verifying_key) log.info(f"Reencryption request from {bob} for policy {hrac}") # Right off the bat, if this HRAC is already known to be revoked, reject the order. if hrac in this_node.revoked_policies: return Response(response=f"Policy with {hrac} has been revoked.", status=HTTPStatus.UNAUTHORIZED) publisher_verifying_key = reenc_request.publisher_verifying_key # Bob bob_ip_address = request.remote_addr bob_verifying_key = bob.stamp.as_umbral_pubkey() bob_identity_message = f"[{bob_ip_address}] Bob({bytes(bob.stamp).hex()})" # Verify & Decrypt KFrag Payload try: verified_kfrag = this_node._decrypt_kfrag(reenc_request.encrypted_kfrag, hrac, publisher_verifying_key) except DecryptingKeypair.DecryptionFailed: # TODO: don't we want to record suspicious activities here too? return Response(response="EncryptedKeyFrag decryption failed.", status=HTTPStatus.FORBIDDEN) except InvalidSignature as e: message = f'{bob_identity_message} Invalid signature for KeyFrag: {e}.' log.info(message) # TODO (#567): bucket the node as suspicious return Response(message, status=HTTPStatus.UNAUTHORIZED) # 401 - Unauthorized except Exception as e: message = f'{bob_identity_message} Invalid EncryptedKeyFrag: {e}.' log.info(message) # TODO (#567): bucket the node as suspicious return Response(message, status=HTTPStatus.BAD_REQUEST) # Enforce Policy Payment # TODO: Accept multiple payment methods # TODO: Evaluate multiple reencryption prerequisites & enforce policy expiration paid = this_node.payment_method.verify(payee=this_node.checksum_address, request=reenc_request) if not paid: message = f"{bob_identity_message} Policy {bytes(hrac)} is unpaid." return Response(message, status=HTTPStatus.PAYMENT_REQUIRED) # Re-encrypt # TODO: return a sensible response if it fails (currently results in 500) response = this_node._reencrypt(kfrag=verified_kfrag, capsules=reenc_request.capsules) # Now, Ursula saves evidence of this workorder to her database... # Note: we give the work order a random ID to store it under. with datastore.describe(ReencryptionRequestModel, str(uuid.uuid4()), writeable=True) as new_request: new_request.bob_verifying_key = bob_verifying_key headers = {'Content-Type': 'application/octet-stream'} return Response(headers=headers, response=bytes(response))
def onRequestBuy(event): # print(event) user = event.args["buyer"] keys = masterfile_contract.functions.userKeys(user).call() tokenId = event.args["tokenId"] token = masterfile_contract.functions.tokenData(tokenId).call() uri = token[1] label = token[2] print(user) print(token) global globalStorage # Call token transfer # using fake policy id compiled_data = encode_abi(['bytes16', 'uint256', 'string', 'address[]'], [ Random.new().read(16), 432000, label, [ "0x9920328f8D239613cDfFea4578e37d843772738F", "0xf71C4fbb1D0a85ded90c58fF347a026E6b8146AC", "0xC11F4fAa477b1634369153c8654eEF581425AD15" ] ]) masterfile_contract.functions.safeTransferFrom( token[0], user, tokenId, 1, compiled_data).transact({'from': w3.eth.accounts[0]}) # Revoke old policy try: if globalStorage[uri]["policy"]: alice.revoke(globalStorage[uri]["policy"]) print("Policy Revoked") except: print("No Policy") # Distribute kfrags # try: print(keys) bob = Bob.from_public_keys(verifying_key=keys[0], encrypting_key=keys[1], federated_only=True) policy = alice.grant(bob, label=uri.encode(), m=2, n=3, expiration=maya.now() + timedelta(days=5)) temp = globalStorage[uri] temp["policy"] = policy globalStorage[uri] = temp # except: # print("policy exsists") policy.treasure_map_publisher.block_until_complete() print("Policy {} was created".format(label))
def make_random_bob(): """Generates a random ephemeral Bob instance.""" bob_verifying_secret = UmbralPrivateKey.gen_key() bob_verifying_key = bob_verifying_secret.pubkey decrypting_secret = UmbralPrivateKey.gen_key() decrypting_key = decrypting_secret.pubkey bob = Bob.from_public_keys(verifying_key=bob_verifying_key, encrypting_key=decrypting_key, federated_only=False) return bob
def make_random_bob(): """Generates a random ephemeral Bob instance.""" bob_verifying_secret = SecretKey.random() bob_verifying_key = bob_verifying_secret.public_key() decrypting_secret = SecretKey.random() decrypting_key = decrypting_secret.public_key() bob = Bob.from_public_keys(verifying_key=bob_verifying_key, encrypting_key=decrypting_key, federated_only=False) print(f'Created BOB - {bytes(bob.stamp).hex()}') return bob
def __init__(self, signing_power_bytes: bytes, decrypt_power_bytes: bytes): self.signing_power_bytes = signing_power_bytes self.decrypt_power_bytes = decrypt_power_bytes powers_and_material = { DecryptingPower: UmbralPublicKey.from_bytes(decrypt_power_bytes), SigningPower: UmbralPublicKey.from_bytes(signing_power_bytes) } self.BOB = Bob.from_public_keys(powers_and_material, federated_only=True)
def grant_access(revoke_time, grant_time, days, m, n, recipient_pubkey_hex): label = b'vehicle-data' if int(revoke_time) >= int(grant_time): # either triggered at start or because revoke was executed return '' # Alicia now wants to share data associated with this label. # To do so, she needs the public key of the recipient. # In this example, we generate it on the fly (for demonstration purposes) bob_pubkeys = demo_keys.get_recipient_pubkeys("bob") powers_and_material = { DecryptingPower: bob_pubkeys['enc'], SigningPower: bob_pubkeys['sig'] } # We create a view of the Bob who's going to be granted access. bob = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) # Here are our remaining Policy details, such as: # - Policy duration policy_end_datetime = maya.now() + datetime.timedelta(days=int(days)) # - m-out-of-n: This means Alicia splits the re-encryption key in 5 pieces and # she requires Bob to seek collaboration of at least 3 Ursulas # TODO: Let's put just one Ursula for the moment. m, n = 1, 1 # With this information, Alicia creates a policy granting access to Bob. # The policy is sent to the NuCypher network. print("Creating access policy for the Doctor...") policy = alicia.grant(bob=bob, label=label, m=int(m), n=int(n), expiration=policy_end_datetime) print("Done!") # For the demo, we need a way to share with Bob some additional info # about the policy, so we store it in a JSON file policy_info = { "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": bytes(alicia.stamp).hex(), "label": label.decode("utf-8"), } with open(POLICY_INFO_FILE, 'w') as f: json.dump(policy_info, f) return 'Access granted to recipient with public key: {}!'.format( recipient_pubkey_hex)
def createPolicy(): print('data') print(request.data.decode('utf-8')) print('data\n\n') json_data = json.loads(request.data.decode('utf-8')) bobName = json_data['bob'] label = json_data['label'] aliceFile = json_data['alice'] password = json_data['password'] label = label.encode() # Generating Alice alice_config = AliceConfiguration.from_configuration_file( filepath=aliceFile, known_nodes={ursula}, start_learning_now=False, ) print(alice_config) alice_config.attach_keyring() alice_config.keyring.unlock(password=password) alicia = alice_config(domains={'TEMPORARY_DOMAIN'}) alicia.start_learning_loop(now=True) # Generating Bob bobFilePath = os.path.join(os.getcwd(), 'bob/' + bobName + '.json') doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey) powers_and_material = { DecryptingPower: doctor_pubkeys['enc'], SigningPower: doctor_pubkeys['sig'] } print (powers_and_material) doctor_strange = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=10) # Generate Policy policy = alicia.grant(bob=doctor_strange, label=label, m=1, n=1, expiration=policy_end_datetime) print (policy.public_key.to_bytes().hex()) data = { 'done' : True } return jsonify(data)
def from_rest_payload(cls, arrangement_id, rest_payload): payload_splitter = BytestringSplitter(Signature) + key_splitter signature, bob_pubkey_sig, (receipt_bytes, packed_capsules) = payload_splitter( rest_payload, msgpack_remainder=True) capsules = [ Capsule.from_bytes(p, params=default_params()) for p in msgpack.loads(packed_capsules) ] verified = signature.verify(receipt_bytes, bob_pubkey_sig) if not verified: raise ValueError("This doesn't appear to be from Bob.") bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob, arrangement_id, capsules, receipt_bytes, signature)
def _mock_ursula_reencrypts(ursula, corrupt_cfrag: bool = False): delegating_privkey = UmbralPrivateKey.gen_key() _symmetric_key, capsule = pre._encapsulate(delegating_privkey.get_pubkey()) signing_privkey = UmbralPrivateKey.gen_key() signing_pubkey = signing_privkey.get_pubkey() signer = Signer(signing_privkey) priv_key_bob = UmbralPrivateKey.gen_key() pub_key_bob = priv_key_bob.get_pubkey() kfrags = pre.generate_kfrags(delegating_privkey=delegating_privkey, signer=signer, receiving_pubkey=pub_key_bob, threshold=2, N=4, sign_delegating_key=False, sign_receiving_key=False) capsule.set_correctness_keys(delegating_privkey.get_pubkey(), pub_key_bob, signing_pubkey) ursula_pubkey = ursula.stamp.as_umbral_pubkey() alice_address = canonical_address_from_umbral_key(signing_pubkey) blockhash = bytes(32) specification = b''.join((bytes(capsule), bytes(ursula_pubkey), bytes(ursula.decentralized_identity_evidence), alice_address, blockhash)) bobs_signer = Signer(priv_key_bob) task_signature = bytes(bobs_signer(specification)) metadata = bytes(ursula.stamp(task_signature)) cfrag = pre.reencrypt(kfrags[0], capsule, metadata=metadata) if corrupt_cfrag: cfrag.proof.bn_sig = CurveBN.gen_rand(capsule.params.curve) cfrag_signature = bytes(ursula.stamp(bytes(cfrag))) bob = Bob.from_public_keys(verifying_key=pub_key_bob) task = WorkOrder.Task(capsule, task_signature, cfrag, cfrag_signature) work_order = WorkOrder(bob, None, alice_address, [task], None, ursula, blockhash) evidence = IndisputableEvidence(task, work_order) return evidence
def from_rest_payload(cls, arrangement_id, rest_payload): payload_splitter = BytestringSplitter(Signature) + key_splitter signature, bob_pubkey_sig, \ (receipt_bytes, packed_capsules, packed_signatures) = payload_splitter(rest_payload, msgpack_remainder=True) capsules, capsule_signatures = list(), list() for capsule_bytes, signed_capsule in zip(msgpack.loads(packed_capsules), msgpack.loads(packed_signatures)): capsules.append(Capsule.from_bytes(capsule_bytes, params=default_params())) signed_capsule = Signature.from_bytes(signed_capsule) capsule_signatures.append(signed_capsule) if not signed_capsule.verify(capsule_bytes, bob_pubkey_sig): raise ValueError("This doesn't appear to be from Bob.") verified = signature.verify(receipt_bytes, bob_pubkey_sig) if not verified: raise ValueError("This doesn't appear to be from Bob.") bob = Bob.from_public_keys({SigningPower: bob_pubkey_sig}) return cls(bob, arrangement_id, capsules, capsule_signatures, receipt_bytes, signature)
def from_rest_payload(cls, arrangement_id, rest_payload, ursula, alice_address): payload_splitter = BytestringSplitter(Signature) + key_splitter payload_elements = payload_splitter(rest_payload, msgpack_remainder=True) signature, bob_verifying_key, (tasks_bytes, blockhash) = payload_elements # TODO: check freshness of blockhash? ursula_identity_evidence = b'' if ursula._stamp_has_valid_signature_by_worker(): ursula_identity_evidence = ursula.decentralized_identity_evidence tasks = [] for task_bytes in tasks_bytes: task = cls.PRETask.from_bytes(task_bytes) tasks.append(task) # Each task signature has to match the original specification specification = task.get_specification(ursula.stamp, alice_address, blockhash, ursula_identity_evidence) if not task.signature.verify(specification, bob_verifying_key): raise InvalidSignature() # Check receipt receipt_bytes = b"wo:" + bytes(ursula.stamp) + keccak_digest( *[bytes(task.capsule) for task in tasks]) if not signature.verify(receipt_bytes, bob_verifying_key): raise InvalidSignature() bob = Bob.from_public_keys(verifying_key=bob_verifying_key) return cls(bob=bob, ursula=ursula, arrangement_id=arrangement_id, tasks=tasks, alice_address=alice_address, blockhash=blockhash, receipt_signature=signature)
def from_rest_payload(cls, arrangement_id, rest_payload, ursula, alice_address): payload_splitter = BytestringSplitter( Signature) + key_splitter + BytestringSplitter( ETH_HASH_BYTE_LENGTH) signature, bob_verifying_key, blockhash, remainder = payload_splitter( rest_payload, return_remainder=True) tasks = { capsule: cls.PRETask(capsule, sig) for capsule, sig in cls.PRETask.input_splitter.repeat(remainder) } # TODO: check freshness of blockhash? #259 ursula_identity_evidence = b'' if ursula._stamp_has_valid_signature_by_worker(): ursula_identity_evidence = ursula.decentralized_identity_evidence for task in tasks.values(): # Each task signature has to match the original specification specification = task.get_specification(ursula.stamp, alice_address, blockhash, ursula_identity_evidence) if not task.signature.verify(specification, bob_verifying_key): raise InvalidSignature() # Check receipt capsules = b''.join(map(bytes, tasks.keys())) receipt_bytes = cls.HEADER + bytes(ursula.stamp) + capsules if not signature.verify(receipt_bytes, bob_verifying_key): raise InvalidSignature() bob = Bob.from_public_keys(verifying_key=bob_verifying_key) return cls(bob=bob, ursula=ursula, arrangement_id=arrangement_id, tasks=tasks, alice_address=alice_address, blockhash=blockhash, receipt_signature=signature)
def share_data_access(self, pubkeys, label, days=5, m=1, n=1, rate=Web3.toWei(50, 'gwei')): """ Share data access based on public keys Args: pubkeys (dict): public keys dict containing sig and enc keys label (bytes): label for the policy days (int): days for which the access should be granted m (int): Minimum number of kfrags needed to activate a Capsule n (int): Total number of kfrags to generate rate (int): rate in wei Returns: policy_info (dict): dict containing policy_pubkey, alice_sig_pubkey and label keys """ bob = Bob.from_public_keys(verifying_key=pubkeys['sig'], encrypting_key=pubkeys['enc'], federated_only=self.federated_only) # Policy expiration date policy_end_datetime = maya.now() + datetime.timedelta(days=days) power_ups = self.alice._crypto_power._CryptoPower__power_ups for key, power_up in power_ups.items(): self.alice._crypto_power.consume_power_up( power_up, password=self.__client_password) policy = self.alice.grant(bob=bob, label=label, m=m, n=n, expiration=policy_end_datetime, rate=rate) policy_info = { "policy_pubkey": policy.public_key.to_bytes().hex(), "alice_sig_pubkey": bytes(self.alice.stamp).hex(), "label": label.decode("utf-8"), } return policy_info
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 grant(self, username, password, account, bob_username, label): self.Alice = self.alice_from_configutation(username, password, account) powers_and_material = self.calculate_powers(bob_username) bob = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=365) encoded_label = label.encode("utf-8") self.Alice.start_learning_loop(now=True) policy = self.Alice.grant(bob, encoded_label, m=1, n=1, expiration=policy_end_datetime) alices_pubkey = bytes(self.Alice.stamp) policy_info = { "policy_pubkey" : policy.public_key.to_bytes().hex(), "alice_sig_pubkey": base58.b58encode(alices_pubkey).decode("utf-8"), "label" : encoded_label.decode("utf-8") } return policy_info
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)
def creat_nucid(alice, cid, enc_pubkey, sig_pubkey, label): powers_and_material = { DecryptingPower: enc_pubkey, SigningPower: sig_pubkey } doctor_strange = Bob.from_public_keys(powers_and_material=powers_and_material, federated_only=True) policy_end_datetime = maya.now() + datetime.timedelta(days=5) # m, n = 1, 2 m, n = 2, 3 print(doctor_strange, label, m, n, policy_end_datetime) print(alice) policy = alice.grant(bob=doctor_strange, label=label, m=m, n=n, expiration=policy_end_datetime) policy_info = { "policy_pubkey": base58.b58encode(policy.public_key.to_bytes()).decode("utf-8"), "alice_sig_pubkey": base58.b58encode(bytes(alice.stamp)).decode("utf-8"), "label": label.decode("utf-8"), } store_url = "%s_%s_%s_%s"%(cid, base58.b58encode(policy.public_key.to_bytes()).decode("utf-8"), base58.b58encode(bytes(alice.stamp)).decode("utf-8"), label.decode("utf-8")) store_url = "nucid://" + store_url return store_url