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

29
pay.py
View File

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