-
Notifications
You must be signed in to change notification settings - Fork 0
/
end_user_standalone_client.py
2529 lines (2377 loc) · 158 KB
/
end_user_standalone_client.py
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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import asyncio
import json
import httpx
import os
import logging
import shutil
import queue
import zstandard as zstd
import base64
import pytz
import hashlib
import urllib.parse as urlparse
import re
import random
import time
import traceback
import uuid
from decimal import Decimal
import decimal
import pandas as pd
from datetime import datetime, date, timezone
from typing import List, Dict, Union, Any, Optional, Tuple
from logging.handlers import RotatingFileHandler, QueueHandler, QueueListener
from httpx import AsyncClient, Limits, Timeout
from decouple import Config as DecoupleConfig, RepositoryEnv
from sqlmodel import SQLModel, Field, Column, JSON
# Note: you must have `minrelaytxfee=0.00001` in your pastel.conf to allow "dust" transactions for the inference request confirmation transactions to work!
logger = logging.getLogger("pastel_supernode_inference_client")
config = DecoupleConfig(RepositoryEnv('.env'))
MESSAGING_TIMEOUT_IN_SECONDS = config.get("MESSAGING_TIMEOUT_IN_SECONDS", default=60, cast=int)
MY_LOCAL_PASTELID = config.get("MY_LOCAL_PASTELID", cast=str)
# MY_PASTELID_PASSPHRASE = config.get("MY_PASTELID_PASSPHRASE", cast=str)
MY_PASTELID_PASSPHRASE = "5QcX9nX67buxyeC"
MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING = config.get("MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING", default=0.1, cast=float)
MAXIMUM_LOCAL_PASTEL_BLOCK_HEIGHT_DIFFERENCE_IN_BLOCKS = config.get("MAXIMUM_LOCAL_PASTEL_BLOCK_HEIGHT_DIFFERENCE_IN_BLOCKS", default=1, cast=int)
TARGET_VALUE_PER_CREDIT_IN_USD = config.get("TARGET_VALUE_PER_CREDIT_IN_USD", default=0.1, cast=float)
TARGET_PROFIT_MARGIN = config.get("TARGET_PROFIT_MARGIN", default=0.1, cast=float)
MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING = config.get("MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING", default=0.1, cast=float)
MAXIMUM_PER_CREDIT_PRICE_IN_PSL_FOR_CLIENT = config.get("MAXIMUM_PER_CREDIT_PRICE_IN_PSL_FOR_CLIENT", default=100.0, cast=float)
def setup_logger():
if logger.handlers:
return logger
old_logs_dir = 'old_logs'
if not os.path.exists(old_logs_dir):
os.makedirs(old_logs_dir)
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
log_file_path = 'pastel_supernode_inference_client.log'
log_queue = queue.Queue(-1) # Create a queue for the handlers
fh = RotatingFileHandler(log_file_path, maxBytes=10*1024*1024, backupCount=5)
fh.setFormatter(formatter)
def namer(default_log_name): # Function to move rotated logs to the old_logs directory
return os.path.join(old_logs_dir, os.path.basename(default_log_name))
def rotator(source, dest):
shutil.move(source, dest)
fh.namer = namer
fh.rotator = rotator
sh = logging.StreamHandler() # Stream handler
sh.setFormatter(formatter)
queue_handler = QueueHandler(log_queue) # Create QueueHandler
queue_handler.setFormatter(formatter)
logger.addHandler(queue_handler)
listener = QueueListener(log_queue, fh, sh) # Create QueueListener with real handlers
listener.start()
logging.getLogger('sqlalchemy.engine').setLevel(logging.WARNING) # Configure SQLalchemy logging
return logger
logger = setup_logger()
def get_local_rpc_settings_func(directory_with_pastel_conf=os.path.expanduser("~/.pastel/")):
with open(os.path.join(directory_with_pastel_conf, "pastel.conf"), 'r') as f:
lines = f.readlines()
other_flags = {}
rpchost = '127.0.0.1'
rpcport = '19932'
for line in lines:
if line.startswith('rpcport'):
value = line.split('=')[1]
rpcport = value.strip()
elif line.startswith('rpcuser'):
value = line.split('=')[1]
rpcuser = value.strip()
elif line.startswith('rpcpassword'):
value = line.split('=')[1]
rpcpassword = value.strip()
elif line.startswith('rpchost'):
pass
elif line == '\n':
pass
else:
current_flag = line.strip().split('=')[0].strip()
current_value = line.strip().split('=')[1].strip()
other_flags[current_flag] = current_value
return rpchost, rpcport, rpcuser, rpcpassword, other_flags
def write_rpc_settings_to_env_file_func(rpc_host, rpc_port, rpc_user, rpc_password, other_flags):
with open('.env', 'w') as f:
f.write(f"RPC_HOST={rpc_host}\n")
f.write(f"RPC_PORT={rpc_port}\n")
f.write(f"RPC_USER={rpc_user}\n")
f.write(f"RPC_PASSWORD={rpc_password}\n")
for current_flag in other_flags:
current_value = other_flags[current_flag]
try:
f.write(f"{current_flag}={current_value}\n")
except Exception as e:
logger.error(f"Error writing to .env file: {e}")
pass
return
class JSONRPCException(Exception):
def __init__(self, rpc_error):
parent_args = []
try:
parent_args.append(rpc_error['message'])
except Exception as e:
logger.error(f"Error occurred in JSONRPCException: {e}")
pass
Exception.__init__(self, *parent_args)
self.error = rpc_error
self.code = rpc_error['code'] if 'code' in rpc_error else None
self.message = rpc_error['message'] if 'message' in rpc_error else None
def __str__(self):
return '%d: %s' % (self.code, self.message)
def __repr__(self):
return '<%s \'%s\'>' % (self.__class__.__name__, self)
def EncodeDecimal(o):
if isinstance(o, Decimal):
return float(round(o, 8))
raise TypeError(repr(o) + " is not JSON serializable")
class AsyncAuthServiceProxy:
max_concurrent_requests = 5000
_semaphore = asyncio.BoundedSemaphore(max_concurrent_requests)
def __init__(self, service_url, service_name=None, reconnect_timeout=15, reconnect_amount=2, request_timeout=20):
self.service_url = service_url
self.service_name = service_name
self.url = urlparse.urlparse(service_url)
self.client = AsyncClient(timeout=Timeout(request_timeout), limits=Limits(max_connections=200, max_keepalive_connections=10))
self.id_count = 0
user = self.url.username
password = self.url.password
authpair = f"{user}:{password}".encode('utf-8')
self.auth_header = b'Basic ' + base64.b64encode(authpair)
self.reconnect_timeout = reconnect_timeout
self.reconnect_amount = reconnect_amount
self.request_timeout = request_timeout
def __getattr__(self, name):
if name.startswith('__') and name.endswith('__'):
raise AttributeError
if self.service_name is not None:
name = f"{self.service_name}.{name}"
return AsyncAuthServiceProxy(self.service_url, name)
async def __call__(self, *args):
async with self._semaphore: # Acquire a semaphore
self.id_count += 1
postdata = json.dumps({
'version': '1.1',
'method': self.service_name,
'params': args,
'id': self.id_count
}, default=EncodeDecimal)
headers = {
'Host': self.url.hostname,
'User-Agent': "AuthServiceProxy/0.1",
'Authorization': self.auth_header,
'Content-type': 'application/json'
}
for i in range(self.reconnect_amount):
try:
if i > 0:
logger.warning(f"Reconnect try #{i+1}")
sleep_time = self.reconnect_timeout * (2 ** i)
await asyncio.sleep(sleep_time)
response = await self.client.post(
self.service_url, headers=headers, data=postdata)
break
except Exception as e:
logger.error(f"Error occurred in __call__: {e}")
err_msg = f"Failed to connect to {self.url.hostname}:{self.url.port}"
rtm = self.reconnect_timeout
if rtm:
err_msg += f". Waiting {rtm} seconds."
logger.exception(err_msg)
else:
logger.error("Reconnect tries exceeded.")
return
response_json = response.json()
if response_json['error'] is not None:
raise JSONRPCException(response_json['error'])
elif 'result' not in response_json:
raise JSONRPCException({
'code': -343, 'message': 'missing JSON-RPC result'})
else:
return response_json['result']
async def check_masternode_top_func():
global rpc_connection
masternode_top_command_output = await rpc_connection.masternode('top')
return masternode_top_command_output
async def check_supernode_list_func():
global rpc_connection
masternode_list_full_command_output = await rpc_connection.masternodelist('full')
masternode_list_rank_command_output = await rpc_connection.masternodelist('rank')
masternode_list_pubkey_command_output = await rpc_connection.masternodelist('pubkey')
masternode_list_extra_command_output = await rpc_connection.masternodelist('extra')
masternode_list_full_df = pd.DataFrame([masternode_list_full_command_output[x].split() for x in masternode_list_full_command_output])
masternode_list_full_df['txid_vout'] = [x for x in masternode_list_full_command_output]
masternode_list_full_df.columns = ['supernode_status', 'protocol_version', 'supernode_psl_address', 'lastseentime', 'activeseconds', 'lastpaidtime', 'lastpaidblock', 'ipaddress:port', 'txid_vout']
masternode_list_full_df.index = masternode_list_full_df['txid_vout']
masternode_list_full_df.drop(columns=['txid_vout'], inplace=True)
for txid_vout in masternode_list_full_df.index:
rank = masternode_list_rank_command_output.get(txid_vout)
pubkey = masternode_list_pubkey_command_output.get(txid_vout)
extra = masternode_list_extra_command_output.get(txid_vout, {})
masternode_list_full_df.at[txid_vout, 'rank'] = rank if rank is not None else 'Unknown'
masternode_list_full_df.at[txid_vout, 'pubkey'] = pubkey if pubkey is not None else 'Unknown'
masternode_list_full_df.at[txid_vout, 'extAddress'] = extra.get('extAddress', 'Unknown')
masternode_list_full_df.at[txid_vout, 'extP2P'] = extra.get('extP2P', 'Unknown')
masternode_list_full_df.at[txid_vout, 'extKey'] = extra.get('extKey', 'Unknown')
masternode_list_full_df['lastseentime'] = pd.to_numeric(masternode_list_full_df['lastseentime'], downcast='integer')
masternode_list_full_df['lastpaidtime'] = pd.to_numeric(masternode_list_full_df['lastpaidtime'], downcast='integer')
masternode_list_full_df['lastseentime'] = pd.to_datetime(masternode_list_full_df['lastseentime'], unit='s')
masternode_list_full_df['lastpaidtime'] = pd.to_datetime(masternode_list_full_df['lastpaidtime'], unit='s')
masternode_list_full_df['activeseconds'] = masternode_list_full_df['activeseconds'].astype(int)
masternode_list_full_df['lastpaidblock'] = masternode_list_full_df['lastpaidblock'].astype(int)
masternode_list_full_df['activedays'] = masternode_list_full_df['activeseconds'].apply(lambda x: float(x)/86400.0)
masternode_list_full_df['rank'] = masternode_list_full_df['rank'].astype(int, errors='ignore')
masternode_list_full_df = masternode_list_full_df[masternode_list_full_df['supernode_status'].isin(['ENABLED', 'PRE_ENABLED'])]
masternode_list_full_df = masternode_list_full_df[masternode_list_full_df['ipaddress:port'] != '154.38.164.75:29933'] # TODO: Remove this
masternode_list_full_df__json = masternode_list_full_df.to_json(orient='index')
return masternode_list_full_df, masternode_list_full_df__json
def get_top_supernode_url(supernode_list_df):
if not supernode_list_df.empty:
supernode_list_df = supernode_list_df[supernode_list_df['supernode_status']=='ENABLED']
top_supernode = supernode_list_df.loc[supernode_list_df['rank'] == supernode_list_df['rank'].min()]
if not top_supernode.empty:
ipaddress_port = top_supernode['ipaddress:port'].values[0]
ipaddress = ipaddress_port.split(':')[0]
supernode_url = f"http://{ipaddress}:7123"
return supernode_url
return None
async def get_current_pastel_block_height_func():
global rpc_connection
best_block_hash = await rpc_connection.getbestblockhash()
best_block_details = await rpc_connection.getblock(best_block_hash)
curent_block_height = best_block_details['height']
return curent_block_height
async def get_best_block_hash_and_merkle_root_func():
global rpc_connection
best_block_height = await get_current_pastel_block_height_func()
best_block_hash = await rpc_connection.getblockhash(best_block_height)
best_block_details = await rpc_connection.getblock(best_block_hash)
best_block_merkle_root = best_block_details['merkleroot']
return best_block_hash, best_block_merkle_root, best_block_height
def compute_sha3_256_hexdigest(input_str):
"""Compute the SHA3-256 hash of the input string and return the hexadecimal digest."""
return hashlib.sha3_256(input_str.encode()).hexdigest()
def get_sha256_hash_of_input_data_func(input_data_or_string):
if isinstance(input_data_or_string, str):
input_data_or_string = input_data_or_string.encode('utf-8')
sha256_hash_of_input_data = hashlib.sha3_256(input_data_or_string).hexdigest()
return sha256_hash_of_input_data
def base64_encode_json(json_input):
return base64.b64encode(json.dumps(json_input, sort_keys=True).encode('utf-8')).decode('utf-8')
async def extract_response_fields_from_credit_pack_ticket_message_data_as_json_func(model_instance: SQLModel) -> str:
response_fields = {}
last_hash_field_name = None
last_signature_field_names = []
for field_name in model_instance.__fields__.keys():
if field_name.startswith("sha3_256_hash_of"):
last_hash_field_name = field_name
elif "_signature_on_" in field_name:
last_signature_field_names.append(field_name)
fields_to_exclude = [last_hash_field_name, last_signature_field_names[-1], 'id']
for field_name, field_value in model_instance.__dict__.items():
if field_name in fields_to_exclude or '_sa_instance_state' in field_name:
continue
if field_value is not None:
if isinstance(field_value, (datetime, date)):
response_fields[field_name] = field_value.isoformat()
elif isinstance(field_value, (list, dict)):
response_fields[field_name] = json.dumps(field_value, ensure_ascii=False, sort_keys=True)
elif isinstance(field_value, decimal.Decimal):
response_fields[field_name] = str(field_value)
elif isinstance(field_value, bool):
response_fields[field_name] = int(field_value)
else:
response_fields[field_name] = field_value
sorted_response_fields = dict(sorted(response_fields.items()))
return json.dumps(sorted_response_fields, ensure_ascii=False, sort_keys=True)
async def compute_sha3_256_hash_of_sqlmodel_response_fields(model_instance: SQLModel) -> str:
response_fields_json = await extract_response_fields_from_credit_pack_ticket_message_data_as_json_func(model_instance)
sha256_hash_of_response_fields = get_sha256_hash_of_input_data_func(response_fields_json)
return sha256_hash_of_response_fields
def compare_datetimes(datetime_input1, datetime_input2):
# Check if the inputs are datetime objects, otherwise parse them
if not isinstance(datetime_input1, datetime):
datetime_input1 = pd.to_datetime(datetime_input1)
if not isinstance(datetime_input2, datetime):
datetime_input2 = pd.to_datetime(datetime_input2)
# Ensure both datetime objects are timezone-aware
if datetime_input1.tzinfo is None:
datetime_input1 = datetime_input1.replace(tzinfo=pytz.UTC)
if datetime_input2.tzinfo is None:
datetime_input2 = datetime_input2.replace(tzinfo=pytz.UTC)
# Calculate the difference in seconds
difference_in_seconds = abs((datetime_input2 - datetime_input1).total_seconds())
# Check if the difference is within the acceptable range
datetimes_are_close_enough_to_consider_them_matching = (
difference_in_seconds <= MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING
)
return difference_in_seconds, datetimes_are_close_enough_to_consider_them_matching
async def verify_message_with_pastelid_func(pastelid, message_to_verify, pastelid_signature_on_message) -> str:
global rpc_connection
verification_result = await rpc_connection.pastelid('verify', message_to_verify, pastelid_signature_on_message, pastelid, 'ed448')
return verification_result['verification']
async def validate_credit_pack_ticket_message_data_func(model_instance: SQLModel):
validation_errors = []
# Validate timestamp fields
for field_name, field_value in model_instance.__dict__.items():
if field_name.endswith("_timestamp_utc_iso_string"):
try:
pd.to_datetime(field_value)
except ValueError:
validation_errors.append(f"Invalid timestamp format for field {field_name}")
# Check if the timestamp is within an acceptable range of the current time
current_timestamp = pd.to_datetime(datetime.utcnow().replace(tzinfo=pytz.UTC))
timestamp_diff, timestamps_match = compare_datetimes(field_value, current_timestamp)
if not timestamps_match:
validation_errors.append(f"Timestamp in field {field_name} is too far from the current time")
# Validate pastel block height fields
best_block_hash, best_block_merkle_root, best_block_height = await get_best_block_hash_and_merkle_root_func()
for field_name, field_value in model_instance.__dict__.items():
if field_name.endswith("_pastel_block_height"):
if abs(field_value - best_block_height) > MAXIMUM_LOCAL_PASTEL_BLOCK_HEIGHT_DIFFERENCE_IN_BLOCKS:
validation_errors.append(f"Pastel block height in field {field_name} does not match the current block height; difference is {abs(field_value - best_block_height)} blocks (local: {field_value}, remote: {best_block_height})")
# Validate hash fields
expected_hash = await compute_sha3_256_hash_of_sqlmodel_response_fields(model_instance)
hash_field_name = None
for field_name in model_instance.__fields__:
if "sha3_256_hash_of_" in field_name and field_name.endswith("_fields"):
hash_field_name = field_name
break
if hash_field_name:
actual_hash = getattr(model_instance, hash_field_name)
if actual_hash != expected_hash:
validation_errors.append(f"SHA3-256 hash in field {hash_field_name} does not match the computed hash of the response fields")
# Validate pastelid signature fields
last_signature_field_name = None
last_hash_field_name = None
for field_name in model_instance.__fields__:
if "_pastelid" in field_name:
first_pastelid = field_name
break
for field_name in model_instance.__fields__:
if "_signature_on_" in field_name:
last_signature_field_name = field_name
elif "sha3_256_hash_of_" in field_name and field_name.endswith("_fields"):
last_hash_field_name = field_name
if last_signature_field_name and last_hash_field_name:
signature_field_name = last_signature_field_name
hash_field_name = last_hash_field_name
if first_pastelid == last_signature_field_name:
first_pastelid = "NA"
if hasattr(model_instance, first_pastelid) or first_pastelid == "NA":
if first_pastelid == "NA":
pastelid_and_signature_combined_field_name = last_signature_field_name
pastelid_and_signature_combined_field_json = getattr(model_instance, pastelid_and_signature_combined_field_name)
pastelid_and_signature_combined_field_dict = json.loads(pastelid_and_signature_combined_field_json)
pastelid_and_signature_combined_field_dict_keys = pastelid_and_signature_combined_field_dict.keys()
for current_key in pastelid_and_signature_combined_field_dict_keys:
if "pastelid" in current_key:
pastelid = pastelid_and_signature_combined_field_dict[current_key]
if "signature" in current_key:
signature = pastelid_and_signature_combined_field_dict[current_key]
message_to_verify = getattr(model_instance, hash_field_name)
else:
pastelid = getattr(model_instance, first_pastelid)
message_to_verify = getattr(model_instance, hash_field_name)
signature = getattr(model_instance, signature_field_name)
verification_result = await verify_message_with_pastelid_func(pastelid, message_to_verify, signature)
if verification_result != 'OK':
validation_errors.append(f"Pastelid signature in field {signature_field_name} failed verification")
else:
validation_errors.append(f"Corresponding pastelid field {first_pastelid} not found for signature field {signature_field_name}")
return validation_errors
async def calculate_xor_distance(pastelid1: str, pastelid2: str) -> int:
hash1 = hashlib.sha3_256(pastelid1.encode()).hexdigest()
hash2 = hashlib.sha3_256(pastelid2.encode()).hexdigest()
xor_result = int(hash1, 16) ^ int(hash2, 16)
return xor_result
def check_if_pastelid_is_valid_func(input_string: str) -> bool:
# Define the regex pattern to match the conditions:
# Starts with 'jX'; Followed by characters that are only alphanumeric and are shown in the example;
pattern = r'^jX[A-Za-z0-9]{84}$'
if re.match(pattern, input_string):
return True
else:
return False
async def get_supernode_url_from_pastelid_func(pastelid: str, supernode_list_df: pd.DataFrame) -> str:
is_valid_pastelid = check_if_pastelid_is_valid_func(pastelid)
if not is_valid_pastelid:
raise ValueError(f"Invalid PastelID: {pastelid}")
supernode_row = supernode_list_df[supernode_list_df['extKey'] == pastelid]
if not supernode_row.empty:
supernode_ipaddress_port = supernode_row['ipaddress:port'].values[0]
ipaddress = supernode_ipaddress_port.split(':')[0]
supernode_url = f"http://{ipaddress}:7123"
return supernode_url
else:
raise ValueError(f"Supernode with PastelID {pastelid} not found in the supernode list")
async def get_closest_supernode_to_pastelid_url(input_pastelid: str, supernode_list_df: pd.DataFrame) -> Tuple[Optional[str], Optional[str]]:
if not supernode_list_df.empty:
list_of_supernode_pastelids = supernode_list_df['extKey'].tolist()
closest_supernode_pastelid = await get_closest_supernode_pastelid_from_list(input_pastelid, list_of_supernode_pastelids)
supernode_url = await get_supernode_url_from_pastelid_func(closest_supernode_pastelid, supernode_list_df)
return supernode_url, closest_supernode_pastelid
return None, None
async def get_n_closest_supernodes_to_pastelid_urls(n: int, input_pastelid: str, supernode_list_df: pd.DataFrame) -> List[Tuple[str, str]]:
if not supernode_list_df.empty:
list_of_supernode_pastelids = supernode_list_df['extKey'].tolist()
xor_distances = [(supernode_pastelid, await calculate_xor_distance(input_pastelid, supernode_pastelid)) for supernode_pastelid in list_of_supernode_pastelids]
sorted_xor_distances = sorted(xor_distances, key=lambda x: x[1])
closest_supernodes = sorted_xor_distances[:n]
supernode_urls_and_pastelids = [(await get_supernode_url_from_pastelid_func(pastelid, supernode_list_df), pastelid) for pastelid, _ in closest_supernodes]
return supernode_urls_and_pastelids
return []
async def get_closest_supernode_pastelid_from_list(local_pastelid: str, supernode_pastelids: List[str]) -> str:
xor_distances = [(supernode_pastelid, await calculate_xor_distance(local_pastelid, supernode_pastelid)) for supernode_pastelid in supernode_pastelids]
closest_supernode = min(xor_distances, key=lambda x: x[1])
return closest_supernode[0]
async def fetch_current_psl_market_price():
async def check_prices():
async with httpx.AsyncClient() as client:
try:
# Fetch data from CoinMarketCap
response_cmc = await client.get("https://coinmarketcap.com/currencies/pastel/")
price_cmc = float(re.search(r'price today is \$([0-9\.]+) USD', response_cmc.text).group(1))
except (httpx.RequestError, AttributeError, ValueError):
price_cmc = None
try:
# Fetch data from CoinGecko
response_cg = await client.get("https://api.coingecko.com/api/v3/simple/price?ids=pastel&vs_currencies=usd")
if response_cg.status_code == 200:
data = response_cg.json()
price_cg = data.get("pastel", {}).get("usd")
else:
price_cg = None
except (httpx.RequestError, AttributeError, ValueError):
price_cg = None
return price_cmc, price_cg
price_cmc, price_cg = await check_prices()
if price_cmc is None and price_cg is None:
#Sleep for a couple seconds and try again:
await asyncio.sleep(2)
price_cmc, price_cg = await check_prices()
# Calculate the average price
prices = [price for price in [price_cmc, price_cg] if price is not None]
if not prices:
raise ValueError("Could not retrieve PSL price from any source.")
average_price = sum(prices) / len(prices)
# Validate the price
if not 0.0000001 < average_price < 0.02:
raise ValueError(f"Invalid PSL price: {average_price}")
return average_price
async def estimated_market_price_of_inference_credits_in_psl_terms() -> float:
try:
psl_price_usd = await fetch_current_psl_market_price()
target_value_per_credit_usd = TARGET_VALUE_PER_CREDIT_IN_USD
target_profit_margin = TARGET_PROFIT_MARGIN
# Calculate the cost per credit in USD, considering the profit margin
cost_per_credit_usd = target_value_per_credit_usd / (1 - target_profit_margin)
# Convert the cost per credit from USD to PSL
cost_per_credit_psl = cost_per_credit_usd / psl_price_usd
return cost_per_credit_psl
except (ValueError, ZeroDivisionError) as e:
logger.error(f"Error calculating estimated market price of inference credits: {str(e)}")
raise
def parse_and_format(value):
try:
# Check if the JSON string is already formatted
if isinstance(value, str) and "\n" in value:
return value
# Unescape the JSON string if it's a string
if isinstance(value, str):
unescaped_value = json.loads(json.dumps(value))
parsed_value = json.loads(unescaped_value)
else:
parsed_value = value
return json.dumps(parsed_value, indent=4)
except (json.JSONDecodeError, TypeError):
return value
def format_list(input_list):
def json_serialize(item):
if isinstance(item, uuid.UUID):
return json.dumps(str(item), indent=4)
if isinstance(item, SQLModel):
item = item.dict() # Convert SQLModel instance to dictionary
elif isinstance(item, dict):
return json.dumps(pretty_json_func(item), indent=4)
elif isinstance(item, list):
return format_list(item)
else:
return json.dumps(item, indent=4)
formatted_list = "[\n" + ",\n".join(" " + json_serialize(item).replace("\n", "\n ") for item in input_list) + "\n]"
return formatted_list
def pretty_json_func(data):
if isinstance(data, SQLModel):
data = data.dict() # Convert SQLModel instance to dictionary
if isinstance(data, dict):
formatted_data = {}
for key, value in data.items():
if isinstance(value, uuid.UUID): # Convert UUIDs to string
formatted_data[key] = str(value)
elif isinstance(value, dict): # Recursively handle dictionary values
formatted_data[key] = pretty_json_func(value)
elif isinstance(value, list): # Special handling for lists
formatted_data[key] = format_list(value)
elif key.endswith("_json"): # Handle keys that end with '_json'
formatted_data[key] = parse_and_format(value)
else: # Handle other types of values
formatted_data[key] = value
return json.dumps(formatted_data, indent=4)
elif isinstance(data, list): # Top-level list handling
formatted_list = []
for item in data:
if isinstance(item, str):
try:
parsed_item = json.loads(item)
formatted_item = json.dumps(parsed_item, indent=4)
formatted_list.append(formatted_item)
except json.JSONDecodeError:
formatted_list.append(json.dumps(item)) # Wrap the string in quotes
elif isinstance(item, dict):
formatted_list.append(json.dumps(pretty_json_func(item), indent=4))
elif isinstance(item, uuid.UUID):
formatted_list.append(json.dumps(str(item))) # Convert UUID to string and wrap in quotes
else:
formatted_list.append(json.dumps(item))
return "[\n" + ",\n".join(" " + item for item in formatted_list) + "\n]"
elif isinstance(data, str): # Handle string type data separately
return parse_and_format(data)
else:
return json.dumps(data) # Convert other types to JSON string
def log_action_with_payload(action_string, payload_name, json_payload):
logger.info(f"Now {action_string} {payload_name} with payload:\n{pretty_json_func(json_payload)}")
def transform_credit_pack_purchase_request_response(result: dict) -> dict:
transformed_result = result.copy()
fields_to_convert = [
"list_of_potentially_agreeing_supernodes",
"list_of_blacklisted_supernode_pastelids",
"list_of_supernode_pastelids_agreeing_to_credit_pack_purchase_terms",
"list_of_supernode_pastelids_agreeing_to_credit_pack_purchase_terms_selected_for_signature_inclusion",
"selected_agreeing_supernodes_signatures_dict",
]
for field in fields_to_convert:
if field in transformed_result:
transformed_result[field] = json.dumps(transformed_result[field])
return transformed_result
async def send_to_address_func(address, amount, comment="", comment_to="", subtract_fee_from_amount=False):
"""
Send an amount to a given Pastel address.
Args:
address (str): The Pastel address to send to.
amount (float): The amount in PSL to send.
comment (str, optional): A comment used to store what the transaction is for.
This is not part of the transaction, just kept in your wallet.
Defaults to an empty string.
comment_to (str, optional): A comment to store the name of the person or organization
to which you're sending the transaction. This is not part of
the transaction, just kept in your wallet. Defaults to an empty string.
subtract_fee_from_amount (bool, optional): Whether to deduct the fee from the amount being sent.
If True, the recipient will receive less Pastel than you enter
in the amount field. Defaults to False.
Returns:
str: The transaction ID if successful, None otherwise.
Example:
send_to_address_func("PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n", 0.1, "donation", "seans outpost", True)
"""
global rpc_connection
try:
result = await rpc_connection.sendtoaddress(address, amount, comment, comment_to, subtract_fee_from_amount)
return result
except Exception as e:
logger.error(f"Error in send_to_address_func: {e}")
return None
async def send_many_func(amounts, min_conf=1, comment="", change_address=""):
"""
Send multiple amounts to multiple recipients.
Args:
amounts (dict): A dictionary representing the amounts to send.
Each key is the Pastel address, and the corresponding value is the amount in PSL to send.
min_conf (int, optional): The minimum number of confirmations required for the funds to be used. Defaults to 1.
comment (str, optional): A comment to include with the transaction. Defaults to an empty string.
change_address (str, optional): The Pastel address to receive the change from the transaction. Defaults to an empty string.
Returns:
str: The transaction ID if successful, None otherwise.
Example:
amounts = {
"PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n": 0.01,
"PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n": 0.02
}
send_many_func(amounts, min_conf=6, comment="testing", change_address="PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n")
"""
global rpc_connection
try:
# Set the 'fromaccount' parameter to an empty string
from_account = ""
# Call the 'sendmany' RPC method
result = await rpc_connection.sendmany(from_account, amounts, min_conf, comment, [""], change_address)
return result
except Exception as e:
logger.error(f"Error in send_many_func: {e}")
return None
async def z_send_many_with_change_to_sender_func(from_address, amounts, min_conf=1, fee=0.1):
"""
Send multiple amounts from a given address to multiple recipients.
Args:
from_address (str): The taddr or zaddr to send the funds from.
amounts (list): A list of dictionaries representing the amounts to send.
Each dictionary should have the following keys:
- "address" (str): The taddr or zaddr to send funds to.
- "amount" (float): The amount in PSL to send.
- "memo" (str, optional): If the address is a zaddr, raw data represented in hexadecimal string format.
min_conf (int, optional): The minimum number of confirmations required for the funds to be used. Defaults to 1.
fee (float, optional): The fee amount to attach to the transaction. Defaults to 0.1.
Returns:
str: The operation ID if successful, None otherwise.
Example:
amounts = [
{"address": "PzSSk8QJFqjo133DoFZvn9wwcCxt5RYeeLFJZRgws6xgJ3LroqRgXKNkhkG3ENmC8oe82UTr3PHcQB9mw7DSLXhyP6atQQ5", "amount": 5.0},
{"address": "PzXFZjHx6KzqNpAaMewvrUj8x1fvj7UZLFZYEuN8jJJuQhSfPYaVoAF1qrFSh3q2zUmCg7QkfQr4nAVrdovwKA4KDwPp5g", "amount": 10.0, "memo": "0xabcd"}
]
z_send_many_with_change_to_sender_func("PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n", amounts, min_conf=2, fee=0.05)
"""
global rpc_connection
try:
result = await rpc_connection.z_sendmanywithchangetosender(from_address, amounts, min_conf, fee)
return result
except Exception as e:
logger.error(f"Error in z_send_many_with_change_to_sender_func: {e}")
return None
async def z_get_operation_status_func(operation_ids=None):
"""
Get the status of one or more operations.
Args:
operation_ids (list, optional): A list of operation IDs to query the status for.
If not provided, all known operations will be examined.
Returns:
list: A list of JSON objects containing the operation status and any associated result or error data.
Example:
operation_ids = ["opid-1234", "opid-5678"]
z_get_operation_status_func(operation_ids)
"""
global rpc_connection
try:
if operation_ids is None:
operation_ids = []
result = await rpc_connection.z_getoperationstatus(operation_ids)
return result
except Exception as e:
logger.error(f"Error in z_get_operation_status_func: {e}")
return None
async def check_psl_address_balance_alternative_func(address_to_check):
global rpc_connection
address_amounts_dict = await rpc_connection.listaddressamounts()
# Convert the dictionary into a list of dictionaries, each representing a row
data = [{'address': address, 'amount': amount} for address, amount in address_amounts_dict.items()]
# Create the DataFrame from the list of dictionaries
address_amounts_df = pd.DataFrame(data)
# Filter the DataFrame for the specified address
address_amounts_df_filtered = address_amounts_df[address_amounts_df['address'] == address_to_check]
# Calculate the sum of the 'amount' column for the filtered DataFrame
balance_at_address = address_amounts_df_filtered['amount'].sum()
return balance_at_address
async def create_and_fund_new_psl_credit_tracking_address(amount_of_psl_to_fund_address_with: float):
global rpc_connection
new_credit_tracking_address = await rpc_connection.getnewaddress()
txid = await send_to_address_func(new_credit_tracking_address, amount_of_psl_to_fund_address_with, comment="Funding new credit tracking address ", comment_to="", subtract_fee_from_amount=False)
return new_credit_tracking_address, txid
async def check_psl_address_balance_func(address_to_check):
global rpc_connection
balance_at_address = await rpc_connection.z_getbalance(address_to_check)
return balance_at_address
async def check_if_address_is_already_imported_in_local_wallet(address_to_check):
global rpc_connection
address_amounts_dict = await rpc_connection.listaddressamounts()
# Convert the dictionary into a list of dictionaries, each representing a row
data = [{'address': address, 'amount': amount} for address, amount in address_amounts_dict.items()]
# Create the DataFrame from the list of dictionaries
address_amounts_df = pd.DataFrame(data)
# Filter the DataFrame for the specified address
address_amounts_df_filtered = address_amounts_df[address_amounts_df['address'] == address_to_check]
if address_amounts_df_filtered.empty:
return False
return True
async def get_and_decode_raw_transaction(txid: str, blockhash: str = None) -> dict:
"""
Retrieves and decodes detailed information about a specified transaction
from the Pastel network using the RPC calls.
Args:
txid (str): The transaction id to fetch and decode.
blockhash (str, optional): The block hash to specify which block to search for the transaction.
Returns:
dict: A dictionary containing detailed decoded information about the transaction.
"""
global rpc_connection
try:
# Retrieve the raw transaction data
raw_tx_data = await rpc_connection.getrawtransaction(txid, 0, blockhash)
if not raw_tx_data:
logger.error(f"Failed to retrieve raw transaction data for {txid}")
return {}
# Decode the raw transaction data
decoded_tx_data = await rpc_connection.decoderawtransaction(raw_tx_data)
if not decoded_tx_data:
logger.error(f"Failed to decode raw transaction data for {txid}")
return {}
# Log the decoded transaction details
return decoded_tx_data
except Exception as e:
logger.error(f"Error in get_and_decode_transaction for {txid}: {e}")
return {}
async def get_transaction_details(txid: str, include_watchonly: bool = False) -> dict:
"""
Fetches detailed information about a specified transaction from the Pastel network using the RPC call.
Args:
txid (str): The transaction id to fetch details for.
include_watchonly (bool, optional): Whether to include watchonly addresses in the details. Defaults to False.
Returns:
dict: A dictionary containing detailed information about the transaction.
"""
global rpc_connection
try:
# Call the 'gettransaction' RPC method with the provided txid and includeWatchonly flag
transaction_details = await rpc_connection.gettransaction(txid, include_watchonly)
# Log the retrieved transaction details
return transaction_details
except Exception as e:
logger.error(f"Error retrieving transaction details for {txid}: {e}")
return {}
async def send_tracking_amount_from_control_address_to_burn_address_to_confirm_inference_request(
inference_request_id: str,
credit_usage_tracking_psl_address: str,
credit_usage_tracking_amount_in_psl: float,
burn_address: str,
):
"""
Send the tracking amount from the control address to the burn address to confirm an inference request.
Args:
inference_request_id (str): The ID of the inference request.
credit_usage_tracking_psl_address (str): The control address to send the tracking amount from.
credit_usage_tracking_amount_in_psl (float): The tracking amount in PSL to send.
burn_address (str): The burn address to send the tracking amount to.
Returns:
str: The transaction ID (txid) if the transaction is successfully confirmed, None otherwise.
Example:
send_tracking_amount_from_control_address_to_burn_address_to_confirm_inference_request(
inference_request_id="abc123",
credit_usage_tracking_psl_address="PtczsZ91Bt3oDPDQotzUsrx1wjmsFVgf28n",
credit_usage_tracking_amount_in_psl=0.5,
burn_address="PtpasteLBurnAddressXXXXXXXXXXbJ5ndd"
)
"""
try:
amounts = {
burn_address: credit_usage_tracking_amount_in_psl
}
txid = await send_many_func(
amounts=amounts,
min_conf=0,
comment="Confirmation tracking transaction for inference request with request_id " + inference_request_id,
change_address=credit_usage_tracking_psl_address
)
if txid is not None:
transaction_info = await rpc_connection.gettransaction(txid)
if transaction_info:
return txid
else:
logger.error(f"No transaction info found for TXID: {txid} to confirm inference request {inference_request_id}")
return None
else:
logger.error(f"Failed to send {credit_usage_tracking_amount_in_psl} PSL from {credit_usage_tracking_psl_address} to {burn_address} to confirm inference request {inference_request_id}")
return None
except Exception as e:
logger.error(f"Error in send_tracking_amount_from_control_address_to_burn_address_to_confirm_inference_request: {e}")
raise
async def import_address_func(address: str, label: str = "", rescan: bool = False) -> None:
"""
Import an address or script (in hex) that can be watched as if it were in your wallet but cannot be used to spend.
Args:
address (str): The address to import.
label (str, optional): An optional label for the address. Defaults to an empty string.
rescan (bool, optional): Rescan the wallet for transactions. Defaults to False.
Returns:
None
Raises:
RPCError: If an error occurs during the RPC call.
Example:
import_address_func("myaddress", "testing", False)
"""
global rpc_connection
try:
await rpc_connection.importaddress(address, label, rescan)
except Exception as e:
logger.error(f"Error importing address: {address}. Error: {e}")
async def compress_data_with_zstd_func(input_data):
zstd_compression_level = 20
zstandard_compressor = zstd.ZstdCompressor(level=zstd_compression_level, write_content_size=True, write_checksum=True)
zstd_compressed_data = zstandard_compressor.compress(input_data)
zstd_compressed_data__base64_encoded = base64.b64encode(zstd_compressed_data).decode('utf-8')
return zstd_compressed_data, zstd_compressed_data__base64_encoded
async def decompress_data_with_zstd_func(compressed_input_data):
zstd_decompressor = zstd.ZstdDecompressor()
zstd_decompressed_data = zstd_decompressor.decompress(compressed_input_data)
return zstd_decompressed_data
async def sign_message_with_pastelid_func(pastelid, message_to_sign, passphrase) -> str:
global rpc_connection
results_dict = await rpc_connection.pastelid('sign', message_to_sign, pastelid, passphrase, 'ed448')
return results_dict['signature']
#____________________________________________________________________________________________________________________________
# SQLModel model classes based on the server's database_code.py
# Messaging related models:
class Message(SQLModel, table=True):
id: Optional[uuid.UUID] = Field(default_factory=uuid.uuid4, primary_key=True, index=True)
sending_sn_pastelid: str = Field(index=True)
receiving_sn_pastelid: str = Field(index=True)
sending_sn_txid_vout: str = Field(index=True)
receiving_sn_txid_vout: str = Field(index=True)
message_type: str = Field(index=True)
message_body: str = Field(sa_column=Column(JSON))
signature: str
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
def __repr__(self):
return f"<Message(id={self.id}, sending_sn_pastelid='{self.sending_sn_pastelid}', receiving_sn_pastelid='{self.receiving_sn_pastelid}', message_type='{self.message_type}', timestamp='{self.timestamp}')>"
class Config:
arbitrary_types_allowed = True # Allow arbitrary types
json_schema_extra = {
"example": {
"sending_sn_pastelid": "jXYJud3rmrR1Sk2scvR47N4E4J5Vv48uCC6se2nUHyfSJ17wacN7rVZLe6Sk",
"receiving_sn_pastelid": "jXa1s9mKDr4m6P8s7bKK1rYFgL7hkfGMLX1NozVSX4yTnfh9EjuP",
"sending_sn_txid_vout": "0x1234...:0",
"receiving_sn_txid_vout": "0x5678...:0",
"message_type": "text",
"message_body": "Hello, how are you?",
"signature": "0xabcd...",
"timestamp": "2023-06-01T12:00:00Z"
}
}
class UserMessage(SQLModel, table=True):
id: Optional[uuid.UUID] = Field(default_factory=uuid.uuid4, primary_key=True, index=True)
from_pastelid: str = Field(index=True)
to_pastelid: str = Field(index=True)
message_body: str = Field(sa_column=Column(JSON))
message_signature: str
timestamp: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), index=True)
class Config:
arbitrary_types_allowed = True # Allow arbitrary types
json_schema_extra = {
"example": {
"from_pastelid": "jXYJud3rmrR1Sk2scvR47N4E4J5Vv48uCC6se2nUHyfSJ17wacN7rVZLe6Sk",
"to_pastelid": "jXa1s9mKDr4m6P8s7bKK1rYFgL7hkfGMLX1NozVSX4yTnfh9EjuP",
"message_body": "Hey, let's meet up!",
"message_signature": "0xdef0...",
"timestamp": "2023-06-01T12:30:00Z"
}
}
# Credit pack purchasing/provisioning related models:
class CreditPackPurchaseRequest(SQLModel, table=True):
id: uuid.UUID = Field(default_factory=uuid.uuid4, index=True, nullable=True)
sha3_256_hash_of_credit_pack_purchase_request_fields: str = Field(primary_key=True, index=True)
requesting_end_user_pastelid: str = Field(index=True)
requested_initial_credits_in_credit_pack: int
list_of_authorized_pastelids_allowed_to_use_credit_pack: str = Field(sa_column=Column(JSON))
credit_usage_tracking_psl_address: str = Field(index=True)
request_timestamp_utc_iso_string: str
request_pastel_block_height: int
credit_purchase_request_message_version_string: str
requesting_end_user_pastelid_signature_on_request_hash: str
class Config:
json_schema_extra = {
"example": {
"id": "79df343b-4ad3-435c-800e-e59e616ff84d",
"requesting_end_user_pastelid": "jXYJud3rmrR1Sk2scvR47N4E4J5Vv48uCC6se2nUHyfSJ17wacN7rVZLe6Sk",
"requested_initial_credits_in_credit_pack": 1000,
"list_of_authorized_pastelids_allowed_to_use_credit_pack": ["jXYJud3rmrR1Sk2scvR47N4E4J5Vv48uCC6se2nUHyfSJ17wacN7rVZLe6Sk"],
"credit_usage_tracking_psl_address": "tPj2wX5mjQErTju6nueVRkxGMCPuMkLn8CWdViJ38m9Wf6PBK5jV",
"request_timestamp_utc_iso_string": "2023-06-01T12:00:00Z",
"request_pastel_block_height": 123456,
"credit_purchase_request_message_version_string": "1.0",
"sha3_256_hash_of_credit_pack_purchase_request_fields": "0x5678...",
"requesting_end_user_pastelid_signature_on_request_hash": "0xabcd..."
}
}
class CreditPackPurchaseRequestRejection(SQLModel, table=True):
sha3_256_hash_of_credit_pack_purchase_request_fields: str = Field(primary_key=True, index=True)
credit_pack_purchase_request_fields_json_b64: str
rejection_reason_string: str
rejection_timestamp_utc_iso_string: str
rejection_pastel_block_height: int
credit_purchase_request_rejection_message_version_string: str
responding_supernode_pastelid: str = Field(index=True)
sha3_256_hash_of_credit_pack_purchase_request_rejection_fields: str = Field(unique=True, index=True)
responding_supernode_signature_on_credit_pack_purchase_request_rejection_hash: str
class Config:
json_schema_extra = {
"example": {
"sha3_256_hash_of_credit_pack_purchase_request_fields": "0x1234...",
"credit_pack_purchase_request_fields_json_b64": 'eyJwcm9tcHQiOiAiSGVsbG8sIGhvdyBhcmUgeW91PyJ9',
"rejection_reason_string": "Invalid credit usage tracking PSL address",
"rejection_timestamp_utc_iso_string": "2023-06-01T12:10:00Z",
"rejection_pastel_block_height": 123457,
"credit_purchase_request_rejection_message_version_string": "1.0",
"responding_supernode_pastelid": "jXYJud3rmrR1Sk2scvR47N4E4J5Vv48uCC6se2nUHyfSJ17wacN7rVZLe6Sk",
"sha3_256_hash_of_credit_pack_purchase_request_rejection_fields": "0xabcd...",