-
Notifications
You must be signed in to change notification settings - Fork 5
/
rosettaapi_flask.py
1136 lines (1038 loc) · 37.2 KB
/
rosettaapi_flask.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
# Verus Network Data API
# Used to provide data for rosetta integration
# Coded by Shreyas from the verus community
# Coinbase Docs: https://docs.cloud.coinbase.com/rosetta/docs/welcome
# Github: https://github.com/Shreyas-ITB/VerusRosettaIntegration
# Module imports.
from flask import Flask, jsonify, request
import os
import requests
from dotenv import load_dotenv, find_dotenv
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address
import gevent.pywsgi
import uuid, json
# Initializing Flask module and getting the env variable values.
app = Flask(__name__)
load_dotenv(find_dotenv())
RPCURL = os.environ.get("RPCURL")
RPCUSER = os.environ.get("RPCUSER")
RPCPASS = os.environ.get("RPCPASS")
PORT = os.environ.get("DATAPIPORT")
RUN_PRODUCTION = os.environ.get("RUN_PRODUCTION")
NUM_BLOCKS = os.environ.get("NUM_BLOCKS")
# Initialize the rate limiter only in production mode
if RUN_PRODUCTION == "True" or RUN_PRODUCTION == "true":
limiter = Limiter(
get_remote_address,
app=app,
default_limits=["200 per day", "50 per hour"],
storage_uri="memory://",
)
else:
None
# Create a dictionary to save all the balance related data for temporary use
baldata = []
# Function definitions.
# Helps to send the request to the RPC.
def send_request(method, url, headers, data):
response = requests.request(method, url, headers=headers, json=data, auth=(RPCUSER, RPCPASS))
return response.json()
# Fetches the network options from the RPC.
def get_network_options():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getnetworkinfo",
"params": []
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
# Parse the response JSON and extract relevant information
network_status = {
"version": response_json["result"]["version"],
"subversion": response_json["result"]["subversion"],
"protocolversion": response_json["result"]["protocolversion"],
"localservices": response_json["result"]["localservices"],
"timeoffset": response_json["result"]["timeoffset"],
"connections": response_json["result"]["connections"],
"networks": [
{
"name": network["name"],
"limited": network["limited"],
"reachable": network["reachable"],
"proxy": network.get("proxy", "")
}
for network in response_json["result"]["networks"]
],
"relayfee": response_json["result"]["relayfee"],
"localaddresses": [
{
"address": address["address"],
"port": address["port"],
"score": address["score"]
}
for address in response_json["result"]["localaddresses"]
],
"warnings": response_json["result"].get("warnings", "")
}
return network_status
else:
# Handle the error case
return None
# Helps to create a new verus address
def getnewaddress():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getnewaddress",
"params": []
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
return response_json
# Helps to create an unsigned raw transaction, takes in a few arguments to create a transaction.
def create_unsigned_transaction(txid, vout, address, amount):
# Define the JSON-RPC request payload
request_data = {
"jsonrpc": "1.0",
"id": "flask-app",
"method": "createrawtransaction",
"params": [
[{"txid": txid, "vout": vout}],
{address: amount}
]
}
try:
result = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, request_data)
unsigned_transaction = result.get("transaction")
return unsigned_transaction
except Exception as e:
raise Exception(f"Failed to create unsigned transaction: {str(e)}")
# Helps to parse, verify and sign the unsigned raw transaction, takes in an argument called hex.
def parse_and_sign_transaction(unsigned_hex):
# Define the JSON-RPC request payload
request_data = {
"jsonrpc": "1.0",
"id": "flask-app",
"method": "signrawtransaction",
"params": [unsigned_hex]
}
try:
result = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, request_data)
return result
except Exception as e:
raise Exception(f"Failed to parse and sign transaction: {str(e)}")
# Helps to broadcast a signed raw transaction into the network, takes in an argument called hex (signed hex).
def submit_signed_transaction(signed_hex):
request_data = {
"jsonrpc": "1.0",
"id": "flask-app",
"method": "sendrawtransaction",
"params": [signed_hex]
}
try:
result = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, request_data)
return result
except Exception as e:
raise Exception(f"Failed to submit signed transaction: {str(e)}")
# Fetches the network status from the RPC.
def get_network_status():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockchaininfo",
"params": []
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
# Parse the response JSON and extract relevant information
blockchain_info = response_json["result"]
network_options = {
"chain": blockchain_info["chain"],
"name": blockchain_info["name"],
"chainid": blockchain_info["chainid"],
}
return network_options
else:
# Handle the error case
return None
# Get the current block identifier
def getcurrentblockidentifier():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getbestblockhash",
"params": []
}
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
return response_json['result']
# Get genesis block identifier
def getgenesisblockidentifier():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockhash",
"params": [0]
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
resp = get_block_info(response_json['result'])
resp = resp['height']
return response_json['result'], resp
# Get current block height
def getcurrentblockheight():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblockchaininfo",
"params": []
}
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
return int(response_json["result"]["blocks"])
def getpeerinfo():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getpeerinfo",
"params": []
}
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
formatted_data = []
for item in response_json['result']:
item_id = item.pop('id') # Extract and remove the 'id' key from the dictionary
formatted_data.append({'id': item_id, 'data': item})
formatted_json = json.dumps(formatted_data, indent=2)
formatted_data = json.loads(formatted_json)
ids = [item['id'] for item in formatted_data]
data_without_id = [item['data'] for item in formatted_data]
return ids
# Gets the block information, takes in an argument called identifier which should be a transaction ID or a block number.
def get_block_info(identifier):
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getblock",
"params": [f"{identifier}"]
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
block_info = response_json["result"]
return block_info
elif "error" in response_json:
return response_json["error"]["message"]
else:
return None
# Get current block identifier height from a hash
def getcurrentblockidentifierheight(hash):
resp = get_block_info(hash)
resp = resp['height']
return resp
# Get the syncing status
def getsyncstatus():
# Calculate the block sync status
hash0 = getcurrentblockidentifier()
height0 = getcurrentblockidentifierheight(hash0)
height = getcurrentblockheight()
calc = int(height) / int(height0)
if calc == 1:
syncstat = "Synced"
boolean = True
else:
syncstat = "Out of sync, Syncing.."
boolean = False
return syncstat, height0, height, boolean
# Gets the transaction information, takes in an argument called transaction ID.
def get_transaction_info(txid):
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getrawtransaction",
"params": [txid, 1]
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
transaction_info = response_json["result"]
return transaction_info
elif "error" in response_json:
return response_json["error"]["message"]
else:
return None
# Gets all the unconfirmed transactions from the mempool.
def get_mempool_info():
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getrawmempool",
"params": []
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
mempool_info = response_json["result"]
return mempool_info
else:
# Handle the error case
return None
# Get transaction amount from a transaction id
def gettxamt(txid):
txid = str(txid)
cleaned_string = txid.replace("[", "").replace("]", "").replace("'", "")
try:
# resp = requests.get(f"https://explorer.verus.io/ext/gettx/{cleaned_string}")
# amount = resp.json()['tx']['vin'][0]['amount']
# addr1 = resp.json()['tx']['vout'][0]['addresses']
# try:
# addr2 = resp.json()['tx']['vout'][1]['addresses']
# except IndexError:
# addr2 = addr1
transaction = get_transaction_info(cleaned_string)
# Extract valueSat from each vout
valuesats = [vout["valueSat"] for vout in transaction["vout"]]
# Extract addresses from scriptPubKey for the first two vouts
addresses = [vout["scriptPubKey"]["addresses"] for vout in transaction["vout"][:2]]
amount = valuesats
addr1 = addresses[0][0]
try:
addr2 = addresses[1][0]
except IndexError:
addr2 = addr1
except:
amount = "00000000"
addr1 = "iCRUc98jcJCP3JEntuud7Ae6eeaWtfZaZK"
addr2 = "iCRUc98jcJCP3JEntuud7Ae6eeaWtfZaZK"
return amount, addr1, addr2
# Gets the balance of an address, takes in an argument called address.
def get_address_balance(address):
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getaddressbalance",
"params": [{"addresses": [address]}]
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
balance_info = response_json["result"]
return balance_info
elif "error" in response_json:
return response_json["error"]["message"]
else:
return None
# Gets the unspent transactions of an address, takes in an argument called address.
def get_address_utxos(address):
# Define the JSON-RPC request payload
payload = {
"jsonrpc": "1.0",
"id": "curltest",
"method": "getaddressutxos",
"params": [{"addresses": [address]}]
}
# Make the request using the provided function
response_json = send_request("POST", RPCURL, {'content-type': 'text/plain;'}, payload)
# Check if the request was successful
if "result" in response_json:
utxos = response_json["result"]
return utxos
elif "error" in response_json:
return response_json["error"]["message"]
else:
return None
# API Endpoints
# Endpoint that is used to get the network lists.
@app.route('/network/list', methods=['POST'])
def network_list():
# request chainid from the vrsc daemon
chain = get_network_status()
newchainid = chain["chainid"]
netinfo = {
"network_identifiers":
[
{
"blockchain":"VRSC",
"network": newchainid,
"sub_network_identifier":
{
"network": newchainid
}
}
]
}
# error message for /network/list endpoint
errnetinfo = {
"code": 12,
"message": "Invalid account format",
"description": "This error is returned when the requested AccountIdentifier is improperly formatted.",
"retriable": "boolean",
"details": None
}
try:
return jsonify(netinfo), 200
except:
return jsonify(errnetinfo), 500
# Endpoint that is used to get the network status.
@app.route('/network/status', methods=['POST'])
def network_status():
data = request.get_json()
if data:
ids = getpeerinfo()
hashhe = get_block_info(1500)
hash = getcurrentblockidentifier()
indexval = getcurrentblockidentifierheight(hash)
ghash, gindex = getgenesisblockidentifier()
syncstat, height0, height, boolean = getsyncstatus()
if RUN_PRODUCTION == "True" or RUN_PRODUCTION == "true":
hash = hash
indexval = indexval
else:
hash = hash
indexval = indexval
timestamp = hashhe['time']
milliseconds = timestamp * 1000
info = {
"current_block_identifier": {
"index": indexval,
"hash": hash
},
"current_block_timestamp": milliseconds,
"genesis_block_identifier": {
"index": gindex,
"hash": ghash
},
"oldest_block_identifier": {
"index": gindex,
"hash": ghash
},
"sync_status": {
"current_index": height,
"target_index": height0,
"stage": syncstat,
"synced": boolean
},
"peers": [
{
"peer_id": str(ids),
"metadata": None
}
]
}
return info, 200
else:
return jsonify({
"code": 500,
"message": "Failed to fetch network version",
"description": "There was an error while fetching network version from the RPC"
}), 500
# Endpoint that is used to get network options.
@app.route('/network/options', methods=['POST'])
def network_options():
nodeversion = get_network_options()
chain = get_network_status()
newchainid = chain["chainid"]
try:
# Add the specified text to the output
versioninfo = {
"version": {
"rosetta_version": "1.2.5",
"node_version": f'{nodeversion["version"]}',
"middleware_version": "0.2.7",
"metadata": None
},
"allow": {
"operation_statuses": [
{
"status": "confirmed",
"successful": True
},
{
"status": "unconfirmed",
"successful": True
},
{
"status": "processing",
"successful": True
},
{
"status": "pubkey",
"successful": True
},
],
"operation_types": [
"Transfer",
"mined",
"minted"
"pubkey"
],
"errors": [
{
"code": 12,
"message": "Invalid account format",
"description": "This error is returned when the requested AccountIdentifier is improperly formatted.",
"retriable": True,
"details": None
},
{
"code": 14,
"message": "Failed to fetch network version",
"description": "There was an error while fetching network version from the RPC",
"retriable": True,
"details": None
},
{
"code": 16,
"message": "Failed to fetch block information",
"description": "There was an error while fetching block information from the RPC",
"retriable": True,
"details": None
},
{
"code": 18,
"message": "Failed to fetch transaction information",
"description": "There was an error while fetching transaction information from the RPC",
"retriable": True,
"details": None
},
{
"code": 20,
"message": "Failed to fetch mempool information",
"description": "There was an error while fetching mempool information from the RPC",
"retriable": True,
"details": None
},
{
"code": 22,
"message": "Failed to fetch balance information",
"description": "There was an error while fetching balance information from the API",
"retriable": True,
"details": None
},
{
"code": 24,
"message": "Failed to fetch UTXOs",
"description": "There was an error while fetching UTXOs from the API",
"retriable": True,
"details": None
},
{
"code": 26,
"message": "Failed to create new verus wallet address",
"description": "There was an error while fetching the information from the Local RPC",
"retriable": True,
"details": None
}
],
"historical_balance_lookup": True,
"timestamp_start_index": 1231006505,
"call_methods": [
"POST"
],
"balance_exemptions": [
{
"sub_account_address": newchainid,
"currency": {
"symbol": "VRSC",
"decimals": 8,
"metadata": None
},
"exemption_type": "dynamic"
}
],
"mempool_coins": False
}
}
return jsonify(versioninfo), 200
except Exception as e:
return jsonify({
"code": 500,
"message": f"Failed to fetch network version: {e}",
"description": "There was an error while fetching network version from the RPC"
}), 500
# Endpoint that is used to get the information of a block.
@app.route('/block', methods=['POST'])
def block_info():
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
block_identifier = data.get("block_identifier")
try:
index_value = data['block_identifier']['index']
except:
index_value = data['index']
if not block_identifier:
block_identifier = data.get("index")
try:
newblkidentifier = block_identifier['index']
data = get_block_info(newblkidentifier)
except:
data = get_block_info(block_identifier)
# data = json.dumps(block_data)
try:
txid = data['tx']
except TypeError:
txid = None
hash_value = data['hash']
height = data['height']
time = data['time']
blocktype = data['blocktype']
confirmations = data['confirmations']
if int(confirmations) > 15:
status = "confirmed"
else:
status = "unconfirmed"
value, addr1, addr2 = gettxamt(txid)
chain = get_network_status()
newchainid = chain["chainid"]
if index_value == 0:
newindexv = 0
else:
newindexv = index_value - 1
parent_hash = get_block_info(newindexv)
parent_hash = parent_hash['hash']
RUN_PRODUCTION = os.environ.get("RUN_PRODUCTION")
if RUN_PRODUCTION == True or RUN_PRODUCTION == "true":
value = int(str(value).replace(".", ""))
else:
value = "00000000"
if data:
data = {
"block": {
"block_identifier": {
"index": index_value,
"hash": hash_value
},
"parent_block_identifier": {
"index": newindexv,
"hash": parent_hash
},
"timestamp": time,
"transactions": [
{
"transaction_identifier": {
"hash": str(txid[:1])
},
"operations": [
{
"operation_identifier": {
"index": 0,
"network_index": 0
},
"related_operations": [
{
"index": -3,
"network_index": 0
}
],
"type": "Transfer",
"status": status,
"account": {
"address": addr1,
"sub_account": {
"address": addr2,
"metadata": None
},
"metadata": None
},
"amount": {
"value": f"{value}",
"currency": {
"symbol": "VRSC",
"decimals": 8,
"metadata": None
},
"metadata": None
},
"coin_change": {
"coin_identifier": {
"identifier": newchainid
},
"coin_action": "coin_spent"
},
"metadata": None
}
],
"related_transactions": [
{
"network_identifier": {
"blockchain": "VRSC",
"network": newchainid,
"sub_network_identifier":
{
"network": newchainid,
"metadata": None
}
},
"transaction_identifier": {
"hash": str(txid[:1])
},
"direction": "forward"
}
],
"metadata": None
}
],
"metadata": None
},
"other_transactions": [
{
"hash": str(txid[:1])
}
]
}
return jsonify(data), 200
else:
return jsonify({
"code": 500,
"message": "Failed to fetch block information",
"description": "There was an error while fetching block information from the RPC"
}), 500
# Endpoint that is used to get the information about a block transaction.
@app.route('/block/transaction', methods=['POST'])
def block_transaction_info():
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
# Parse JSON data
parsed_data = json.loads(json.dumps(data))
# Access the desired hash value
try:
chain = get_network_status()
newchainid = chain["chainid"]
transaction_hash = parsed_data['transaction_identifier']['hash'][2:-2] #Remove the square brackets and quotes
if transaction_hash == "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b":
txid = "4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b"
if RUN_PRODUCTION == "True" or RUN_PRODUCTION == "true":
value = "500000000"
else:
value = "00000000"
address = "RJJBTXXfgE5DjiPQpZSnYrQe73NhrBZ3ao"
status = "confirmed"
else:
# Split the variable by comma, strip whitespace, and remove single quotes
strings = [s.strip().strip("'") for s in transaction_hash.split(',')]
# Check the length of the list
if len(strings) > 1:
result = strings[0] # Return the first string
else:
result = transaction_hash.strip("'")
data = get_transaction_info(result)
# Extracting values
txid = data["txid"]
if RUN_PRODUCTION == "True" or RUN_PRODUCTION == "true":
value = data["vout"][0]["valueSat"]
else:
value = "00000000"
try:
address = data["vout"][0]["scriptPubKey"]["addresses"]
except:
address = "RJJBTXXfgE5DjiPQpZSnYrQe73NhrBZ3ao"
confirmations = data["confirmations"]
# Checking confirmations and setting status
status = "confirmed" if confirmations > 100 else "unconfirmed"
senddata = {
"transaction": {
"transaction_identifier": {
"hash": str(txid)
},
"operations": [
{
"operation_identifier": {
"index": 0,
"network_index": 0
},
"related_operations": [
{
"index": -3,
"network_index": 0
}
],
"type": "Transfer",
"status": status,
"account": {
"address": str(address),
"sub_account": {
"address": str(address),
"metadata": None
},
"metadata": None
},
"amount": {
"value": f"{value}0",
"currency": {
"symbol": "VRSC",
"decimals": 8,
"metadata": None
},
"metadata": None
},
"coin_change": {
"coin_identifier": {
"identifier": f"{txid}:0"
},
"coin_action": "coin_spent"
},
"metadata": None
}
],
"related_transactions": [
{
"network_identifier": {
"blockchain": "VRSC",
"network": newchainid,
"sub_network_identifier": {
"network": newchainid,
"metadata": None
}
},
"transaction_identifier": {
"hash": str(txid)
},
"direction": "forward"
}
],
"metadata": None
}
}
return jsonify(senddata), 200
except Exception as e:
return jsonify({
"code": 500,
"message": f"Failed to fetch the transaction information: {e}",
"description": "There was an error while fetching transaction information from the RPC"
}), 500
# Endpoint that is used to fetch mempool transactions.
@app.route('/mempool', methods=['POST'])
def mempool_info():
mempool_data = get_mempool_info()
if mempool_data:
data = {
"transaction_identifiers": [
{
"hash": mempool_data
}
]
}
return jsonify(data), 200
else:
return jsonify({
"code": 500,
"message": "Failed to fetch mempool information",
"description": "There was an error while fetching mempool information from the RPC"
}), 500
# Endpoint that is used to fetch an account's balance.
@app.route('/account/balance', methods=['POST'])
def account_balance():
global baldata
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
address = data['account_identifier']['address']
balance_data = get_address_balance(address)
baldata.append(balance_data)
try:
value_satt = baldata[0]['balance']
except:
value_satt = "00000000"
value_sat = int(str(value_satt)[:8])
index_value = data['block_identifier']['index']
data = get_block_info(index_value)
if RUN_PRODUCTION == "True" or RUN_PRODUCTION == "true":
value_sat = value_sat
else:
value_sat = "00000000"
hash = data['hash']
data = {
"block_identifier": {
"index": index_value,
"hash": str(hash)
},
"balances": [
{
"value": f"{value_sat}",
"currency": {
"symbol": "VRSC",
"decimals": 8,
"metadata": None
},
"metadata": None
}
],
"metadata": None
}
return jsonify(data), 200
# else:
# return jsonify({
# "code": 500,
# "message": "Failed to fetch balance information",
# "description": "There was an error while fetching balance information from the API"
# }), 500
# Endpoint that is used to fetch the unspend amount of coins/transaction in an account.
@app.route('/account/coins', methods=['POST'])
def account_coins():
data = request.get_json()
if not data:
return jsonify({"error": "No data provided"}), 400
address = data.get("address")
if not address:
return jsonify({"error": "Address not provided"}), 400
utxos_data = get_address_utxos(address)
heights = [entry['height'] for entry in utxos_data]
txids = [entry['txid'] for entry in utxos_data]
satoshis = [entry['satoshis'] for entry in utxos_data]
chain = get_network_status()
newchainid = chain["chainid"]
if utxos_data:
data = {
"block_identifier": {
"index": heights,
"hash": txids
},
"coins": [
{
"coin_identifier": {
"identifier": newchainid
},
"amount": {
"value": satoshis,
"currency": {
"symbol": "VRSC",