Check all TX docs; Send multiple TX docs

This commit is contained in:
poka 2020-11-19 07:37:59 +01:00
parent 550a0a68ef
commit 3c2de4f2fd
2 changed files with 86 additions and 66 deletions

View File

@ -20,6 +20,7 @@ client = Client(transport=transport, fetch_schema_from_transport=True)
class Transaction:
def __init__(self, recipient, amount, comment=''):
self.recipient = recipient
self.amount = amount
@ -27,8 +28,8 @@ class Transaction:
self.issuer = get_privkey(dunikey, "pubsec").pubkey
self.isChange = False
if not re.match(r"(?![OIl])[1-9A-Za-z]{42,45}", self.recipient):
sys.stderr.write("Issuer pubkey is not to good format.\n")
if not re.match(r"(?![OIl])[1-9A-Za-z]{42,45}", recipient):
sys.stderr.write("La clé publique n'est pas au bon format.\n")
sys.exit(1)
def genDoc(self):
@ -65,76 +66,92 @@ class Transaction:
# Check document
def checkTXDoc(self):
docList = self.txDoc.splitlines()
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]
issuerRaw=[];outAmount=[];outPubkey=[];commentRaw=[]
self.splitDoc = self.txDoc.split("', '")
for i, docs in enumerate(self.splitDoc):
docList = docs.splitlines()
for j, line in enumerate(docList):
if re.search("Issuers:", line):
issuerRaw[i:] = [docList[(j + 1) % len(docList)]]
if re.search("Outputs:", line):
outputRaw = docList[(j + 1) % len(docList)].split(":")
outAmount[i:] = [int(outputRaw[0])]
outPubkey[i:] = [outputRaw[2].split("SIG(")[1].replace(')','')]
if re.search("Comment:", line):
commentRaw[i:] = [line.split(': ', 1)[1]]
# Check if is change transaction
if issuerRaw == outPubkey:
# print(outPubkey)
# if all(i == self.issuer for i in outPubkey):
# print(sum(outAmount))
# print(self.txDoc)
# sys.exit(0)
# Check if is only change transaction
if all(i == self.issuer for i in outPubkey):
print("Ce document contient une transaction de change")
self.isChange = True
# Check validity of the document
elif issuerRaw != self.issuer or int(outAmount) != self.amount or outPubkey != self.recipient or commentRaw != self.comment:
elif issuerRaw[0] != self.issuer or outAmount[0] != self.amount or outPubkey[0] != self.recipient or commentRaw[0] != 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.stderr.write(colored(issuerRaw[0] + " envoi " + str(outAmount[0]) + " vers " + outPubkey[0] + " with comment: " + commentRaw[0] + "\n", "yellow"))
sys.exit(1)
else:
print("Le document généré est conforme.")
self.isChange = False
return self.txDoc
def signDoc(self):
# Sign TX document
signature = fmt["64"](sign(self.txDoc.encode(), get_privkey(dunikey, "pubsec"))[:-len(self.txDoc.encode())])
self.signedDoc = self.txDoc + signature.decode()
# Sign TX documents
signature=[]
self.signedDoc=[]
for i, docs in enumerate(self.splitDoc):
signature.append(fmt["64"](sign(docs.encode(), get_privkey(dunikey, "pubsec"))[:-len(docs.encode())]))
self.signedDoc.append(docs + signature[i].decode())
return self.signedDoc
def sendTXDoc(self):
# Build TX document
querySign = gql(
"""
mutation ($signedDoc: String!){ tx(
rawTx: $signedDoc
) {
version
issuers
outputs
# Build TX documents
txResult=[]
for docs in self.signedDoc:
querySign = gql(
"""
mutation ($signedDoc: String!){ tx(
rawTx: $signedDoc
) {
version
issuers
outputs
}
}
"""
)
paramsSign = {
"signedDoc": docs
}
}
"""
)
paramsSign = {
"signedDoc": self.signedDoc
}
# Send TX Signed document
try:
txResult = str(client.execute(querySign, variable_values=paramsSign))
except Exception as e:
message = ast.literal_eval(str(e))["message"]
sys.stderr.write("Echec de la transaction:\n" + message + "\n")
sys.exit(1)
else:
# print(txResult)
if self.isChange:
self.send()
# Send TX Signed document
try:
txResult.append(str(client.execute(querySign, variable_values=paramsSign)))
except Exception as e:
message = ast.literal_eval(str(e))["message"]
sys.stderr.write("Echec de la transaction:\n" + message + "\n")
sys.exit(1)
else:
print(colored("Transaction effectué avec succès !", "green"))
return txResult
if self.isChange:
self.send()
else:
print(colored("Transaction effectué avec succès !", "green"))
return txResult
def send(self):
self.genDoc()
self.checkTXDoc()
self.signDoc()
self.sendTXDoc()
result = self.genDoc()
result = self.checkTXDoc()
result = self.signDoc()
result = self.sendTXDoc()
return result

29
pay.py
View File

@ -1,21 +1,24 @@
#!/usr/bin/env python3
import sys
import sys, argparse
from libs.paylib import Transaction
# Get args
try:
recipient = sys.argv[1]
amount = int(sys.argv[2])
if len(sys.argv) > 3:
comment = sys.argv[3]
else:
comment = ""
except Exception as e:
print("Please enter the recipient's public and the amount\n" + str(e))
# Parse arguments
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--destinataire', help="Destinataire du paiement")
parser.add_argument('-m', '--montant', type=int, help="Montant de la transaction")
parser.add_argument('-c', '--commentaire', default="", help="Commentaire de la transaction")
parser.add_argument('-v', '--verbose', action='store_true', help="Commentaire de la transaction")
args = parser.parse_args()
if not args.montant or not args.montant:
print("Veuillez renseigner la clé publique du destinataire, ainsi que le montant de la transaction")
parser.print_help()
sys.exit(1)
# Create transaction and send it
trans = Transaction(recipient, amount, comment)
trans.send()
trans = Transaction(args.destinataire, args.montant, args.commentaire)
result = trans.send()
if args.verbose:
print(str(result))