Big improve on historylib code; Use bases;

This commit is contained in:
poka 2020-11-27 03:21:42 +01:00
parent c186b3c13c
commit 030f254904
3 changed files with 49 additions and 74 deletions

View File

@ -55,6 +55,7 @@ class History:
} }
balance(script: $pubkey) { balance(script: $pubkey) {
amount amount
base
} }
} }
""" """
@ -73,82 +74,54 @@ class History:
def parseHistory(self): def parseHistory(self):
trans = []
res = self.historyDoc['transactionsHistory']['received']
transIn=[[0 for x in range(0)] for y in range(len(res))]
for i, bloc in enumerate(res):
for output in bloc['outputs']:
if re.search(self.pubkey, output):
transIn[i].append("IN")
transIn[i].append(bloc['writtenTime'])
transIn[i].append(bloc['issuers'][0])
transIn[i].append(int(output.split(':')[0])/100)
transIn[i].append(bloc['comment'])
res = self.historyDoc['transactionsHistory']['sent']
transOut=[[0 for x in range(0)] for y in range(len(res))]
i = 0 i = 0
for bloc in res:
for output in bloc['outputs']: for sens in 'received','sent','receiving','sending':
if not re.search(self.pubkey, output): res = self.historyDoc['transactionsHistory'][sens]
transOut[i].append("OUT") for bloc in res:
transOut[i].append(bloc['writtenTime']) output = bloc['outputs'][0]
transOut[i].append(output.split("SIG(")[1].replace(')','')) trans.append(i)
transOut[i].append(int(output.split(':')[0])/100) trans[i] = []
transOut[i].append(bloc['comment']) trans[i].append(sens)
i += 1 if sens in ('receiving','sending'):
trans[i].append(int(time.time()))
else:
trans[i].append(bloc['writtenTime'])
if sens in ('sent','sending'):
trans[i].append(output.split("SIG(")[1].replace(')',''))
else:
trans[i].append(bloc['issuers'][0])
amount = int(output.split(':')[0])
base = int(output.split(':')[1])
trans[i].append(amount*pow(10,base)/100)
trans[i].append(bloc['comment'])
i += 1
res = self.historyDoc['transactionsHistory']['receiving']
transInMempool=[[0 for x in range(0)] for y in range(len(res))]
for i, bloc in enumerate(res):
for output in bloc['outputs']:
if re.search(self.pubkey, output):
transInMempool[i].append("INM")
transInMempool[i].append(int(time.time()))
transInMempool[i].append(bloc['issuers'][0])
transInMempool[i].append(int(output.split(':')[0])/100)
transInMempool[i].append(bloc['comment'])
res = self.historyDoc['transactionsHistory']['sending']
transOutMempool=[[0 for x in range(0)] for y in range(len(res))]
i = 0
for bloc in res:
for output in bloc['outputs']:
if not re.search(self.pubkey, output):
transOutMempool[i].append("OUTM")
transOutMempool[i].append(int(time.time()))
transOutMempool[i].append(output.split("SIG(")[1].replace(')',''))
transOutMempool[i].append(int(output.split(':')[0])/100)
transOutMempool[i].append(bloc['comment'])
i += 1
trans = transIn + transOut + transInMempool + transOutMempool
trans = list(filter(None, trans))
trans.sort(key=lambda x: x[1]) trans.sort(key=lambda x: x[1])
# Get balance # Get balance
balance = self.historyDoc['balance']['amount']/100 balance = self.historyDoc['balance']['amount']
baseBalance = self.historyDoc['balance']['base']
balance = balance*pow(10,baseBalance)/100
# Get terminal size # Get terminal size
rows = int(os.popen('stty size', 'r').read().split()[1]) rows = int(os.popen('stty size', 'r').read().split()[1])
print('-'.center(rows, '-')) print('-'.center(rows, '-'))
print("\033[1m{: <20} | {: <45} | {: <7} | {: <30}\033[0m".format(" Date"," De / À (clé publique)","Montant (Ḡ1)","Commentaire")) print("\033[1m{: <20} | {: <45} | {: <7} | {: <30}\033[0m".format(" Date"," De / À (clé publique)","Montant (Ḡ1)","Commentaire"))
for i in trans: for t in trans:
if i[0] == "IN": if t[0] == "received":
color = "green" color = "green"
elif i[0] == "INM": elif t[0] == "receiving":
color = "yellow" color = "yellow"
elif i[0] == "OUTM": elif t[0] == "sending":
color = "red" color = "red"
else: color = "blue" else: color = "blue"
date = datetime.fromtimestamp(i[1]).strftime("%d/%m/%Y à %H:%M") date = datetime.fromtimestamp(t[1]).strftime("%d/%m/%Y à %H:%M")
print('-'.center(rows, '-')) print('-'.center(rows, '-'))
print(colored("| {: <18} | {: <45} | {: <9} | {: <30}".format(date, *i[2:]), color)) print(colored("| {: <18} | {: <45} | {: <12} | {: <30}".format(date, *t[2:]), color))
print('-'.center(rows, '-')) print('-'.center(rows, '-'))
print('\033[1mSolde du compte: {0} Ḡ1\033[0m'.format(balance).center(rows, ' ')) print('\033[1mSolde du compte: {0} Ḡ1\033[0m'.format(balance).center(rows, ' '))
print('-'.center(rows, '-')) print('-'.center(rows, '-'))

View File

@ -46,7 +46,7 @@ class Transaction:
print("useMempool:", str(self.useMempool)) print("useMempool:", str(self.useMempool))
queryBuild = gql( queryBuild = gql(
""" """
query ($recipient: String!, $issuer: String!, $amount: Int!, $comment: String!, $useMempool: Boolean!){ genTxs( query ($recipient: String!, $issuer: String!, $amount: Int!, $comment: String!, $useMempool: Boolean!){ genTx(
amount: $amount amount: $amount
comment: $comment comment: $comment
issuer: $issuer issuer: $issuer
@ -66,7 +66,10 @@ class Transaction:
# Send TX document # Send TX document
try: try:
self.txDoc = str(self.client.execute(queryBuild, variable_values=paramsBuild))[13:-3].replace('\\n','\n') # self.txDoc = []
self.txDoc = self.client.execute(queryBuild, variable_values=paramsBuild)['genTx']
print(self.txDoc[0])
# sys.exit(0)
return self.txDoc return self.txDoc
except Exception as e: except Exception as e:
message = ast.literal_eval(str(e))["message"] message = ast.literal_eval(str(e))["message"]
@ -77,25 +80,24 @@ class Transaction:
# Check document # Check document
def checkTXDoc(self): def checkTXDoc(self):
issuerRaw=[];outAmount=[];outPubkey=[];commentRaw=[] issuerRaw=[];outAmount=[];outPubkey=[];commentRaw=[]
self.splitDoc = self.txDoc.split("', '") for i, docs in enumerate(self.txDoc):
for i, docs in enumerate(self.splitDoc):
docList = docs.splitlines() docList = docs.splitlines()
for j, line in enumerate(docList): for j, line in enumerate(docList):
if re.search("Issuers:", line): if re.search("Issuers:", line):
issuerRaw[i:] = [docList[(j + 1) % len(docList)]] issuerRaw.append(docList[(j + 1) % len(docList)])
if re.search("Outputs:", line): if re.search("Outputs:", line):
outputRaw = docList[(j + 1) % len(docList)].split(":") outputRaw = docList[(j + 1) % len(docList)].split(":")
outAmount[i:] = [int(outputRaw[0])] outAmount.append(int(outputRaw[0]))
outPubkey[i:] = [outputRaw[2].split("SIG(")[1].replace(')','')] outPubkey.append(outputRaw[2].split("SIG(")[1].replace(')',''))
if re.search("Comment:", line): if re.search("Comment:", line):
commentRaw[i:] = [line.split(': ', 1)[1]] commentRaw.append(line.split(': ', 1)[1])
# Check if it's only a change transaction # Check if it's only a change transaction
if all(i == self.issuer for i in outPubkey): if all(i == self.issuer for i in outPubkey):
print("Le document contient une transaction de change") print("Le document contient une transaction de change")
self.isChange = True self.isChange = True
# Check validity of the document # Check validity of the document
elif issuerRaw[0] != self.issuer or outAmount[0] != self.amount or outPubkey[0] != self.recipient or commentRaw[0] != self.comment: elif all(i != self.issuer for i in issuerRaw) or sum(outAmount) != self.amount or all(i != self.recipient for i in outPubkey) or all(i != self.comment for i in commentRaw):
sys.stderr.write(colored("Le document généré est corrompu !\nLe noeud " + self.node + "a peut être un dysfonctionnement.\n", 'red')) sys.stderr.write(colored("Le document généré est corrompu !\nLe noeud " + self.node + "a peut être un dysfonctionnement.\n", 'red'))
sys.stderr.write(colored(issuerRaw[0] + " envoi " + str(outAmount[0]) + " vers " + outPubkey[0] + " with comment: " + commentRaw[0] + "\n", "yellow")) sys.stderr.write(colored(issuerRaw[0] + " envoi " + str(outAmount[0]) + " vers " + outPubkey[0] + " with comment: " + commentRaw[0] + "\n", "yellow"))
raise ValueError('Le document généré est corrompu !') raise ValueError('Le document généré est corrompu !')
@ -108,7 +110,7 @@ class Transaction:
# Sign TX documents # Sign TX documents
signature=[] signature=[]
self.signedDoc=[] self.signedDoc=[]
for i, docs in enumerate(self.splitDoc): for i, docs in enumerate(self.txDoc):
signature.append(fmt["64"](sign(docs.encode(), get_privkey(self.dunikey, "pubsec"))[:-len(docs.encode())])) signature.append(fmt["64"](sign(docs.encode(), get_privkey(self.dunikey, "pubsec"))[:-len(docs.encode())]))
self.signedDoc.append(docs + signature[i].decode()) self.signedDoc.append(docs + signature[i].decode())
return self.signedDoc return self.signedDoc

View File

@ -61,10 +61,10 @@ sg.theme('DarkGrey2')
layout = [ [sg.Text('Noeud utilisé: ' + node)], layout = [ [sg.Text('Noeud utilisé: ' + node)],
[sg.Text('Votre clé publique: ' + issuer)], [sg.Text('Votre clé publique: ' + issuer)],
[sg.Text('')], [sg.Text('')],
[sg.Text('Destinataire: '), sg.InputText(size=(50, None),default_text=issuer)], [sg.Text('Destinataire: '), sg.InputText(size=(55, None),default_text=issuer)],
[sg.Text('Montant: '), sg.InputText(size=(7, None)), sg.Text('Ḡ1')], [sg.Text('Montant: '), sg.InputText(size=(7, None)), sg.Text('Ḡ1')],
[sg.Text('Commentaire:'), sg.InputText(size=(50, None))], [sg.Text('Commentaire:'), sg.InputText(size=(55, None))],
[sg.Button('Envoyer'), sg.Button('Annuler')] ] [sg.Button('Envoyer')] ]
# Create the Window # Create the Window
window = sg.Window('Paiement Ḡ1 - GVA', layout) window = sg.Window('Paiement Ḡ1 - GVA', layout)
@ -72,13 +72,13 @@ window = sg.Window('Paiement Ḡ1 - GVA', layout)
while True: while True:
try: try:
event, values = window.read() event, values = window.read()
if event == sg.WIN_CLOSED or event == 'Annuler': if event == sg.WIN_CLOSED:
break break
if event == 'Envoyer': if event == 'Envoyer':
ProceedPaiement(values[0], values[1], values[2]) ProceedPaiement(values[0], values[1], values[2])
except Exception as e: except Exception as e:
loc = window.CurrentLocation() loc = window.CurrentLocation()
sg.popup(f'Une erreur est survenu', e, title="Erreur", location=(loc)) sg.popup(e, title="ERREUR", button_color=('black','red'), location=(loc))
else: else:
loc = window.CurrentLocation() loc = window.CurrentLocation()
sg.popup(f'Transaction effectué avec succès !', title="Envoyé", location=(loc)) sg.popup(f'Transaction effectué avec succès !', title="Envoyé", location=(loc))