示例#1
0
 async def go():
     _, port, url = await self.create_server(
         'GET', '/wot/certified-by/pubkey', handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(certified_by, 'pubkey')
     await client.close()
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    try:
        # Create Web Socket connection on block path (async method)
        ws = await client(bma.ws.block)  # Type: WSConnection

        print("Connected successfully to web socket block path")

        loop = True
        # Iterate on each message received...
        while loop:
            print("Waiting message...")
            # Wait and capture next message
            data = await ws.receive_json()
            jsonschema.validate(data, bma.ws.WS_BLOCK_SCHEMA)
            print("Message received:")
            print(json.dumps(data, indent=2))

        # Close session
        await client.close()

    except (aiohttp.WSServerHandshakeError, ValueError) as e:
        print("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
    except (aiohttp.ClientError, gaierror, TimeoutError) as e:
        print("{0} : {1}".format(str(e), BMAS_ENDPOINT))
    except jsonschema.ValidationError as e:
        print("{:}:{:}".format(str(e.__class__.__name__), str(e)))
    await client.close()
示例#3
0
 async def go():
     _, port, url = await self.create_server('GET', '/wot/members',
                                             handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(members)
     await client.close()
 async def go():
     _, port, _ = await self.create_server("GET", "/blockchain/with/tx",
                                           handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(tx)
     await client.close()
async def main():
    """
    Main code (asynchronous requests)

    You can send one millions request with aiohttp :

    https://pawelmhm.github.io/asyncio/python/aiohttp/2016/04/22/asyncio-aiohttp.html

    But don't do that on one server, it's DDOS !

    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)
    tasks = []

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    task = asyncio.ensure_future(client(bma.node.summary))
    tasks.append(task)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    task = asyncio.ensure_future(client(bma.blockchain.parameters))
    tasks.append(task)

    responses = await asyncio.gather(*tasks)
    # you now have all response bodies in this variable
    print("\nResponses:")
    print(responses)

    # Close client aiohttp session
    await client.close()
async def main():
    """
    Main code (synchronous requests)
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    response = await client(bma.node.summary)
    print(response)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    response = await client(bma.blockchain.parameters)
    print(response)

    # Get the current block
    print("\nCall bma.blockchain.current:")
    response = await client(bma.blockchain.current)
    print(response)

    # Get the block number 10
    print("\nCall bma.blockchain.block(10):")
    response = await client(bma.blockchain.block, 10)
    print(response)

    # jsonschema validator
    summary_schema = {
        "type": "object",
        "properties": {
            "duniter": {
                "type": "object",
                "properties": {
                    "software": {
                        "type": "string"
                    },
                    "version": {
                        "type": "string"
                    },
                    "forkWindowSize": {
                        "type": "number"
                    },
                },
                "required": ["software", "version"],
            }
        },
        "required": ["duniter"],
    }

    # Get the node summary infos (direct REST GET request)
    print("\nCall direct get on node/summary")
    response = await client.get("node/summary",
                                rtype=RESPONSE_AIOHTTP,
                                schema=summary_schema)
    print(response)

    # Close client aiohttp session
    await client.close()
示例#7
0
def heads(client: Client):
    """
    GET Certification data over a member

    :param client: Client to connect to the api
    :rtype: dict
    """
    return client.get(MODULE + '/ws2p/heads', schema=WS2P_HEADS_SCHEMA)
示例#8
0
 async def go():
     _, port, _ = await self.create_server(
         "GET", "/wot/certifiers-of/pubkey", handler
     )
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(certifiers_of, "pubkey")
     await client.close()
 async def go():
     _, port, url = await self.create_server('GET',
                                             '/network/ws2p/heads',
                                             handler)
     with self.assertRaises(jsonschema.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(heads)
     await client.close()
示例#10
0
 async def go():
     _, port, _ = await self.create_server("GET",
                                           "/network/peering/peers",
                                           handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(network.peers)
     await client.close()
示例#11
0
def peer(client: Client) -> _WSRequestContextManager:
    """
    Connect to peer websocket

    :param client: Client to connect to the api
    :return:
    """
    return client.connect_ws(MODULE + '/peer')
示例#12
0
def block(client: Client) -> _WSRequestContextManager:
    """
    Connect to block websocket

    :param client: Client to connect to the api
    :return:
    """
    return client.connect_ws(MODULE + '/block')
示例#13
0
 async def go():
     _, port, url = await self.create_server('GET',
                                             '/blockchain/with/certs',
                                             handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(certifications)
     await client.close()
示例#14
0
def heads(client: Client):
    """
    GET Certification data over a member

    :param client: Client to connect to the api
    :rtype: dict
    """
    return client.get(MODULE + "/ws2p/heads", schema=WS2P_HEADS_SCHEMA)
示例#15
0
 async def go():
     _, port, url = await self.create_server(
         'GET', '/blockchain/memberships'
         '/8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU', handler)
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(memberships,
                      "8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU")
     await client.close()
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos to test the connection
    response = await client(bma.node.summary)
    print(response)

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"Enter recipient pubkey: ")

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # capture sources of account
    response = await client(bma.tx.sources, pubkey_from)

    if len(response["sources"]) == 0:
        print("no sources found for account %s" % pubkey_to)
        sys.exit(1)

    # get the first source
    source = response["sources"][0]

    # create the transaction document
    transaction = get_transaction_document(current_block, source, pubkey_from,
                                           pubkey_to)

    # sign document
    transaction.sign([key])

    # send the Transaction document to the node
    response = await client(bma.tx.process, transaction.signed_raw())

    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing transaction: {0}".format(
            await response.text()))

    # Close client aiohttp session
    await client.close()
 async def go():
     _, port, _ = await self.create_server(
         "GET",
         "/blockchain/hardship/8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU",
         handler,
     )
     with self.assertRaises(jsonschema.exceptions.ValidationError):
         client = Client(BMAEndpoint("127.0.0.1", "", "", port))
         await client(hardship,
                      "8Fi1VSTbjkXguwThF4v2ZxC5whK7pwG2vcGTkPUPjPGU")
     await client.close()
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos to test the connection
    response = await client(bma.node.summary)
    print(response)

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"Enter your public key: ")

    # init signer instance
    signer = SigningKey.from_credentials(salt, password)

    # check public key
    if signer.pubkey != pubkey:
        print("Bad credentials!")
        sys.exit(0)

    # capture current block to get currency name
    current_block = await client(bma.blockchain.current)

    # create our Identity document to sign the Certification document
    identity = await get_identity_document(client, current_block, pubkey)
    if identity is None:
        print("Identity not found for pubkey {0}".format(pubkey))
        # Close client aiohttp session
        await client.close()
        sys.exit(1)

    # get the revoke document
    revocation_signed_raw_document = get_signed_raw_revocation_document(
        identity, salt, password)

    # save revoke document in a file
    fp = open(REVOCATION_DOCUMENT_FILE_PATH, "w")
    fp.write(revocation_signed_raw_document)
    fp.close()

    # document saved
    print("Revocation document saved in %s" % REVOCATION_DOCUMENT_FILE_PATH)

    # Close client aiohttp session
    await client.close()
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos to test the connection
    response = await client(bma.node.summary)
    print(response)

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"Enter certified pubkey: ")

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # create our Identity document to sign the Certification document
    identity = await get_identity_document(client, current_block, pubkey_to)
    if identity is None:
        print("Identity not found for pubkey {0}".format(pubkey_to))
        # Close client aiohttp session
        await client.close()
        sys.exit(1)

    # send the Certification document to the node
    certification = get_certification_document(current_block, identity,
                                               pubkey_from)

    # sign document
    certification.sign([key])

    # Here we request for the path wot/certify
    response = await client(bma.wot.certify, certification.signed_raw())

    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing certification: {0}".format(
            await response.text()))

    # Close client aiohttp session
    await client.close()
示例#20
0
async def recursive_discovering(endpoints, endpoint):
    """
    Discover recursively new nodes.
    If new node found add it and try to found new node from his known nodes.
    """
    api = generate_duniterpy_endpoint_format(endpoint)
    sub_client = Client(api)
    news = await get_peers_among_leaves(sub_client)
    await sub_client.close()
    for new in news:
        if best_endpoint_address(new, False) is not None and new not in endpoints:
            endpoints.append(new)
            await recursive_discovering(endpoints, new)
    return endpoints
示例#21
0
async def generate_ws2p_endpoint(
        bma_endpoint: Union[str, BMAEndpoint,
                            SecuredBMAEndpoint]) -> WS2PEndpoint:
    """
    Retrieve WS2P endpoints from BMA peering
    Take the first one found
    """
    bma_client = Client(bma_endpoint)
    peering = await bma_client(bma.network.peering)
    await bma_client.close()

    for endpoint in peering["endpoints"]:
        if endpoint.startswith("WS2P"):
            return WS2PEndpoint.from_inline(endpoint)
    raise ValueError("No WS2P endpoint found")
示例#22
0
async def main():
    """
    Main code (synchronous requests)
    """
    # Create Client from endpoint string in Duniter format
    client = Client(ES_CORE_ENDPOINT)

    # Get the current node (direct REST GET request)
    print("\nGET g1-test/block/current/_source:")
    response = await client.get('g1-test/block/current/_source')
    print(response)

    # Get the node number 2 with only selected fields (direct REST GET request)
    print("\nGET g1-test/block/2/_source:")
    response = await client.get(
        'g1-test/block/2/_source',
        {'_source': 'number,hash,dividend,membersCount'})
    print(response)

    # Close client aiohttp session
    await client.close()

    # Create Client from endpoint string in Duniter format
    client = Client(ES_USER_ENDPOINT)

    # prompt entry
    pubkey = input("\nEnter a public key to get the user profile: ")

    # Get the profil of a public key (direct REST GET request)
    print("\nGET user/profile/{0}/_source:".format(pubkey))
    response = await client.get('user/profile/{0}/_source'.format(
        pubkey.strip(' \n')))
    print(response)

    # Close client aiohttp session
    await client.close()
示例#23
0
async def test_check_passed_blocks_range(from_block, to_block, capsys,
                                         monkeypatch):
    monkeypatch.setattr(bma.blockchain, "current", current)
    client = Client(EndPoint().BMA_ENDPOINT)
    # https://medium.com/python-pandemonium/testing-sys-exit-with-pytest-10c6e5f7726f
    with pytest.raises(SystemExit) as pytest_wrapped_e:
        await check_passed_blocks_range(client, from_block, to_block)
    assert pytest_wrapped_e.type == SystemExit
    assert pytest_wrapped_e.value.code == FAILURE_EXIT_STATUS
    captured = capsys.readouterr()
    if to_block == HEAD_BLOCK + 1:
        expected = "Passed TO_BLOCK argument is bigger than the head block: " + str(
            HEAD_BLOCK)
    else:
        expected = "TO_BLOCK should be bigger or equal to FROM_BLOCK\n"
    assert expected in captured.out
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    try:
        # Create Web Socket connection on block path
        ws_connection = client(bma.ws.block)

        # From the documentation ws_connection should be a ClientWebSocketResponse object...
        #
        # https://docs.aiohttp.org/en/stable/client_quickstart.html#websockets
        #
        # In reality, aiohttp.session.ws_connect() returns a aiohttp.client._WSRequestContextManager instance.
        # It must be used in a with statement to get the ClientWebSocketResponse instance from it (__aenter__).
        # At the end of the with statement, aiohttp.client._WSRequestContextManager.__aexit__ is called
        # and close the ClientWebSocketResponse in it.

        # Mandatory to get the "for msg in ws" to work !
        async with ws_connection as ws:
            print("Connected successfully to web socket block path")
            # Iterate on each message received...
            async for msg in ws:
                # if message type is text...
                if msg.type == aiohttp.WSMsgType.TEXT:
                    print("Received a block")
                    # Validate jsonschema and return a the json dict
                    block_data = parse_text(msg.data, bma.ws.WS_BLOCK_SCHEMA)
                    print(block_data)
                elif msg.type == aiohttp.WSMsgType.CLOSED:
                    # Connection is closed
                    print("Web socket connection closed !")
                elif msg.type == aiohttp.WSMsgType.ERROR:
                    # Connection error
                    print("Web socket connection error !")

                # Close session
                await client.close()

    except (aiohttp.WSServerHandshakeError, ValueError) as e:
        print("Websocket block {0} : {1}".format(type(e).__name__, str(e)))
    except (aiohttp.ClientError, gaierror, TimeoutError) as e:
        print("{0} : {1}".format(str(e), BMAS_ENDPOINT))
    except jsonschema.ValidationError as e:
        print("{:}:{:}".format(str(e.__class__.__name__), str(e)))
示例#25
0
async def test_tx_history_generate_table():
    client = Client("BMAS " + " ".join(G1_DEFAULT_ENDPOINT))
    ud_value = 10.07
    currency = "gtest"
    uids = False
    table_columns = 5
    pubkey = "78ZwwgpgdH5uLZLbThUQH7LKwPgjMunYfLiCfUCySkM8"

    received_txs, sent_txs = list(), list()
    await tx_history.get_transactions_history(client, pubkey, received_txs,
                                              sent_txs)

    tx_history.remove_duplicate_txs(received_txs, sent_txs)
    txs_list = await tx_history.generate_table(received_txs, sent_txs, pubkey,
                                               ud_value, currency, uids)
    await client.close()

    for tx_list in txs_list:
        assert len(tx_list) == table_columns
示例#26
0
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    response = await client(bma.node.summary)
    print(response)

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"results"][0]

    # create a membership demand document
    membership = get_membership_document("IN", current_block, identity, key)

    # send the membership signed raw document to the node
    response = await client(bma.blockchain.membership, membership.signed_raw())

    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing membership : {0}".format(
            await response.text()))

    # Close client aiohttp session
    await client.close()
示例#27
0
async def get_ws2p_endpoints(
    bma_endpoint: Union[str, BMAEndpoint, SecuredBMAEndpoint]
) -> List[WS2PEndpoint]:
    """
    Return the list of WS2P endpoints for a BMA endpoint
    """
    ws2p_endpoints = list()
    bma_client = Client(bma_endpoint)
    try:
        peering = await bma_client(bma.network.peering)
    except Exception as ex:
        await bma_client.close()
        raise ex

    for endpoint in peering["endpoints"]:
        if endpoint.startswith("WS2P"):
            ws2p_endpoints.append(WS2PEndpoint.from_inline(endpoint))

    await bma_client.close()

    return ws2p_endpoints
示例#28
0
文件: blocks.py 项目: duniter/silkaj
async def verify_blocks_signatures(from_block, to_block):
    client = Client(EndPoint().BMA_ENDPOINT)
    to_block = await check_passed_blocks_range(client, from_block, to_block)
    invalid_blocks_signatures = list()
    chunks_from = range(from_block, to_block + 1, BMA_MAX_BLOCKS_CHUNK_SIZE)
    with progressbar(chunks_from,
                     label="Processing blocks verification") as bar:
        for chunk_from in bar:
            chunk_size = get_chunk_size(from_block, to_block, chunks_from,
                                        chunk_from)
            logging.info("Processing chunk from block {} to {}".format(
                chunk_from, chunk_from + chunk_size))
            chunk = await get_chunk(client, chunk_size, chunk_from)

            for block in chunk:
                block = Block.from_signed_raw(block["raw"] +
                                              block["signature"] + "\n")
                verify_block_signature(invalid_blocks_signatures, block)

    await client.close()
    display_result(from_block, to_block, invalid_blocks_signatures)
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos by dedicated method (with json schema validation)
    response = await client(bma.node.summary)
    print(response)

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"Enter your UID: ")

    # create our signed identity document
    identity = get_identity_document(current_block, uid, salt, password)

    # create a membership demand document
    membership = get_membership_document("IN", current_block, identity, salt, password)

    # send the membership signed raw document to the node
    response = await client(bma.blockchain.membership, membership.signed_raw())

    if response.status == 200:
        print(await response.text())
    else:
        print("Error while publishing membership : {0}".format(await response.text()))

    # Close client aiohttp session
    await client.close()
async def main():
    """
    Main code
    """
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)

    # Get the node summary infos to test the connection
    response = await client(bma.node.summary)
    print(response)

    # capture current block to get version and currency and blockstamp
    current_block = await client(bma.blockchain.current)

    # prompt entry
    uid = input("Enter your Unique IDentifier (pseudonym): ")

    # prompt hidden user entry
    salt = getpass.getpass("Enter your passphrase (salt): ")

    # prompt hidden user entry
    password = getpass.getpass("Enter your password: "******"Error while publishing identity : {0}".format(await response.text()))

    # Close client aiohttp session
    await client.close()
示例#31
0
 def __init__(self):
     self.client = Client(EndPoint().BMA_ENDPOINT)