Improve .env import

This commit is contained in:
poka 2020-11-22 06:27:26 +01:00
parent 3c2de4f2fd
commit 258aeb5641
5 changed files with 59 additions and 39 deletions

2
.env.template Normal file
View File

@ -0,0 +1,2 @@
DUNIKEY="" # Chemin de la clé privé Ḡ1 de l'émetteur, au format PubSec
NODE="https://g1.librelois.fr/gva" # Noeud duniter ayant GVA activé

2
.gitignore vendored
View File

@ -1,3 +1,3 @@
__pycache__
userEnv.py
.env
.vscode

View File

@ -1,37 +1,37 @@
#!/usr/bin/env python3
import sys, re, os.path, json, ast
from shutil import copyfile
if not os.path.isfile("userEnv.py"):
copyfile("userEnv.py.template", "userEnv.py")
from termcolor import colored
from userEnv import dunikey, node
from natools import fmt, sign, get_privkey
from gql import gql, Client
from gql.transport.aiohttp import AIOHTTPTransport
if not (dunikey):
print("Please set the path to your pubsec keychain in userEnv.py file.")
sys.exit(1)
# Define Duniter GVA node
transport = AIOHTTPTransport(url=node)
client = Client(transport=transport, fetch_schema_from_transport=True)
VERSION = "0.1.0"
PUBKEY_REGEX = "(?![OIl])[1-9A-Za-z]{42,45}"
class Transaction:
def __init__(self, recipient, amount, comment=''):
def __init__(self, dunikey, node, recipient, amount, comment='', verbose=False):
self.dunikey = dunikey
self.recipient = recipient
self.amount = amount
self.comment = comment
self.issuer = get_privkey(dunikey, "pubsec").pubkey
self.verbose = verbose
self.isChange = False
if not re.match(r"(?![OIl])[1-9A-Za-z]{42,45}", recipient):
if not re.match(PUBKEY_REGEX, recipient) or len(recipient) > 45:
sys.stderr.write("La clé publique n'est pas au bon format.\n")
sys.exit(1)
if recipient == self.issuer:
sys.stderr.write("Le destinataire ne peut pas être vous même.\n")
sys.exit(1)
# Define Duniter GVA node
transport = AIOHTTPTransport(url=node)
self.client = Client(transport=transport, fetch_schema_from_transport=True)
def genDoc(self):
# Build TX generation document
queryBuild = gql(
@ -56,7 +56,7 @@ class Transaction:
# Send TX document
try:
self.txDoc = str(client.execute(queryBuild, variable_values=paramsBuild))[13:-3].replace('\\n','\n')
self.txDoc = str(self.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"]
@ -80,18 +80,9 @@ class Transaction:
if re.search("Comment:", line):
commentRaw[i:] = [line.split(': ', 1)[1]]
# 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("Le document contient une transaction de change")
self.isChange = True
# 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:
@ -108,7 +99,7 @@ class Transaction:
signature=[]
self.signedDoc=[]
for i, docs in enumerate(self.splitDoc):
signature.append(fmt["64"](sign(docs.encode(), get_privkey(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())
return self.signedDoc
@ -135,16 +126,21 @@ class Transaction:
# Send TX Signed document
try:
txResult.append(str(client.execute(querySign, variable_values=paramsSign)))
txResult.append(str(self.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")
if self.verbose:
sys.stderr.write("Document final:\n" + docs)
sys.exit(1)
else:
if self.isChange:
self.send()
else:
print(colored("Transaction effectué avec succès !", "green"))
if self.verbose:
print(docs)
break
return txResult

42
pay.py
View File

@ -1,24 +1,48 @@
#!/usr/bin/env python3
import sys, argparse
from libs.paylib import Transaction
import sys, argparse, os
from os.path import join, dirname
from shutil import copyfile
from dotenv import load_dotenv
from libs.paylib import Transaction, VERSION
# Get variables environment
if not os.path.isfile('.env'):
copyfile(".env.template", ".env")
dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)
dunikey = os.getenv('DUNIKEY')
node = os.getenv('NODE')
if not dunikey or not node:
sys.stderr.write("Please fill the path of your private key (PubSec), and a Duniter node in .env file\n")
sys.exit(1)
# dunikey="/home/poka/dev/trousseau-Do99s6wQ-g1-PubSec.dunikey"
# node="http://localhost:30901/gva"
# 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")
parser.add_argument('-v', '--verbose', action='store_true', help="Affiche le résultat JSON de la transaction")
parser.add_argument('--version', action='store_true', help="Affiche la version actuelle du programme")
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)
if args.version:
print(VERSION)
sys.exit(0)
if not args.destinataire 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(args.destinataire, args.montant, args.commentaire)
trans = Transaction(dunikey, node, args.destinataire, args.montant, args.commentaire, args.verbose)
result = trans.send()
if args.verbose:
print(str(result))
print(str(result))

View File

@ -1,2 +0,0 @@
dunikey = "" # Chemin de la clé privé Ḡ1 de l'émetteur, au format PubSec
node = "https://g1.librelois.fr/gva" # Noeud duniter ayant GVA activé