Exemple #1
0
def get_moderator_wallet():
    m_sk = os.environ.get('MODERATOR_SK')
    m_pk = os.environ.get('MODERATOR_PK')
    m_address = os.environ.get('MODERATOR_ADDR')

    if not m_sk or not m_pk or not m_address:
        logger.error(
            'Fail to get MODERATOR_SK, MODERATOR_PK, MODERATOR_ADDR from environtment.'
        )
        return
    m_wallet = protos.WalletInfo(sk=utils.multibase_b64decode(m_sk),
                                 pk=utils.multibase_b64decode(m_pk),
                                 address=m_address)
    return m_wallet
Exemple #2
0
def b64decode_to_dict(data):
    try:
        dict_string = utils.multibase_b64decode(data).decode()
        return ast.literal_eval(dict_string)
    except Exception as e:
        logger.error('Error in decoding b64urlsafe '
                     'encoded data to dictionary.')
        logger.error(e, exc_info=True)
        return {}
Exemple #3
0
def deploy(m_wallet):
    with open(input) as f:
        raw = json.load(f).get('event_chain')
        logger.info("Protocol json loaded!")

        decoded = utils.multibase_b64decode(raw)
        itx = utils.parse_to_proto(decoded, protos.DeployProtocolTx)
        itx_hash = mcrypto.Hasher('sha3').hash(itx.SerializeToString())
        addr = did.AbtDid(role_type='tx', form='short').hash_to_did(itx_hash)
        itx.address = addr

        res = forge.rpc.send_itx(tx=itx,
                                 wallet=m_wallet,
                                 type_url='fg:t:deploy_protocol',
                                 nonce=0)
        if res.code == 0:
            logger.info("Success: event_chain tx deployed.")
        else:
            logger.error("Fail: Error in deploying event_chain tx.")
            logger.error(res)
Exemple #4
0
def deploy(forge, input_file):
    m_wallet = get_moderator_wallet()
    with open(input_file) as f:
        raw = list(json.load(f).values())[0]
        logger.info("Protocol json loaded!")

        decoded = utils.multibase_b64decode(raw)
        itx = utils.parse_to_proto(decoded, protos.DeployProtocolTx)
        itx_hash = mcrypto.Hasher('sha3').hash(itx.SerializeToString())
        addr = did.AbtDid(role_type='tx', form='short').hash_to_did(itx_hash)
        itx.address = addr

        res = forge.rpc.send_itx(tx=itx,
                                 wallet=m_wallet,
                                 type_url='fg:t:deploy_protocol',
                                 nonce=0)
        if res.code == 0:
            logger.info("Successfully deployed new transaction protocol.")
        else:
            logger.error("Fail to deploy new transaction protocol.")
            logger.error(res)
Exemple #5
0
    def verify(token, pk):
        """
        Verify if the token matches the public key

        Args:
            token(string): JWT token
            pk(bytes): public key

        Returns:
            bool

        Examples:
            >>> import base64
            >>> token='eyJhbGciOiAiRWQyNTUxOSIsICJ0eXAiOiAiSldUIn0.eyJpc3MiOiAiZGlkOmFidDp6MWYyaFB1ZEZnanRhOGNkRVYyeFRZaGRhcjNEb2ZxSGhkNiIsICJpYXQiOiAxNTU2NzcyNDE1LCAibmJmIjogMTU1Njc3MjQxNSwgImV4cCI6IDE1NTY3NzQyMTUsICJvcmlnaW4iOiAidGVzdGRhdGEifQ.sdbRA4_-gtMhlTRqhNzxnqYG-sFl3EGFOpVcsX6sSZ0E_33k6ga8jPTmNMkRz3DdFwnW_M62oK_-nFSw9wJQBw'
            >>> pk =base64.b16decode('F04A5204D6C529FBB3C435F62E042DB4E6D2BBF839A723A83A8B30740F0AD524')
            >>> AbtDid.verify(token, pk)
            True
        """
        try:
            header, body, signature = token.split('.')
            alg = lib.b64decode_to_dict(header).get('alg').lower()
            if alg == 'secp256k1' or alg == 'es256k':
                signer = Signer('secp256k1')
            elif alg == 'ed25519':
                signer = Signer('ed25519')

            sig = utils.multibase_b64decode(signature)
            is_sig_valid = signer.verify((header + '.' + body).encode(), sig,
                                         pk)
            did = lib.b64decode_to_dict(body).get('iss')
            if is_sig_valid and AbtDid.is_match_pk(did, pk):
                return True
            return False
        except Exception as e:
            logger.error(e, exc_info=True)
            logger.error("Fail to verify token {0} and pk {1}".format(
                token, pk))
            return False
Exemple #6
0

def deploy(m_wallet):
    with open(input) as f:
        raw = json.load(f).get('event_chain')
        logger.info("Protocol json loaded!")

        decoded = utils.multibase_b64decode(raw)
        itx = utils.parse_to_proto(decoded, protos.DeployProtocolTx)
        itx_hash = mcrypto.Hasher('sha3').hash(itx.SerializeToString())
        addr = did.AbtDid(role_type='tx', form='short').hash_to_did(itx_hash)
        itx.address = addr

        res = forge.rpc.send_itx(tx=itx,
                                 wallet=m_wallet,
                                 type_url='fg:t:deploy_protocol',
                                 nonce=0)
        if res.code == 0:
            logger.info("Success: event_chain tx deployed.")
        else:
            logger.error("Fail: Error in deploying event_chain tx.")
            logger.error(res)


if __name__ == "__main__":
    m_wallet = protos.WalletInfo(sk=utils.multibase_b64decode(m_sk),
                                 pk=utils.multibase_b64decode(m_pk),
                                 address=m_address)
    delcare_moderator(m_wallet)
    deploy(m_wallet)
Exemple #7
0
def parse_response(res):
    auth_info = res.get('authInfo')
    middle = auth_info.split('.')[1]
    res = forge_utils.multibase_b64decode(middle).decode()
    return json.loads(res)
Exemple #8
0
def get_origin(request):
    decoded = forge_utils.multibase_b64decode(request).decode()
    origin = json.loads(decoded).get('requestedClaims')[0].get('origin')
    return origin
async def send(context):
    '''
    Get a ramdon element from each category, and current time to generate a bill for simulation.
    Send this bill on the chain through AggregateTx
    ------
    Args:
        context(dict): all necessary info (items, vending_machines, batch)

    Output:
        send aggregate tx on the chain
    '''

    # put random info together to generate a random bill

    item_unit = choice(context['items'])
    vm_unit = choice(context['vms'])

    op = vm_unit['operator']
    ma = vm_unit['manufacturer']
    su = item_unit['supplier']
    lo = vm_unit['location']

    # get current time
    curr_time = Timestamp()
    curr_time.GetCurrentTime()

    # get item's value
    value = utils.int_to_biguint(utils.to_unit(item_unit['value']))

    logger.debug("before tx...")
    logger.debug(
        f"{op['moniker']}'s balance is {rpc.get_account_balance(op['address'])}"
    )
    logger.debug(
        f"{ma['moniker']}'s balance is {rpc.get_account_balance(ma['address'])}"
    )
    logger.debug(
        f"{su['moniker']}'s balance is {rpc.get_account_balance(su['address'])}"
    )
    logger.debug(
        f"{lo['moniker']}'s balance is {rpc.get_account_balance(lo['address'])}"
    )

    # group a wallet object for vending_machine
    vm_wallet = protos.WalletInfo(pk=utils.multibase_b64decode(vm_unit['pk']),
                                  sk=utils.multibase_b64decode(vm_unit['sk']),
                                  address=vm_unit['address'])

    # creat tx
    itx = AggregateTx(sku=item_unit['sku'],
                      value=value,
                      time=curr_time,
                      operator=op['address'],
                      manufacturer=ma['address'],
                      supplier=su['address'],
                      location=lo['address'])
    itx2 = utils.encode_to_any(type_url="fg:t:aggregate", data=itx)

    logger.info(
        f"batch {context['batch']} is sending tx... ---> value: {item_unit['value']}, from: {vm_unit['address']}, operator: {op['address']}, manufacturer: {ma['address']}, supplier: {su['address']}, location: {lo['address']}"
    )
    res = rpc.send_itx(tx=itx2, wallet=vm_wallet, nonce=0)

    await asyncio.sleep(5)
    logger.info(f"verify tx: {rpc.is_tx_ok(res.hash)}")

    logger.debug(
        f"{op['moniker']}'s balance is {rpc.get_account_balance(op['address'])}"
    )
    logger.debug(
        f"{ma['moniker']}'s balance is {rpc.get_account_balance(ma['address'])}"
    )
    logger.debug(
        f"{su['moniker']}'s balance is {rpc.get_account_balance(su['address'])}"
    )
    logger.debug(
        f"{lo['moniker']}'s balance is {rpc.get_account_balance(lo['address'])}"
    )