Change paylib to class format

This commit is contained in:
poka 2020-11-17 06:06:45 +01:00
parent 4cedf50a8e
commit de6372cdd8
3 changed files with 105 additions and 101 deletions

View File

@ -1,8 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
from tkinter import * from tkinter import Tk, Label, Entry, Button
sys.path.insert(1, 'libs') from libs.paylib import Transaction
from paylib import *
window = Tk() window = Tk()
@ -12,7 +11,6 @@ title.pack()
# Recipient input # Recipient input
recipientEntry = Entry() recipientEntry = Entry()
# xRecipient = Entry(window, textvariable=recipient, width=30)
recipientEntry.pack() recipientEntry.pack()
@ -29,13 +27,11 @@ def ProceedPaiement():
amount = int(AmountEntry.get()) amount = int(AmountEntry.get())
comment = str(commentEntry.get()) comment = str(commentEntry.get())
print("Paiement en cours ... " + recipient) print("Paiement en cours ... " + recipient)
returnGen = sendGenDoc(recipient, amount, comment)
checkTXDoc(returnGen, recipient, amount, comment)
returnSigned = signDoc(returnGen)
sendTXDoc(returnSigned)
# del recipient, amount, comment, returnGen, returnSigned trans = Transaction(recipient, amount, comment)
recipient = amount = comment = returnGen = returnSigned = None trans.send()
recipient = amount = comment = None
sendButton = Button(window, text="Envoyer", command=ProceedPaiement) sendButton = Button(window, text="Envoyer", command=ProceedPaiement)
sendButton.pack() sendButton.pack()

View File

@ -17,94 +17,106 @@ if not (dunikey):
# Define Duniter GVA node # Define Duniter GVA node
transport = AIOHTTPTransport(url=node) transport = AIOHTTPTransport(url=node)
client = Client(transport=transport, fetch_schema_from_transport=True) client = Client(transport=transport, fetch_schema_from_transport=True)
issuer = get_privkey(dunikey, "pubsec").pubkey
def sendGenDoc(recipient, amount, comment=''):
# TODO: Check args
# Build TX generation document
queryBuild = gql(
"""
query ($recipient: String!, $issuer: String!, $amount: Int!, $comment: String!){ genTxs(
amount: $amount
comment: $comment
issuer: $issuer
recipient: $recipient
)
}
"""
)
paramsBuild = {
"recipient": recipient,
"issuer": issuer,
"amount": amount,
"comment": comment
}
# Send TX document
try:
txDoc = str(client.execute(queryBuild, variable_values=paramsBuild))[13:-3].replace('\\n','\n')
return txDoc
except Exception as e:
message = ast.literal_eval(str(e))["message"]
sys.stderr.write("Echec de la génération du document:\n" + message + "\n")
sys.exit(1)
# Check document class Transaction():
def checkTXDoc(txDoc, recipient, amount, comment=''): def __init__(self, recipient, amount, comment=''):
docList = txDoc.splitlines() self.recipient = recipient
for i, line in enumerate(docList): self.amount = amount
if re.search("Issuers:", line): self.comment = comment
issuerRaw = docList[(i + 1) % len(docList)] self.issuer = get_privkey(dunikey, "pubsec").pubkey
if re.search("Outputs:", line):
outputRaw = docList[(i + 1) % len(docList)].split(":")
outAmount = outputRaw[0]
outPubkey = outputRaw[2].split("SIG(")[1].replace(')','')
if re.search("Comment:", line):
commentRaw = line.split(': ', 1)[1]
if issuerRaw != issuer or int(outAmount) != amount or outPubkey != recipient or commentRaw != comment: def genDoc(self):
sys.stderr.write(colored("Le document généré est corrompu !\nNe fait plus confiance au noeud " + node + "\n", 'red')) # TODO: Check args
sys.stderr.write(colored(issuerRaw + " envoi " + outAmount + " vers " + outPubkey + " with comment: " + commentRaw + "\n", "yellow"))
sys.exit(1) # Build TX generation document
else: queryBuild = gql(
print("Le document généré est conforme.") """
return True query ($recipient: String!, $issuer: String!, $amount: Int!, $comment: String!){ genTxs(
amount: $amount
comment: $comment
issuer: $issuer
recipient: $recipient
)
}
"""
)
paramsBuild = {
"recipient": self.recipient,
"issuer": self.issuer,
"amount": self.amount,
"comment": self.comment
}
# Send TX document
try:
self.txDoc = str(client.execute(queryBuild, variable_values=paramsBuild))[13:-3].replace('\\n','\n')
return self.txDoc
except Exception as e:
message = ast.literal_eval(str(e))["message"]
sys.stderr.write("Echec de la génération du document:\n" + message + "\n")
sys.exit(1)
def signDoc(txDoc): # Check document
# Sign TX document def checkTXDoc(self):
signature = fmt["64"](sign(txDoc.encode(), get_privkey(dunikey, "pubsec"))[:-len(txDoc.encode())]) docList = self.txDoc.splitlines()
signedDoc = txDoc + signature.decode() for i, line in enumerate(docList):
if re.search("Issuers:", line):
issuerRaw = docList[(i + 1) % len(docList)]
if re.search("Outputs:", line):
outputRaw = docList[(i + 1) % len(docList)].split(":")
outAmount = outputRaw[0]
outPubkey = outputRaw[2].split("SIG(")[1].replace(')','')
if re.search("Comment:", line):
commentRaw = line.split(': ', 1)[1]
return signedDoc if issuerRaw != self.issuer or int(outAmount) != self.amount or outPubkey != self.recipient or commentRaw != self.comment:
sys.stderr.write(colored("Le document généré est corrompu !\nNe fait plus confiance au noeud " + node + "\n", 'red'))
sys.stderr.write(colored(issuerRaw + " envoi " + outAmount + " vers " + outPubkey + " with comment: " + commentRaw + "\n", "yellow"))
sys.exit(1)
else:
print("Le document généré est conforme.")
return self.txDoc
def sendTXDoc(signedDoc): def signDoc(self):
# Build TX document # Sign TX document
querySign = gql( signature = fmt["64"](sign(self.txDoc.encode(), get_privkey(dunikey, "pubsec"))[:-len(self.txDoc.encode())])
""" self.signedDoc = self.txDoc + signature.decode()
mutation ($signedDoc: String!){ tx( return self.signedDoc
rawTx: $signedDoc
) {
version
issuers
outputs
}
}
"""
)
paramsSign = {
"signedDoc": signedDoc
}
# Send TX Signed document
try: def sendTXDoc(self):
client.execute(querySign, variable_values=paramsSign) # Build TX document
print(colored("Transaction effectué avec succès !", "green")) querySign = gql(
except Exception as e: """
message = ast.literal_eval(str(e))["message"] mutation ($signedDoc: String!){ tx(
sys.stderr.write("Echec de la transaction:\n" + message + "\n") rawTx: $signedDoc
sys.exit(1) ) {
version
issuers
outputs
}
}
"""
)
paramsSign = {
"signedDoc": self.signedDoc
}
# Send TX Signed document
try:
client.execute(querySign, variable_values=paramsSign)
print(colored("Transaction effectué avec succès !", "green"))
except Exception as e:
message = ast.literal_eval(str(e))["message"]
sys.stderr.write("Echec de la transaction:\n" + message + "\n")
sys.exit(1)
def send(self):
self.genDoc()
self.checkTXDoc()
self.signDoc()
self.sendTXDoc()

16
pay.py
View File

@ -1,7 +1,7 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import sys import sys
from libs.paylib import sendGenDoc, checkTXDoc, signDoc, sendTXDoc from libs.paylibClass import Transaction
# Get args # Get args
try: try:
@ -9,17 +9,13 @@ try:
amount = int(sys.argv[2]) amount = int(sys.argv[2])
if len(sys.argv) > 3: if len(sys.argv) > 3:
comment = sys.argv[3] comment = sys.argv[3]
else:
comment = ""
except Exception as e: except Exception as e:
print("Please enter the recipient's public and the amount\n" + str(e)) print("Please enter the recipient's public and the amount\n" + str(e))
sys.exit(1) sys.exit(1)
# Execute workflow # Create transaction and send it
## Generate TX document from server and check it trans = Transaction(recipient, amount, comment)
returnGen = sendGenDoc(recipient, amount, comment='') trans.send()
docIsOK = checkTXDoc(returnGen, recipient, amount, comment='')
# Confirm TX document is ok, sign and send it
if docIsOK:
returnSigned = signDoc(returnGen)
sendTXDoc(returnSigned)