File: request_ws2p.py

package info (click to toggle)
python-duniterpy 1.1.1-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,228 kB
  • sloc: python: 10,624; makefile: 182; sh: 17
file content (169 lines) | stat: -rw-r--r-- 5,388 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# Copyright  2014-2022 Vincent Texier <vit@free.fr>
#
# DuniterPy is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# DuniterPy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

import json
import time
from typing import Any

import jsonschema
from jsonschema import ValidationError

from duniterpy.api.client import Client, WSConnection
from duniterpy.api.ws2p import requests
from duniterpy.constants import G1_TEST_CURRENCY_CODENAME
from duniterpy.helpers.ws2p import generate_ws2p_endpoint, handshake
from duniterpy.key import SigningKey
from duniterpy.tools import get_ws2p_challenge

# CONFIG #######################################

# You can either use a complete defined endpoint : [NAME_OF_THE_API] [DOMAIN] [IPv4] [IPv6] [PORT] [PATH]
# or the simple definition : [NAME_OF_THE_API] [DOMAIN] [PORT] [PATH]
# Here we use the WS2P API (WS2P [UUID] [DOMAIN] [PORT] [PATH])
BMAS_ENDPOINT = "BMAS g1-test.duniter.org 443"
CURRENCY = G1_TEST_CURRENCY_CODENAME


################################################


def send(ws: WSConnection, request: str, request_id: str, schema: dict) -> Any:
    """
    Send a WS2P request

    :rtype: Any
    :param ws: WSConnection instance
    :param request: Request string to send
    :param request_id: Unique request id
    :param schema: Validation schema
    """
    # Send request
    ws.send_str(request)

    # Wait response with request id
    response = ws.receive_json()
    while "resId" not in response or (
        "resId" in response and response["resId"] != request_id
    ):
        response = ws.receive_json()
        time.sleep(1)
    try:
        # Check response format
        jsonschema.validate(response, schema)
        # If valid display response
    except ValidationError:
        # If invalid response...
        try:
            # Check error response format
            jsonschema.validate(response, requests.ERROR_RESPONSE_SCHEMA)
            # If valid, display error response
        except ValidationError as exception:
            # If invalid, display exception on response validation
            print(exception)

    return response


def request_ws2p():
    """
    Main code
    """
    # dummy credentials
    salt = password = "test"

    # You can connect with member credentials in case there is not much slots available on the endpoint
    #
    # # Prompt hidden user entry
    # import getpass
    # salt = getpass.getpass("Enter your passphrase (salt): ")
    #
    # # Prompt hidden user entry
    # password = getpass.getpass("Enter your password: ")

    # Init signing_key instance
    signing_key = SigningKey.from_credentials(salt, password)

    # Create Client from endpoint string in Duniter format
    try:
        ws2p_endpoint = generate_ws2p_endpoint(BMAS_ENDPOINT)
    except ValueError as e:
        print(e)
        return
    client = Client(ws2p_endpoint)

    try:
        # Create a Web Socket connection
        ws = client.connect_ws()

        print("Successfully connected to the web socket endpoint")

        # HANDSHAKE #######################################################
        try:
            handshake(ws, signing_key, CURRENCY)
        except ValidationError as exception:
            print(exception.message)
            print("HANDSHAKE FAILED!")
            return

        # Send ws2p request
        print("Send getCurrent() request")
        request_id = get_ws2p_challenge()[:8]
        response = send(
            ws,
            requests.get_current(request_id),
            request_id,
            requests.BLOCK_RESPONSE_SCHEMA,
        )
        print("Response: " + json.dumps(response, indent=2))

        # Send ws2p request
        print("Send getBlock(30000) request")
        request_id = get_ws2p_challenge()[:8]
        response = send(
            ws,
            requests.get_block(request_id, 30000),
            request_id,
            requests.BLOCK_RESPONSE_SCHEMA,
        )
        print("Response: " + json.dumps(response, indent=2))

        # Send ws2p request
        print("Send getBlocks(30000, 2) request")
        request_id = get_ws2p_challenge()[:8]
        response = send(
            ws,
            requests.get_blocks(request_id, 30000, 2),
            request_id,
            requests.BLOCKS_RESPONSE_SCHEMA,
        )
        print("Response: " + json.dumps(response, indent=2))

        # Send ws2p request
        print("Send getRequirementsPending(3) request")
        request_id = get_ws2p_challenge()[:8]
        response = send(
            ws,
            requests.get_requirements_pending(request_id, 3),
            request_id,
            requests.REQUIREMENTS_RESPONSE_SCHEMA,
        )
        print("Response: " + json.dumps(response, indent=2))

    except jsonschema.ValidationError as e:
        print(f"{str(e.__class__.__name__)}:{str(e)}")


if __name__ == "__main__":
    request_ws2p()