コード例 #1
0
def initialize_bob(bob_privkeys):
    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI,
                                             federated_only=True,
                                             minimum_stake=0)
    TEMP_DOCTOR_DIR = "{}/listener-files".format(
        os.path.dirname(os.path.abspath(__file__)))

    # Remove previous demo files and create new ones
    shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)

    bob_enc_keypair = DecryptingKeypair(private_key=bob_privkeys["enc"])
    bob_sig_keypair = SigningKeypair(private_key=bob_privkeys["sig"])
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Listener ...")

    listener = Bob(
        domains={TEMPORARY_DOMAIN},
        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(),
    )

    print("Listener = ", listener)
    return listener
コード例 #2
0
 def act_as_bob(self, name):
     print("act_as_bob")
     dirname = "accounts/" + name + "/"
     fname = dirname+"recipent.private.json"
     with open(fname) as data_file:    
         data = json.load(data_file)
     enc_privkey = UmbralPrivateKey.from_bytes(bytes.fromhex(data["enc"]))
     sig_privkey = UmbralPrivateKey.from_bytes(bytes.fromhex(data["sig"]))
     
     bob_enc_keypair = DecryptingKeypair(private_key=enc_privkey)
     bob_sig_keypair = SigningKeypair(private_key=sig_privkey)
     enc_power = DecryptingPower(keypair=bob_enc_keypair)
     sig_power = SigningPower(keypair=bob_sig_keypair)
     power_ups = [enc_power, sig_power]
     bob = Bob(
         is_me=True,
         federated_only=True,
         crypto_power_ups=power_ups,
         start_learning_now=True,
         abort_on_learning_error=True,
         known_nodes=[self.ursula],
         save_metadata=False,
         network_middleware=RestMiddleware(),
     )
     return bob
コード例 #3
0
def generate_charlie():
    shutil.rmtree(TEMP_CHARLIE_DIR, ignore_errors=True)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL,
                                             federated_only=True,
                                             minimum_stake=0)

    # To create a Bob, we need the charlie's private keys previously generated.
    from charlie_keys import get_charlie_privkeys
    charlie_keys = get_charlie_privkeys()

    bob_enc_keypair = DecryptingKeypair(private_key=charlie_keys["enc"])
    bob_sig_keypair = SigningKeypair(private_key=charlie_keys["sig"])
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Charlie ...")

    charlie = 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(),
    )

    print("Charlie = ", charlie)

    # Join policy generated by alice
    with open("policy-metadata.json", 'r') as f:
        policy_data = json.load(f)

    policy_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["policy_pubkey"]))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["alice_sig_pubkey"]))
    label = policy_data["label"].encode()

    print("The Charlie joins policy for label '{}'".format(
        label.decode("utf-8")))
    charlie.join_policy(label, alices_sig_pubkey)

    return charlie, policy_pubkey, alices_sig_pubkey, label
コード例 #4
0
    def downloadFile(self, username, receipt, policy_info):
        hash = receipt['hash_key']
        input = self.ipfs_gateway_api.cat(hash)

        enc_privkey, sig_privkey = self.reveal_private_keys(username)

        bob_enc_key = DecryptingKeypair(private_key=enc_privkey)
        bob_sig_keyp = SigningKeypair(private_key=sig_privkey)
        enc_power = DecryptingPower(keypair=bob_enc_key)
        sig_power = SigningPower(keypair=bob_sig_keyp)
        power_ups = [enc_power, sig_power]

        self.Bob = Bob(
            federated_only=True,
            crypto_power_ups=power_ups,
            start_learning_now=True,
            abort_on_learning_error=True,
            known_nodes=[self.ursula], 
            save_metadata=False,
            network_middleware=RestMiddleware(),
        )

        policy_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(policy_info["policy_pubkey"]))

        enrico = Enrico.from_public_keys(
            {SigningPower: UmbralPublicKey.from_bytes(bytes.fromhex(receipt['data_source_public_key']))},
            policy_encrypting_key=policy_pubkey
        )
        alice_pubkey_restored = UmbralPublicKey.from_bytes(base58.b58decode(policy_info['alice_sig_pubkey']))
        self.Bob.join_policy(policy_info['label'].encode(), alice_pubkey_restored)

        data = msgpack.loads(input, raw=False)
        message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])
        message_kit = next(message_kits)

        retrieved_plaintexts = self.Bob.retrieve(
            message_kit,
            enrico=enrico,
            alice_verifying_key=alice_pubkey_restored,
            label=policy_info['label'].encode(),
        )

        plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)
        print(plaintext)
        decrypted_data = plaintext['data']
        return decrypted_data
コード例 #5
0
ファイル: doctor.py プロジェクト: chaoticx-org/nucypher
# Remove previous demo files and create new ones
shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)

ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI,
                                         federated_only=True,
                                         minimum_stake=0)

# To create a Bob, we need the doctor's private keys previously generated.
from doctor_keys import get_doctor_privkeys

doctor_keys = get_doctor_privkeys()

bob_enc_keypair = DecryptingKeypair(private_key=doctor_keys["enc"])
bob_sig_keypair = SigningKeypair(private_key=doctor_keys["sig"])
enc_power = DecryptingPower(keypair=bob_enc_keypair)
sig_power = SigningPower(keypair=bob_sig_keypair)
power_ups = [enc_power, sig_power]

print("Creating the Doctor ...")

doctor = Bob(
    domain=TEMPORARY_DOMAIN,
    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(),
)
コード例 #6
0
def decryptDelegated():
    # Fetch Request Data
    # {
    #     "bobKeys": "{\"enc\": \"40f05590a27491caf37049366fefd43e46034e4308f4f1fd233c166bc3980ab4\", \"sig\": \"3bcf21d3cb160118b499a883023569c60476f8731bd9eade11016c5030c1ca5d\"}",
    #     "policy_public_key": "02aef01b40c0a62a9a1f650dd9a8381695e21a7b3826c748a5b64831aa0dd9862c",
    #     "alice_sig_pubkey": "036c5d361000e6fbf3c4a84c98f924a3206e8a72c758a67e8300b5bee111b5fa97",
    #     "label": "1stlabel",
    #     "message": "messagekit",
    #     "data_source": "03a38eef9fd09c9841585dea93791e139a3003d540539673c8c719af55e46c0c1b",
    # }
    json_data = json.loads(request.data.decode('utf-8'))
    bob_private_keys = json.loads(json_data['bobKeys'])
    policy_public_key = json_data['policy_public_key']
    alice_signing_key = json_data['alice_sig_pubkey']
    label = json_data['label']

    # username = json_data['username']

    message = json_data['message']
    data_source = json_data['data_source']

    data_source = bytes.fromhex(data_source)
    print (bob_private_keys['enc'])

    enc = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["enc"]))
    sig = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["sig"]))

    # signingPublic = sig.get_pubkey()
    # bobFilePath = os.path.join(os.getcwd(), 'bob/' + username + '.json')
    # doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey)
    # print (signingPublic == doctor_pubkeys['sig'])
    # print (signingPublic)
    # print (doctor_pubkeys['sig'])
    print ('\n\n\n')

    bob_enc_keypair = DecryptingKeypair(private_key=enc)
    bob_sig_keypair = SigningKeypair(private_key=sig)

    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    doctor = Bob(
        domains={'TEMPORARY_DOMAIN'},
        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_public_key))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(alice_signing_key))
    label = label.encode()

    doctor.join_policy(label, alices_sig_pubkey)

    message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(message))

    print (message_kit == MessageKit)
    print (message_kit)
    print (MessageKit)
    print ('\n\n\n')

    data_source = Enrico.from_public_keys(
        {SigningPower: data_source},
        policy_encrypting_key=policy_pubkey
    )

    retrieved_plaintexts = doctor.retrieve(
        label=label,
        message_kit=message_kit,
        data_source=data_source,
        alice_verifying_key=alices_sig_pubkey
    )

    # the object to be sent back to front end

    # {
    #     "fileFieldCount": 2,
    #     "textFieldCount": 2,
    #     "files  (stringified)": {
    #         "fileKey1": "fileUrl1",
    #         "fileKey2": "fileUrl2"
    #     },
    #     "textFields (stringified)": {
    #         "age": "18",
    #         "name": "arvind"
    #     }
    #  }

    plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

    # the object from plaintext
    data_obj = createDataObject(plaintext, json_data['label'])


    return jsonify(data_obj)
コード例 #7
0
ファイル: zkdonation.py プロジェクト: izrake/PWPEvents
def createBobToResolveData(sub_uuid, sender, event_uuid, sub_private_key,
                           sub_signer_key, policy_pub_key, policy_sign_key,
                           label):
    SEEDNODE_URI = "127.0.0.1:10151"
    # TODO: path joins?
    TEMP_DOCTOR_DIR = "{}/doctor-files".format(
        os.path.dirname(os.path.abspath(__file__)))

    # Remove previous demo files and create new ones
    shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI,
                                             federated_only=True,
                                             minimum_stake=0)
    # doctor private key

    encdoctor = UmbralPrivateKey.from_bytes(bytes.fromhex(sub_private_key))
    signdoctor = UmbralPrivateKey.from_bytes(bytes.fromhex(sub_signer_key))

    bob_enc_keypair = DecryptingKeypair(private_key=encdoctor)
    bob_sig_keypair = SigningKeypair(private_key=signdoctor)
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Doctor ...")

    doctor = Bob(
        domains={TEMPORARY_DOMAIN},
        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(),
    )

    print("Doctor = ", doctor)

    policy_pub_keys = UmbralPublicKey.from_bytes(bytes.fromhex(policy_pub_key))
    policy_sign_keys = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_sign_key))
    label = label.encode()

    print("The Doctor joins policy for label '{}'".format(
        label.decode("utf-8")))
    doctor.join_policy(label, policy_sign_keys)

    data = msgpack.load(open(event_uuid + ".msgpack", "rb"), raw=False)
    message_kits = UmbralMessageKit.from_bytes(data['data'])
    data_source = Enrico.from_public_keys(
        verifying_key=data['data_source'],
        policy_encrypting_key=policy_pub_keys)

    try:
        retrieved_plaintexts = doctor.retrieve(
            message_kits,
            label=label,
            enrico=data_source,
            alice_verifying_key=policy_sign_keys)

        plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

        # Now we can get the heart rate and the associated timestamp,
        # generated by the heart rate monitor.
        location_decrypted = plaintext['data_enc']
        print(location_decrypted)
    except Exception as e:
        # We just want to know what went wrong and continue the demo
        traceback.print_exc()

    return location_decrypted
コード例 #8
0
def decryptDelegated():

    json_data = json.loads(request.data.decode('utf-8'))
    bob_private_keys = json.loads(json_data['bobKeys'])
    policy_public_key = json_data['policy_public_key']
    alice_signing_key = json_data['alice_sig_pubkey']
    label = json_data['label']

    # username = json_data['username']

    message = json_data['message']
    data_source = json_data['data_source']

    data_source = bytes.fromhex(data_source)
    print (bob_private_keys['enc'])

    enc = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["enc"]))
    sig = UmbralPrivateKey.from_bytes(bytes.fromhex(bob_private_keys["sig"]))

    # signingPublic = sig.get_pubkey()
    # bobFilePath = os.path.join(os.getcwd(), 'bob/' + username + '.json')
    # doctor_pubkeys = _get_keys(bobFilePath, UmbralPublicKey)
    # print (signingPublic == doctor_pubkeys['sig'])
    # print (signingPublic)
    # print (doctor_pubkeys['sig'])
    print ('\n\n\n')

    bob_enc_keypair = DecryptingKeypair(private_key=enc)
    bob_sig_keypair = SigningKeypair(private_key=sig)

    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    doctor = Bob(
        domains={'TEMPORARY_DOMAIN'},
        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_public_key))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(bytes.fromhex(alice_signing_key))
    label = label.encode()

    doctor.join_policy(label, alices_sig_pubkey)

    message_kit = UmbralMessageKit.from_bytes(bytes.fromhex(message))

    print (message_kit == MessageKit)
    print (message_kit)
    print (MessageKit)
    print ('\n\n\n')

    data_source = Enrico.from_public_keys(
        {SigningPower: data_source},
        policy_encrypting_key=policy_pubkey
    )

    retrieved_plaintexts = doctor.retrieve(
        label=label,
        message_kit=message_kit,
        data_source=data_source,
        alice_verifying_key=alices_sig_pubkey
    )

    # the object to be sent back to front end

    # {
    #     "fileFieldCount": 2,
    #     "textFieldCount": 2,
    #     "files  (stringified)": {
    #         "fileKey1": "fileUrl1",
    #         "fileKey2": "fileUrl2"
    #     },
    #     "textFields (stringified)": {
    #         "age": "18",
    #         "name": "arvind"
    #     }
    #  }

    plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

    # the object from plaintext
    # data_obj = createDataObject(plaintext, json_data['label'])

    return jsonify(plaintext)
コード例 #9
0
ファイル: doctor.py プロジェクト: SagarKishore-PFM/Stridon
def run_doc():

    globalLogPublisher.addObserver(SimpleObserver())

    ######################
    # Boring setup stuff #
    ######################

    SEEDNODE_URL = 'localhost:11501'

    # TODO: path joins?
    TEMP_DOCTOR_DIR = "{}/doctor-files".format(
        os.path.dirname(os.path.abspath(__file__)))

    # Remove previous demo files and create new ones
    shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL,
                                             federated_only=True,
                                             minimum_stake=0)

    # To create a Bob, we need the doctor's private keys previously generated.

    doctor_keys = get_doctor_privkeys()

    bob_enc_keypair = DecryptingKeypair(private_key=doctor_keys["enc"])
    bob_sig_keypair = SigningKeypair(private_key=doctor_keys["sig"])
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Doctor ...")

    doctor = 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(),
    )

    print("Doctor = ", doctor)

    # Let's join the policy generated by Alicia. We just need some info about it.
    with open("policy-metadata.json", 'r') as f:
        policy_data = json.load(f)

    policy_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["policy_pubkey"]))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["alice_sig_pubkey"]))
    label = policy_data["label"].encode()

    print("The Doctor joins policy for label '{}'".format(
        label.decode("utf-8")))
    doctor.join_policy(label, alices_sig_pubkey)

    # Now that the Doctor joined the policy in the NuCypher network,
    # he can retrieve encrypted data which he can decrypt with his private key.
    # But first we need some encrypted data!
    # Let's read the file produced by the heart monitor and unpack the MessageKits,
    # which are the individual ciphertexts.
    data = msgpack.load(open("heart_data.msgpack", "rb"), raw=False)
    message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

    # The doctor also needs to create a view of the Data Source from its public keys
    data_source = Enrico.from_public_keys({SigningPower: data['data_source']},
                                          policy_encrypting_key=policy_pubkey)

    # Now he can ask the NuCypher network to get a re-encrypted version of each MessageKit.
    for message_kit in message_kits:
        try:
            start = timer()
            retrieved_plaintexts = doctor.retrieve(
                label=label,
                message_kit=message_kit,
                data_source=data_source,
                alice_verifying_key=alices_sig_pubkey)
            end = timer()

            plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)

            # Now we can get the heart rate and the associated timestamp,
            # generated by the heart rate monitor.
            heart_rate = plaintext['heart_rate']
            timestamp = maya.MayaDT(plaintext['timestamp'])

            # This code block simply pretty prints the heart rate info
            terminal_size = shutil.get_terminal_size().columns
            max_width = min(terminal_size, 120)
            columns = max_width - 12 - 27
            scale = columns / 40
            scaled_heart_rate = int(scale * (heart_rate - 60))
            retrieval_time = "Retrieval time: {:8.2f} ms".format(1000 *
                                                                 (end - start))
            line = ("-" * scaled_heart_rate) + "❤︎ ({} BPM)".format(heart_rate)
            line = line.ljust(max_width - 27, " ") + retrieval_time
            print(line)
        except Exception as e:
            # We just want to know what went wrong and continue the demo
            traceback.print_exc()
コード例 #10
0
ファイル: doctor.py プロジェクト: manishvishnoi2/MedBlock
def doctor_decrypt(hash_key):
    globalLogPublisher.addObserver(SimpleObserver())
    SEEDNODE_URL = 'localhost:11501'

    TEMP_DOCTOR_DIR = "{}/doctor-files".format(
        os.path.dirname(os.path.abspath(__file__)))
    shutil.rmtree(TEMP_DOCTOR_DIR, ignore_errors=True)

    ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URL,
                                             federated_only=True,
                                             minimum_stake=0)

    from doctor_keys import get_doctor_privkeys

    doctor_keys = get_doctor_privkeys()

    bob_enc_keypair = DecryptingKeypair(private_key=doctor_keys["enc"])
    bob_sig_keypair = SigningKeypair(private_key=doctor_keys["sig"])
    enc_power = DecryptingPower(keypair=bob_enc_keypair)
    sig_power = SigningPower(keypair=bob_sig_keypair)
    power_ups = [enc_power, sig_power]

    print("Creating the Doctor ...")

    doctor = 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(),
    )

    print("Doctor = ", doctor)

    with open("policy-metadata.json", 'r') as f:
        policy_data = json.load(f)

    policy_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["policy_pubkey"]))
    alices_sig_pubkey = UmbralPublicKey.from_bytes(
        bytes.fromhex(policy_data["alice_sig_pubkey"]))
    label = policy_data["label"].encode()

    print("The Doctor joins policy for label '{}'".format(
        label.decode("utf-8")))
    doctor.join_policy(label, alices_sig_pubkey)

    ipfs_api = ipfsapi.connect()
    file = ipfs_api.get(hash_key)
    print(file)
    os.rename(hash_key, 'patient_details.msgpack')
    data = msgpack.load(open("patient_details.msgpack", "rb"), raw=False)
    message_kits = (UmbralMessageKit.from_bytes(k) for k in data['kits'])

    data_source = DataSource.from_public_keys(
        policy_public_key=policy_pubkey,
        datasource_public_key=data['data_source'],
        label=label)
    complete_message = []
    for message_kit in message_kits:
        print(message_kit)
        try:
            start = timer()
            retrieved_plaintexts = doctor.retrieve(
                message_kit=message_kit,
                data_source=data_source,
                alice_verifying_key=alices_sig_pubkey)
            end = timer()
            plaintext = msgpack.loads(retrieved_plaintexts[0], raw=False)
            complete_message.append(plaintext)
            print(plaintext)
            #with open("details.json", "w") as write_file:
            #               json.dump(plaintext, write_file)
        except Exception as e:
            traceback.print_exc()
    with open("details.json", "w") as write_file:
        json.dump(complete_message, write_file)
    return complete_message
コード例 #11
0
ファイル: nucypher_kms.py プロジェクト: viraja1/nucypher_kms
 def __init__(self,
              ursula_url,
              dir_name,
              passphrase,
              ipfs_addr='',
              arweave_wallet_file_path='',
              federated_only=True,
              signer_uri='',
              checksum_address=None,
              client_password=None,
              provider_uri='',
              domain=TEMPORARY_DOMAIN):
     """
     Args:
         ursula_url (str): ursula url e.g. localhost:11500
         dir_name (str): dir_name where account files will be stored in tmp directory
         passphrase (str): passphrase for account
         ipfs_addr (str): ipfs addr (required only if you want to store data in ipfs)
         arweave_wallet_file_path (str): arweave wallet file path (required only if you want to store
                                         data in arweave)
         federated_only (bool): Whether federated mode should be used
         signer_uri (str): signer uri for ethereum transaction
                         https://docs.nucypher.com/en/latest/guides/ethereum_node.html#external-transaction-signing
         checksum_address (str): Ethereum address
         client_password (str): Password for ethereum keystore. Required only if signer_uri is keystore://{path}
         provider_uri (str): geth or infura https uri
         domain (str): nucypher network name e.g. lynx for nucypher testnet and mainnet for nucypher mainnet
     """
     self.__client_password = client_password
     self.federated_only = federated_only
     self.ursula_url = ursula_url
     self.ursula = Ursula.from_seed_and_stake_info(
         seed_uri=self.ursula_url,
         federated_only=self.federated_only,
         minimum_stake=0)
     self.arweave_wallet = None
     if arweave_wallet_file_path:
         self.arweave_wallet = arweave.Wallet(arweave_wallet_file_path)
     self.ipfs = None
     if ipfs_addr:
         self.ipfs = ipfshttpclient.connect(ipfs_addr)
     self.temp_dir = os.path.join('/', 'tmp', dir_name)
     self.alice_config = AliceConfiguration(
         provider_uri=provider_uri,
         checksum_address=checksum_address,
         signer_uri=signer_uri,
         config_root=os.path.join(self.temp_dir),
         domain=domain,
         known_nodes={self.ursula},
         start_learning_now=False,
         federated_only=self.federated_only,
         learn_on_same_thread=True)
     try:
         if os.path.exists(os.path.join(self.temp_dir, "alice.json")):
             raise ExistingKeyringError()
         self.alice_config.initialize(password=passphrase)
     except ExistingKeyringError:
         self.alice_config = AliceConfiguration.from_configuration_file(
             filepath=os.path.join(self.temp_dir, "alice.json"),
             known_nodes={self.ursula},
             start_learning_now=False)
         self.alice_config.attach_keyring()
     self.alice_config.keyring.unlock(password=passphrase)
     signer = Signer.from_signer_uri(signer_uri) if signer_uri else None
     if signer:
         signer.unlock_account(account=checksum_address,
                               password=client_password)
     self.alice = self.alice_config.produce(signer=signer)
     try:
         self.alice_config_file = self.alice_config.to_configuration_file()
     except FileExistsError:
         pass
     self.alice.start_learning_loop(now=True)
     self.privkeys, self.pubkeys = fetch_keys(path=self.temp_dir)
     bob_enc_keypair = DecryptingKeypair(private_key=self.privkeys["enc"])
     bob_sig_keypair = SigningKeypair(private_key=self.privkeys["sig"])
     enc_power = DecryptingPower(keypair=bob_enc_keypair)
     sig_power = SigningPower(keypair=bob_sig_keypair)
     power_ups = [enc_power, sig_power]
     self.bob = Bob(domain=domain,
                    federated_only=self.federated_only,
                    crypto_power_ups=power_ups,
                    start_learning_now=True,
                    abort_on_learning_error=True,
                    known_nodes=[self.ursula],
                    save_metadata=False,
                    network_middleware=RestMiddleware(),
                    provider_uri=provider_uri)
コード例 #12
0
ファイル: client.py プロジェクト: Chientze/nucypher-ipfs
    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()