Merge branch 'development' into 3161-undefined-name-errors

pull/3162/head
Owen Campbell 2023-06-29 09:44:45 +01:00
commit fa389cb54c
No known key found for this signature in database
GPG Key ID: 628F79BCBE9C2B73
2 changed files with 63 additions and 82 deletions

View File

View File

@ -1,14 +1,14 @@
# Run nucypher dkg by running:
# Run nucypher dkg on 'lynx'/'mumbai' by running:
#
# python scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> <RITUAL_ID> <NETWORK> <SIGNER_URI>
# python scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> <COORDINATOR_PROVIDER_URI> <RITUAL_ID> <SIGNER_URI_FOR_COORDINATOR_NETWORK>
#
# For example:
#
# Use existing ritual id (eg. id '0'):
# python ./scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> 0 lynx
# python ./scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> <COORDINATOR_PROVIDER_URI> 0
#
# Go through entire process of initiating a ritual, waiting for it to finish, then use for encryption/decryption:
# python ./scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> -1 lynx <SIGNER_URI>
# python ./scripts/hooks/nucypher_dkg.py <ETH_PROVIDER_URI> <COORDINATOR_PROVIDER_URI> -1 <SIGNER_URI_FOR_COORDINATOR_NETWORK>
#
import random
@ -16,7 +16,6 @@ import sys
import time
import click
from constant_sorrow.constants import NO_BLOCKCHAIN_CONNECTION
from nucypher_core.ferveo import DkgPublicKey
from web3 import Web3
@ -25,97 +24,82 @@ from nucypher.blockchain.eth.agents import (
CoordinatorAgent,
PREApplicationAgent,
)
from nucypher.blockchain.eth.interfaces import BlockchainInterfaceFactory
from nucypher.blockchain.eth.registry import (
BaseContractRegistry,
GithubRegistrySource,
InMemoryContractRegistry,
RegistrySourceManager,
)
from nucypher.blockchain.eth.registry import InMemoryContractRegistry
from nucypher.blockchain.eth.signers import Signer
from nucypher.characters.lawful import Bob, Enrico, Ursula
from nucypher.characters.lawful import Bob, Enrico
from nucypher.crypto.powers import TransactingPower
from nucypher.policy.conditions.lingo import ConditionLingo
from nucypher.utilities.emitters import StdoutEmitter
from nucypher.utilities.logging import GlobalLoggerSettings
NO_BLOCKCHAIN_CONNECTION.bool_value(False) # FIXME
GlobalLoggerSettings.start_console_logging()
emitter = StdoutEmitter(verbosity=2)
class TDecGithubRegistrySource(GithubRegistrySource):
def get_publication_endpoint(self) -> str:
url = f"{self._BASE_URL}/tdec/nucypher/blockchain/eth/contract_registry/{self.network}/{self.registry_name}"
return url
try:
eth_provider_uri = sys.argv[1]
except IndexError:
emitter.message("You have to pass a provider URI", color="red")
emitter.message("You must provide a eth (staking) provider URI", color="red")
sys.exit(-1)
try:
ritual_id = int(sys.argv[2])
if ritual_id == -1:
ritual_id = None
coordinator_provider_uri = sys.argv[2]
except IndexError:
ritual_id = None
emitter.message("You must provide a coordinator network provider URI", color="red")
sys.exit(-1)
try:
ritual_id = int(sys.argv[3])
except IndexError:
emitter.message(
"You must provide a ritual ID; expected <id> or -1 (to initiate a new ritual)",
color="red",
)
sys.exit(-1)
try:
signer_uri = sys.argv[4]
except IndexError:
if ritual_id is None:
if ritual_id < 0:
emitter.message(
"You must provide an account signer URI for new ritual transactions if not reusing a ritual id",
"You must provide a signer URI for new ritual transactions if not reusing an existing ritual id",
color="red",
)
sys.exit(-1)
signer_uri = None
try:
network = sys.argv[3]
except IndexError:
network = "lynx"
staking_network = "lynx"
coordinator_network = "mumbai"
BlockchainInterfaceFactory.initialize_interface(
eth_provider_uri=eth_provider_uri, light=False, emitter=emitter
)
blockchain = BlockchainInterfaceFactory.get_interface(eth_provider_uri=eth_provider_uri)
emitter.echo(message="Reading Latest Chaindata...")
blockchain.connect()
github_source = TDecGithubRegistrySource(
network=network, registry_name=BaseContractRegistry.REGISTRY_NAME
)
source_manager = RegistrySourceManager(sources=[github_source])
registry = InMemoryContractRegistry.from_latest_publication(
source_manager=source_manager, network=network
)
emitter.echo(f"NOTICE: Connecting to {network} network", color="yellow")
application_agent = ContractAgency.get_agent(
agent_class=PREApplicationAgent, registry=registry
) # type: PREApplicationAgent
coordinator_agent = ContractAgency.get_agent(
agent_class=CoordinatorAgent, registry=registry
agent_class=CoordinatorAgent,
registry=InMemoryContractRegistry.from_latest_publication(
network=coordinator_network
),
provider_uri=coordinator_provider_uri,
) # type: CoordinatorAgent
staking_network_registry = InMemoryContractRegistry.from_latest_publication(
network=staking_network
)
application_agent = ContractAgency.get_agent(
agent_class=PREApplicationAgent,
registry=staking_network_registry,
provider_uri=eth_provider_uri,
) # type: PREApplicationAgent
#
# Initial Ritual
#
# must be a power of 2
if ritual_id is None:
emitter.echo("--------- Initiating Ritual ---------")
if ritual_id < 0:
emitter.echo("--------- Initiating Ritual ---------", color="yellow")
# create account from keystore file
signer = Signer.from_signer_uri(uri=signer_uri)
account_address = signer.accounts[0]
emitter.echo(f"Using account {account_address}", color="green")
emitter.echo(
f"Using account {account_address} to initiate DKG Ritual", color="green"
)
password = click.prompt(
"Enter your keystore password", confirmation_prompt=False, hide_input=True
@ -124,7 +108,7 @@ if ritual_id is None:
transacting_power = TransactingPower(signer=signer, account=account_address)
emitter.echo(
f"Ready to commence DKG Ritual on {network} using {account_address}",
f"Commencing DKG Ritual on {coordinator_network} using {account_address}",
color="green",
)
@ -133,7 +117,7 @@ if ritual_id is None:
staking_providers = list(staking_providers_dict.keys())
staking_providers.remove(
"0x7AFDa7e47055CDc597872CA34f9FE75bD083D0Fe"
) # TODO why is this address active? It doesn't have a running node
) # TODO skip Bogdan's node; remove at some point
# sample then sort
dkg_staking_providers = random.sample(staking_providers, 2)
@ -152,7 +136,7 @@ if ritual_id is None:
), "ritual successfully initiated"
emitter.echo(
f"DKG Ritual {ritual_id} initiated: {Web3.to_hex(receipt['transactionHash'])}",
f"DKG Ritual #{ritual_id} initiated: {Web3.to_hex(receipt['transactionHash'])}",
color="green",
)
@ -171,7 +155,7 @@ if ritual_id is None:
ritual_status == coordinator_agent.Ritual.Status.TIMEOUT
or ritual_status == coordinator_agent.Ritual.Status.INVALID
):
emitter.error(f"Ritual {ritual_id} failed with status {ritual_status}")
emitter.error(f"Ritual #{ritual_id} failed with status {ritual_status}")
sys.exit(-1)
emitter.echo(
@ -180,11 +164,12 @@ if ritual_id is None:
time.sleep(10)
emitter.echo(
f"DKG Ritual ended with status {ritual_status} after {time.time() - start_time}s"
f"DKG Ritual #{ritual_id} completed after {time.time() - start_time}s",
color="green",
)
else:
ritual = coordinator_agent.get_ritual(ritual_id) # ensure ritual can be found
emitter.echo(f"Reusing existing DKG Ritual {ritual_id}", color="green")
emitter.echo(f"Reusing existing DKG Ritual #{ritual_id}", color="green")
#
# Encrypt some data
@ -192,8 +177,11 @@ else:
emitter.echo("--------- Data Encryption ---------")
PLAINTEXT = """
Those who mistake the unessential to be essential and the essential to be unessential, dwelling in wrong thoughts, never arrive at the essential.
Those who know the essential to be essential and the unessential to be unessential, dwelling in right thoughts, do arrive at the essential.
Those who mistake the unessential to be essential and the essential to be unessential,
dwelling in wrong thoughts, never arrive at the essential.
Those who know the essential to be essential and the unessential to be unessential,
dwelling in right thoughts, do arrive at the essential.
"""
# -- Dhammapada
@ -202,18 +190,18 @@ CONDITIONS = {
"condition": {
"returnValueTest": {"value": "0", "comparator": ">"},
"method": "blocktime",
"chain": blockchain.client.chain_id,
"chain": application_agent.blockchain.client.chain_id,
},
}
encrypting_key = DkgPublicKey.from_bytes(
coordinator_agent.get_ritual(ritual_id).public_key
bytes(coordinator_agent.get_ritual(ritual_id).public_key)
)
enrico = Enrico(encrypting_key=encrypting_key)
ciphertext = enrico.encrypt_for_dkg(plaintext=PLAINTEXT.encode(), conditions=CONDITIONS)
emitter.echo("Data encrypted", color="green")
emitter.echo("-- Data encrypted --", color="green")
#
# Get Data Decrypted
@ -221,15 +209,10 @@ emitter.echo("Data encrypted", color="green")
emitter.echo("--------- Threshold Decryption ---------")
bob = Bob(
eth_provider_uri=eth_provider_uri,
domain=network,
registry=registry,
known_nodes=[
Ursula.from_teacher_uri(
f"https://{network}.nucypher.network:9151",
provider_uri=eth_provider_uri,
min_stake=0,
)
],
domain=staking_network,
registry=staking_network_registry,
coordinator_network=coordinator_network,
coordinator_provider_uri=coordinator_provider_uri,
)
bob.start_learning_loop(now=True)
@ -237,9 +220,7 @@ cleartext = bob.threshold_decrypt(
ritual_id=ritual_id,
ciphertext=ciphertext,
conditions=CONDITIONS,
# uncomment to use the precomputed variant
# variant=FerveoVariant.PRECOMPUTED.name
)
emitter.echo(f"Data decrypted: \n{bytes(cleartext).decode()}", color="green")
emitter.echo(f"\n-- Data decrypted -- \n{bytes(cleartext).decode()}", color="green")
assert bytes(cleartext).decode() == PLAINTEXT