Example #1
0
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()
Example #2
0
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)
Example #3
0
    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 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?
Example #6
0
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
Example #7
0
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")
Example #8
0
# 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.
##########
# 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."
Example #10
0
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,
Example #11
0
                                         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)
    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)
# 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)
Example #14
0
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
Example #15
0
######################################

# 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,
# 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)