Esempio n. 1
0
def create_factory():
    """ Create and initialise the factory contract """
    # Deploy the exchange template contract
    exchange_template = deploy_contract(abi=exchange_abi, bytecode=exchange_bc)
    # Get uniswap factory and initialise it
    factory = deploy_contract(abi=factory_abi, bytecode=factory_bc)
    factory.functions.initializeFactory(
        template=Web3.toChecksumAddress(exchange_template.address)).transact()
    return factory
Esempio n. 2
0
def deploy():
    logging.info(f'deploying DKG contract from Ethereum account {account}...')
    logging.info()
    contract, tx = utils.deploy_contract('DKG',
                                         account,
                                         return_tx_receipt=True)
    log_tx(tx, 'deployment transaction confirmed:')
    logging.info(f'contract deployed at: {contract.address}')
def setup_multiple(num_nodes=3, register=False):
    assert num_nodes <= len(w3.eth.accounts), \
        "Each node needs a seperate account, update e.g. Ganache settings for more accounts"

    contract = utils.deploy_contract('DKG')
    nodes = [EthNode(w3.eth.accounts[i]) for i in range(num_nodes)]
    for node in nodes:
        c = utils.get_contract('DKG', contract.address)
        node.keygen()
        node.connect(c)

    if register:
        utils.run([node.register for node in nodes])
        utils.mine_blocks_until(contract.registrations_confirmed)
        utils.run([node.init_secret_sharing for node in nodes])

        # here we actually ensure that we return the nodes ordered by id, for easier tests
        nodes.sort(key=lambda node: node.id)

    return contract, nodes
def test_verification_of_aggregate_signature():
    # generates and verfies a signature under the master key derived for contract
    # 0x64eB9cbc8AAc7723A7A94b178b7Ac4c18D7E6269
    # see ../evaluation/testnet-execution for the transscripts

    master_pk = (
        16185756129160603637125524807239031401829819645832054270709340132395400777397,
        8519501919971397775891715048167089286600326398415030764834336433929153469650,
        18597752777763136713734159587276505878060020022295659236248459536349704859281,
        451510684427994150648572847494629298315616628846799867117722216880750483787
    )

    msg = 'test message'
    msg_hash = hashlib.sha3_256(msg.encode()).digest()

    # ids for the 3 correct nodes A, B, C (assigned durign registration)
    id_A, id_B, id_C = 3, 2, 1

    # group secret keys for the 3 correct nodes A, B and C
    gsk_A = (
        19063102076674778359749742475275688996157982969842615782345982391516317582432
    )
    gsk_B = (
        25409986690480885131491958594328734819629294462429970027081157236075400972958
    )
    gsk_C = (
        48802012483270245949082675044770005030925758437990233282811259804203609665090
    )

    sig_A = bls.sign(gsk_A, msg_hash)
    sig_B = bls.sign(gsk_B, msg_hash)
    sig_C = bls.sign(gsk_C, msg_hash)

    # three signature shares are sufficient to generate a signature which successfully verifies under the master pk
    sig = bls.aggregate([(id_A, sig_A), (id_B, sig_B), (id_C, sig_C)])
    assert bls.verify(master_pk, msg_hash, sig)

    # verify that the signature can also be verified in the smart contract
    contract = utils.deploy_contract('DKG')
    assert contract.verify_signature(master_pk, msg_hash, sig)
Esempio n. 5
0
def initialise_token(token: Token):
    """ Deploy the ERC20 contract, create uniswap exchange, add liquidity

        Returns deployed token_contract
    """
    logger.info(f'Deploying contract for {token.name}')
    token_contract = deploy_contract(abi=ERC20_ABI,
                                     bytecode=ERC20_BC,
                                     constructor_kwargs=dict(
                                         name=token.name,
                                         symbol=token.symbol,
                                         decimals=token.decimals))
    # Mint tokens for the first three accounts
    logger.info(
        f'Minting {token.initial_balance} {token.symbol} for {", ".join([a for a in w3.eth.accounts[:3]])}'
    )
    for address in w3.eth.accounts[:3]:
        token_contract.functions.mint(to=Web3.toChecksumAddress(address),
                                      value=token.initial_balance *
                                      10**token.decimals).transact()

    return token_contract
def test_sharing_non_registered():

    contractA, nodes = setup_multiple(6)
    contractB = utils.deploy_contract('DKG')

    nodesA = nodes[:3]
    nodesB = nodes[3:]
    for b in nodesB:
        b.contract = contractB

    utils.run([node.register for node in nodesA])
    utils.run([node.register for node in nodesB])
    utils.mine_blocks_until(contractA.registrations_confirmed)
    utils.mine_blocks_until(contractB.registrations_confirmed)

    utils.run([node.init_secret_sharing for node in nodesA])
    utils.run([node.init_secret_sharing for node in nodesB])

    bad_node = nodesB[0]
    bad_node.contract = contractA

    with pytest.raises(ValueError, match='.*key sharing failed.*'):
        # bad_node is not registered for contract A, call to contract should therefore fail
        bad_node.share_key()
def run(num_nodes):
    contract = utils.deploy_contract('DKG')
    nodes = [EthNode(w3.eth.accounts[i]) for i in range(num_nodes)]

    tx_register = []
    tx_share_key = []
    tx_dispute = []
    tx_upload = None

    for i, node in enumerate(nodes):
        print(f'setting up node {i + 1}... ', end="", flush=True)
        c = utils.get_contract('DKG', contract.address)
        node.keygen()
        node.connect(c)
        print("done")
    print()

    for i, node in enumerate(nodes):
        print(f'registering node {i + 1}... ', end="", flush=True)
        tx = node.register()
        tx_register.append(tx)
        print("done")
    print()

    print(f'waiting for begin of key sharing phase... ', end='', flush=True)
    utils.mine_blocks_until(contract.registrations_confirmed)
    print('done\n')

    for i, node in enumerate(nodes):
        print(f'init secret sharing for node {i + 1}... ', end="", flush=True)
        node.init_secret_sharing()
        print("done")
    print()

    # invalid the share from last to first node
    # to actually also test the dispute case
    manipulate_share(nodes[-1], 1)

    for node in nodes:
        print(f'distribute key shares for node {node.id}... ', end="", flush=True)
        tx = node.share_key()
        tx_share_key.append(tx)
        print("done")
    print()

    print(f'waiting for begin of dispute phase... ', end='', flush=True)
    utils.mine_blocks_until(contract.sharing_confirmed)
    print('done\n')

    # for node in nodes:
    for node in nodes[:1]:
        print(f'loading and verififying shares for node {node.id}... ', end='', flush=True)
        try:
            node.load_shares()
        except ValueError:
            print("done (invalid share detected)")
        else:
            print("done")
    print()

    # for node in nodes:
    for node in nodes[:1]:
        dispute_ids = [n.id for n in node.nodes if hasattr(n, 'share') and not n.share_ok]
        for id in dispute_ids:
            print(f'submitting dispute from node {node.id} against node {id}... ', end="", flush=False)
            try:
                tx = node.dispute(id)
                tx_dispute.append(tx)
            except ValueError:
                print(f'done (dispute no required, node {id} already flagged as malicous)')
            else:
                print("done")
    print()

    print(f'waiting for begin of finalization phase... ', end='', flush=True)
    utils.mine_blocks_until(contract.dispute_confirmed)
    print('done\n')

    print(f'loading dispute and state information... ', end='', flush=True)
    nodes[0].verify_nodes()
    print("done\n")

    for node in nodes[0].nodes:
        t = 'OK' if node in nodes[0].group else 'FAILED'
        print(f'node {node.id}: status={t}')
    print()

    print(f'deriving master key... ', end='', flush=True)
    nodes[0].derive_group_keys()
    print("done")

    print(f'uploading master key... ', end='', flush=True)
    tx_upload = nodes[0].upload_group_key()
    print("done")

    print()
    print()
    print(f'GAS USAGE STATS FOR {num_nodes} NODES')
    print()
    print('                  |   min   |   max   |   avg')
    print('-----------------------------------------------')

    for txs, name in zip([tx_register, tx_share_key, tx_dispute], ['registration', 'key sharing', 'dispute']):
        gas_min = min(tx['gasUsed'] for tx in txs)
        gas_max = max(tx['gasUsed'] for tx in txs)
        gas_avg = math.ceil(sum(tx['gasUsed'] for tx in txs) / len(txs))
        print(f'{name:<17} | {gas_min:7} | {gas_max:7} | {gas_avg:7}')
        print('-----------------------------------------------')
    g = tx_upload['gasUsed']  # noqa
    print(f'master key upload | {g:7} | {g:7} | {g:7} ')
    print()
    print()
    print()
    print("=" * 80)
    print("=" * 80)
    print("=" * 80)
    print()
    print()
    print()
Esempio n. 8
0
def contract():
    return utils.deploy_contract(CONTRACT)
import utils
import vss
from crypto import G1, G2, add, neg, multiply, random_scalar, check_pairing

w3 = utils.connect()
contract = utils.deploy_contract('DKG')


def test_add():
    a = multiply(G1, 5)
    b = multiply(G1, 10)
    s = add(a, b)
    assert contract.bn128_add([a[0], a[1], b[0], b[1]]) == list(s)


def test_multiply():
    assert G1 == (1, 2)
    assert contract.bn128_multiply([1, 2, 5]) == list(multiply(G1, 5))


def test_check_pairing():
    P1 = multiply(G1, 5)
    Q1 = G2
    Q2 = multiply(neg(G2), 5)
    P2 = G1
    assert check_pairing(P1, Q1, P2, Q2)


def test_verify_decryption_key():
    sk1, sk2 = random_scalar(), random_scalar()
    pk1, pk2 = multiply(G1, sk1), multiply(G1, sk2)
def setup_single():
    contract = utils.deploy_contract('DKG')
    node = EthNode(account)
    node.keygen()
    node.connect(contract)
    return node, contract
Esempio n. 11
0
import utils

w3 = utils.connect()
contract = utils.deploy_contract('Greeter')


def test_initial():
    assert contract.greet() == 'Hello'


def test_update():
    contract.setGreeting('Nihao', transact={'from': w3.eth.accounts[-1]})
    assert contract.greet() == 'Nihao'


def test_array_parameter():
    contract.doSomethingWithArray([1, 2, 3],
                                  transact={'from': w3.eth.accounts[-1]})
    assert contract.getNumbers() == [1, 2, 3]


def test_revert():
    # for now there seams to be no easy way to access the tx hash of the reverted transaction for web3py
    try:
        tx_hash = contract.test_revert(wait=False,
                                       transact={'from': w3.eth.accounts[-1]})
        print(tx_hash)
    except ValueError:
        pass