G1FabLab CODE STILL USING silkaj...

This commit is contained in:
fred 2023-01-22 20:01:20 +01:00
parent 7a6d1ee7bf
commit 5891cfd120
45 changed files with 44279 additions and 0 deletions

174
0ne.sh Normal file
View File

@ -0,0 +1,174 @@
#!/bin/bash
################################################################################
# Capture picture. Find a face. Print G1Card.
# Autoriser le user à imprimer: sudo usermod -a -G lp pi
#
# !!!! PGP CONFIG !!!!!
# Add this to ~/.gnupg/gpg.conf:
# use-agent
# pinentry-mode loopback
#
# Add this to ~/.gnupg/gpg-agent.conf
# allow-loopback-pinentry
#
# Then restart the agent with
# echo RELOADAGENT | gpg-connect-agent
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 0.1
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
################################################################################
# Initialize GPIO states
LED=5
BUTTON=21
gpio -g mode $BUTTON up
gpio -g mode $LED out
ip="$(ifconfig wlan0 | grep "inet " | awk '{print $2}')"
ipfsid=$(ipfs id -f="<id>\n")
echo "#############################" > /dev/usb/lp0
echo "NODE: $ip" > /dev/usb/lp0
echo "IPFS: $ipfsid" > /dev/usb/lp0
echo "#############################" > /dev/usb/lp0
mkdir -p "./print/"
sleep=5
# Forever Loop
while :
do
if [ $(gpio -g read $BUTTON) -eq 0 ]; then
gpio -g write $LED 1
STAMP=$(date +%Y%m%d%H%M%S)
# TAKE PICTURE (+++ brightness)
raspistill -n -th none -t 50 -fli auto -br 80 -co 80 -w 720 -h 480 -o ./picture.jpg
gpio -g write $LED 0
# START FACE DETECTION & WAIT...
cp ./picture.jpg ./tmp/${STAMP}.jpg
for (( i=$sleep ; i>=0 ; i-- ))
do
if [[ -f "./processed_images/face.jpg" ]]; then
# FOUND A FACE
gpio -g write $LED 1
break
else
sleep 1s
# printf "\r%02d:%02d" $((i/60)) $((i%60))
fi
done
# DO WE HAVE ONE FACE?
if [[ ! -f "./processed_images/face.jpg" ]]; then
# NO !!!
gpio -g write $LED 1
sleep 0.2
gpio -g write $LED 0
sleep 0.2
gpio -g write $LED 1
sleep 0.2
gpio -g write $LED 0
else
# YES !!! CREATING CARD...
SALT=$(./diceware.sh 5 | xargs)
PEPPER=$(./diceware.sh 5 | xargs)
# MAKE pgp passphrase [0-9] -> [1-10]
P1=$((RANDOM % 10))
K1=$(echo "$SALT $PEPPER" | cut -d ' ' -f $(($P1 + 1)))
P2=$((RANDOM % 10))
K2=$(echo "$SALT $PEPPER" | cut -d ' ' -f $(($P2 + 1)))
P3=$((RANDOM % 10))
K3=$(echo "$SALT $PEPPER" | cut -d ' ' -f $(($P3 + 1)))
P4=$((RANDOM % 10))
K4=$(echo "$SALT $PEPPER" | cut -d ' ' -f $(($P4 + 1)))
PIN=$P1$P2$P3$P4
KEY=$K1$K2$K3$K4
echo "________ G1 CARTE ________" > /dev/usb/lp0
echo "Date: $(date +%Y/%m/%d-%H:%M:%S)" > /dev/usb/lp0
# GENERATE PUBLIC KEY with SILKAJ CLI HACK (Bad ASS coding, I know! But it works...)
# sudo pip3 install commandlines scrypt
PUBKEY=$(./silkaj/silkaj generate_auth_file --auth-scrypt -salt="$SALT" -password="$PEPPER")
# NEW G1 CARD CREATION
if [[ -f "./authfile" && ! -d "./CARDS/${PUBKEY}" ]]; then
mkdir -p "./CARDS/${PUBKEY}/"
# RECORD qrcode.png
qrencode "${PUBKEY}" -o "./CARDS/${PUBKEY}/G1_qrcode.png" -s 10
# RECORD visage.jpg & picture.jpg
# TODO: More security with Deep Learning on visage(s).jpg
mv "./processed_images/face.jpg" "./CARDS/${PUBKEY}/visage.jpg"
mv "./picture.jpg" "./CARDS/${PUBKEY}/photo.jpg"
# RECORD authfile.pgp ($KEY ENCRYPTED)
# TODO: Find Better Encryption! Use longer PIN with RFID?
echo $KEY | gpg -c --passphrase-fd 0 ./authfile
mv "./authfile.gpg" "./CARDS/${PUBKEY}/"
rm -f "./authfile"
# RECORD key.pgp ($PIN ENCRYPTED)
# TODO: Make it less sensible to brute force attack
echo "$KEY" > ./key
echo $PIN | gpg -c --passphrase-fd 0 ./key
mv "./key.gpg" "./CARDS/${PUBKEY}/"
rm -f "./key"
# SEND "./CARDS/${PUBKEY}" TO IPFS
IPFS=$(ipfs add -r -q "./CARDS/${PUBKEY}" | tail -n 1)
# NOW WE CAN GET BACK FILES BY
# ipfs cat ${PUBKEY}/file
# RECEVOIR
echo " RECEVOIR" > /dev/usb/lp0
# PRINT photo.jpg
convert "./CARDS/${PUBKEY}/photo.jpg" -strip -resize 384 -format jpg "./print/photo.jpg"
python ./esc-pos-image.py "./print/photo.jpg" > /dev/usb/lp0
# PRINT qrcode.png
convert "./CARDS/${PUBKEY}/G1_qrcode.png" -strip -resize 384 -format png "./print/G1_qrcode.png"
python ./esc-pos-image.py "./print/G1_qrcode.png" > /dev/usb/lp0
echo "${PUBKEY}" > /dev/usb/lp0
echo "8<--------- 8<-------- 8<------" > /dev/usb/lp0
# ENVOYER
# CREATE & PRINT IPFS_qrcode.png
echo " ENVOYER" > /dev/usb/lp0
qrencode "${IPFS}" -o "/tmp/IPFS_qrcode.png" -s 10 #--foreground=FFFFFF --background=000000
convert "/tmp/IPFS_qrcode.png" -strip -resize 384 -format png "./print/IPFS_qrcode.png"
python ./esc-pos-image.py "./print/IPFS_qrcode.png" > /dev/usb/lp0
echo " " > /dev/usb/lp0
echo "${IPFS}" > /dev/usb/lp0
echo "8<--------- 8<-------- 8<------" > /dev/usb/lp0
# PRINT PRIVATE ACCESS
echo "########## _SECRET_ #########" > /dev/usb/lp0
echo "COMPTE (Cesium)" > /dev/usb/lp0
echo "${SALT}" > /dev/usb/lp0
echo "${PEPPER}" > /dev/usb/lp0
echo "#############################" > /dev/usb/lp0
echo " $PIN" > /dev/usb/lp0
echo "#############################" > /dev/usb/lp0
echo " " > /dev/usb/lp0
# PRINT visage.jpg
convert "./CARDS/${PUBKEY}/visage.jpg" -strip -resize 384 -format jpg "./print/visage.jpg"
python ./esc-pos-image.py "./print/visage.jpg" > /dev/usb/lp0
echo " " > /dev/usb/lp0
else
echo "COLLISION! Veuillez recommencer..." > /dev/usb/lp0
fi
gpio -g write $LED 0
fi
else
#DO NOTHING
sleep 0.1
fi
done

Binary file not shown.

After

Width:  |  Height:  |  Size: 404 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 203 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

127
checknodes.sh Normal file
View File

@ -0,0 +1,127 @@
#!/bin/bash
# Sleep time in seconds
sleep=300
# Checks the current block number of a node - is run in parallel and stores the result in the outfile
# Parameters: <node> <all watched nodes> <outfile>
checkonenode()
{
# Timeout in seconds for https nodes
httpsTimeout=10
# Timeout in seconds for http nodes
httpTimeout=3
node=$1
watched=$2
outfile=$3
# Curl: -m timeout, -k ignore SSL certificate errors
cur=`echo "$( { curl -m $httpsTimeout -k https://$node/blockchain/current; } 2>&1 )"`
n=$node
if [[ "$cur" != *issuersFrameVar* ]]
then
# It failed in https, maybe try http?
cur=`echo "$( { curl -m $httpTimeout http://$node/blockchain/current; } 2>&1 )"`
if [[ "$cur" == *issuersFrameVar* ]]
then
# Indicate that the node is http
n="$n-(http)"
fi
fi
if [[ "$cur" != *issuersFrameVar* ]]
then
# The node didn't respond on time
cur="ERROR"
else
# The node did respond - grab the block number and hash of the block as key
cur="`echo "$cur"|grep '^ "number": '|awk '{print $2}'|awk -F, '{print $1}'`-`echo "$cur"|grep '^ "hash": '|awk '{print $2}'|awk '{print substr($1,2,13)}'`"
fi
if [[ $watched =~ .*#$node#.* ]]
then
# The node is a watched node, add some bold
n="\e[1m$n\e[0m"
fi
# Put the result into the file
echo "$cur $n">$outfile
# Notify that we're done here
touch $outfile.done
}
# Temp dir where results are stored
DIR=/tmp/gnodewatch
export DIR
mkdir -p $DIR
# Main loop
while [ true ]
do
# Grab the nodes we are actively wotching - they will be in bold in the final output
watched=`grep -v "#" nodes.txt|egrep "\!$"|awk '{print "#" $1 "#"}'`
# All nodes we are watching
nodes=`grep -v "#" nodes.txt|awk '{print $1}'`
# The index to generate separate file names
index=0
# Wipe out the output directory
rm $DIR/*out $DIR/*done 2>/dev/null
printf "Probing nodes..."
# Query all nodes in parallel
for node in $nodes
do
checkonenode $node "$watched" $DIR/$index.out &
((index++))
done
# Wait a little for the first files to be created
sleep 1s
# Wait for all the threads to report they are done
while [ `ls $DIR/*done|wc -l` -lt $index ]
do
sleep 1s
done
printf "\r \r"
# Grab all results
curs=`cat $DIR/*out|sort`
# Extract all forks, excluding all errors
chains="`echo "$curs"|grep -v ERROR|awk '{print $1}'|sort -r|uniq`"
# Count the number of chains and output the corresponding nodes
nb=0
for chain in $chains
do
echo $chain
echo -e "`echo "$curs"|egrep "^$chain "|awk '{print "| " $2}'`"
((nb++))
done
# Output the nodes in error
if [[ "`echo "$curs"|grep ERROR`" != "" ]]
then
echo ""
echo "Nodes in error:"
echo -e "`echo "$curs"|grep ERROR|awk '{print "| " $2}'`"
fi
echo ""
# Output a final status
if [[ $nb == 0 ]]
then
echo -e "\e[1m\e[31mIS G1 DEAD???\e[0m"
elif [[ $nb == 1 ]]
then
echo -e "\e[1m\e[32mG1 is OK\e[0m"
else
echo -e "\e[1m\e[31mG1 is FORKING in $nb chains\e[0m"
fi
# Sleep for a while but still show something is happening and the script did not crash
for (( i=$sleep ; i>0 ; i-- ))
do
sleep 1s
printf "\r%02d:%02d" $((i/60)) $((i%60))
done
echo ""
done

7776
diceware-wordlist.txt Normal file

File diff suppressed because it is too large Load Diff

17
diceware.sh Normal file
View File

@ -0,0 +1,17 @@
#!/usr/bin/env bash
# Default to 6 word passphrase
MOTS=$(echo "$1" | grep -E "^\-?[0-9]+$")
if [[ "$MOTS" == "" ]]; then MOTS=4; fi
WORDCOUNT=${1-$MOTS}
# Download the wordlist
# wget -nc -O ~/.diceware-wordlist http://world.std.com/%7Ereinhold/diceware.wordlist.asc 2> /dev/null
# print a list of the diceware words
cat ./diceware-wordlist.txt |
awk '/[1-6][1-6][1-6][1-6][1-6]/{ print $2 }' |
# randomize the list order
shuf --random-source=/dev/urandom |
# pick the first n words
head -n ${WORDCOUNT} |
# pretty print
tr '\n' ' '
echo

49
esc-pos-image.py Normal file
View File

@ -0,0 +1,49 @@
#!/usr/bin/python
# esc-pos-image.py - print image files given as command line arguments
# to simple ESC-POS image on stdout
# scruss - 2014-07-26 - WTFPL (srsly)
# if you want a proper CUPS driver for a 58mm thermal printer
# that uses this command set, go here:
# https://github.com/klirichek/zj-58
import sys
from PIL import Image
import PIL.ImageOps
import struct
# give usage and exit if no arguments
if len(sys.argv) == 1:
print 'Usage:', sys.argv[0], \
'image1 image2 ... [ > printer_device ]'
exit(1)
# print all of the images!
for i in sys.argv[1:]:
im = Image.open(i)
# if image is not 1-bit, convert it
if im.mode != '1':
im = im.convert('1')
# if image width is not a multiple of 8 pixels, fix that
if im.size[0] % 8:
im2 = Image.new('1', (im.size[0] + 8 - im.size[0] % 8,
im.size[1]), 'white')
im2.paste(im, (0, 0))
im = im2
# Invert image, via greyscale for compatibility
# (no, I don't know why I need to do this)
im = PIL.ImageOps.invert(im.convert('L'))
# ... and now convert back to single bit
im = im.convert('1')
# output header (GS v 0 \000), width, height, image data
sys.stdout.write(''.join(('\x1d\x76\x30\x00',
struct.pack('2B', im.size[0] / 8 % 256,
im.size[0] / 8 / 256),
struct.pack('2B', im.size[1] % 256,
im.size[1] / 256),
im.tobytes())))

109
face_detect.py Normal file
View File

@ -0,0 +1,109 @@
#!/usr/bin/python3
################################################################################
# Authors: Fred (support@qo-op.com) + Mark
# Version: 0.1
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
################################################################################
import cv2
import os
import time
import subprocess
import numpy as np
cascPath = "./haarcascade_frontalface_default.xml"
shot_images_path = "./tmp/"
processed_images_path = "./processed_images"
#if directories dont exist, make them
if not os.path.isdir(shot_images_path):
os.mkdir(shot_images_path)
if not os.path.isdir(processed_images_path):
os.mkdir(processed_images_path)
print("FaceDetect READY...")
sleep_count = 20
while 1:
files = os.listdir(shot_images_path)
if not files:
time.sleep(0.1)
if sleep_count ==20:
#print("sleeping ...")
sleep_count = 0
sleep_count+=1
else:
for file in files:
# Get user supplied values
imagePath = os.path.join(shot_images_path,file)
# Create the haar cascade
faceCascade = cv2.CascadeClassifier(cascPath)
# Read the image
#may read while image is not finished loading thus this work-around
try:
image = cv2.imread(imagePath)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
except Exception:
print("Could not read image... Retrying...")
break
# Detect faces in the image
faces = faceCascade.detectMultiScale(
gray,
#scaleFactor=1,
minNeighbors=1,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE#cv.CV_HAAR_SCALE_IMAGE
)
print("Found {0} face(s)!".format(len(faces)))
#iterate through the found faces
count = 0
for (x, y, w, h) in faces:
x1 = int(x - w*0.05)
y1 = int(y - h*0.1)
x2 = int(x + w*1.1)
y2 = int(y + h*1.25)
#check if 'face' is really a face...
check_gray = gray[y1:y2,x1:x2]
check = faceCascade.detectMultiScale(
check_gray,
#scaleFactor=1,
minNeighbors=1,
minSize=(30, 30),
flags = cv2.CASCADE_SCALE_IMAGE
)
if len(faces)==1:
#We found ONE face :D
#reshape to print width and height and write to ./processed_images
(img_h,img_w) = check_gray.shape
fw = 384/img_w
img_out = cv2.resize(check_gray,(0,0), fx = fw, fy = fw )
#brighten up the image
added_brightness = 10
img_out = img_out +added_brightness
img_out = np.where((255-img_out)<added_brightness, 255, img_out + added_brightness )
file_name = "./processed_images/face.jpg"
cv2.imwrite(file_name, img_out)
count+=1
os.remove(imagePath)

File diff suppressed because it is too large Load Diff

BIN
photo.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 111 KiB

BIN
print/G1_qrcode.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

BIN
print/IPFS_qrcode.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

BIN
print/photo.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

BIN
print/visage.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

67
silkaj/.gitignore vendored Normal file
View File

@ -0,0 +1,67 @@
# ---> Python
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
env/
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
*.egg-info/
.installed.cfg
*.egg
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*,cover
# Translations
*.mo
*.pot
# Django stuff:
*.log
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Idea
.idea
# Vim swap files
*~
*.swp
*.swo

662
silkaj/LICENSE Normal file
View File

@ -0,0 +1,662 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<http://www.gnu.org/licenses/>.

98
silkaj/README.md Normal file
View File

@ -0,0 +1,98 @@
# Silkaj
- CLI Duniter client written with Python 3.
- [Website](https://silkaj.duniter.org)
## Install
### With release
Download [last release](https://git.duniter.org/clients/python/silkaj/tags) with `wget`.
Check it's integrity comparing it to `silkaj_sha256sum`:
```bash
sha256sum silkaj
```
Add executable permissions:
```bash
chmod a+x silkaj
```
### Manually
- [Install inside a Python environemnt](doc/install_pyenv.md)
- [Install without Python environment](doc/install_on_the_system.md)
- [Build an executable with Pyinstaller](doc/build_with_pyinstaller.md)
- [Install as a drop-down for GNOME Shell with Argos](doc/argos.md)
## Usage
- Get help usage with `-h`, `--help` or `--usage` options, then run:
```bash
./silkaj <sub-command>
```
- Will automatically request and post data on `duniter.org 10901` main Ğ1 node.
- Specify a custom node with `-p` option:
```bash
./silkaj <sub-command> -p <address>:<port>
```
## Features
- Currency information
- Show amount of account
- Send transaction
- Proof-of-Work difficulties: Σ diffi, Π diffi, match
- network information tab:
- endpoints, ip6, ip4, domain name and port. Handle nodes sharing same pubkey.
- pubkey, uid, if member.
- Proof-of-Work difficulties.
- generated block and median times.
- nodes versions.
- current block n°, hash and time.
- Issuers last ones or all: hash, gentime, mediantime
## Example
```bash
./silkaj network
### 20 peers ups, with 15 members and 5 non-members
| domain | ip4 | port | block | hash | gen_time | uid |member| pubkey |diffi| version |
|---------------------+----------------+------+-------+-------------+----------+-----------+------+--------+-----+----------|
| cgeek.fr | 88.174.120.187 | 9330| 41166 | 000027421F… | 15:59:00 | cgeek | yes | HnFcS… | 77 | 0.31.0b6 |
| mirror1.cgeek.fr | 88.174.120.187 | 9331| 41166 | 000027421F… | 15:59:00 | | no | 4jT89… | | 0.31.0b6 |
| mirror2.cgeek.fr | 88.174.120.187 | 9332| 41166 | 000027421F… | 15:59:00 | | no | AZ2JP… | | 0.31.0b6 |
| …t.duniter.inso.ovh | | 80| 41166 | 000027421F… | 15:59:00 | inso | yes | 8Fi1V… | 231 | 0.30.17 |
| peer.duniter.org | 51.255.197.83 | 8999| 41166 | 000027421F… | 15:59:00 | | no | BSmby… | | 0.30.17 |
| desktop.moul.re | 78.227.107.45 | 24723| 41166 | 000027421F… | 15:59:00 | moul | yes | J78bP… | 77 | 0.31.0b7 |
| misc.moul.re | 78.227.107.45 | 8999| 41166 | 000027421F… | 15:59:00 | moul | yes | J78bP… | 77 | 0.31.0b7 |
| test-net.duniter.fr | 88.189.14.141 | 9201| 41166 | 000027421F… | 15:59:00 | kimamila | yes | 5ocqz… | 385 | 0.31.0b3 |
| raspi3.cgeek.fr | 88.174.120.187 | 8999| 41166 | 000027421F… | 15:59:00 | | no | G3wQw… | | 0.31.0a9 |
| duniter.vincentux.fr| | 8999| 41166 | 000027421F… | 15:59:00 | vincentux | yes | 9bZEA… | | 0.30.17 |
| remuniter.cgeek.fr | 88.174.120.187 | 16120| 41166 | 000027421F… | 15:59:00 | remuniter…| yes | TENGx… | | 0.30.17 |
| | 88.163.42.58 | 34052| 41166 | 000027421F… | 15:59:00 | cler53 | yes | 4eDis… | 77 | 0.30.17 |
| suchard.si7v.fr | 163.172.252.3 | 8999| 41166 | 000027421F… | 15:59:00 | hacky | yes | DesHj… | 77 | 0.31.0a8 |
| | 87.91.122.123 | 9330| 41166 | 000027421F… | 15:59:00 | mmpio | yes | BmDso… | 154 | 0.31.0b3 |
| …er.help-web-low.fr | 151.80.40.148 | 8999| 41166 | 000027421F… | 15:59:00 | pafzedog | yes | XeBpJ… | 154 | 0.30.17 |
| | 87.90.32.15 | 8999| 41166 | 000027421F… | 15:59:00 | nay4 | yes | BnSRj… | 77 | 0.31.0a9 |
| duniter.modulix.net | 212.47.227.101 | 9330| 41166 | 000027421F… | 15:59:00 | modulix | yes | DeCip… | | 0.30.17 |
| | 88.174.120.187 | 33036| 41166 | 000027421F… | 15:59:00 | | no | GNRug… | | 0.31.0b7 |
| duniter.cco.ovh | 163.172.176.32 | 8999| 41166 | 000027421F… | 15:59:00 | charles | yes | DA4PY… | 77 | 0.31.0a8 |
| duniter.ktorn.com | 107.170.192.122| 8999| 41166 | 000027421F… | 15:59:00 | ktorn | yes | BR5DD… | 77 | 0.30.17 |
```
### Dependencies
Silkaj is based on Python dependencies:
- [Tabulate](https://bitbucket.org/astanin/python-tabulate/overview): to display charts.
- [Commandlines](https://github.com/chrissimpkins/commandlines): to parse command and sub-commands.
- [PyNaCl](https://github.com/pyca/pynacl/): Cryptography (NaCl) library.
- [scrypt](https://bitbucket.org/mhallin/py-scrypt): scrypt key derivation function.
- [pyaes](https://github.com/ricmoo/pyaes): Pure-Python implementation of AES
### Names
I wanted to call that program:
- bamiyan
- margouillat
- lsociety
- cashmere
I finally called it `Silkaj` as `Silk` in esperanto.

1
silkaj/authfile Normal file
View File

@ -0,0 +1 @@
8558401de5f7a29a7e5d06829d24f8043aef20afa66e83dfc9c25c5bf7739424

View File

@ -0,0 +1 @@
e1a1322b39ba512b0e7607337cd360263adc3370624cae4fe1057e412d9fc848

17
silkaj/doc/argos.md Normal file
View File

@ -0,0 +1,17 @@
## Integrate it on a dropdown menu to the panel
Under GNOME Shell, with [Argos](https://github.com/p-e-w/argos) extension:
- [Install Argos](https://github.com/p-e-w/argos#installation)
- Put inside `~/.config/argos/silkaj.30s.sh`:
```bash
#!/usr/bin/env bash
/path/to/silkaj/silkaj argos
```
Add execution premission:
```bash
chmod u+x ~/.config/argos/silkaj.30s.sh
```
Argos should the script and reload it every 30 seconds.

View File

@ -0,0 +1,18 @@
# Build with Pyinstaller
## Install Pyinstaller
```bash
pip install pyinstaller
```
If you are using Pyenv, dont forget to save pyinstaller install:
```bash
pyenv rehash
```
## Build
```bash
pyinstaller src/silkaj.py --hidden-import=_cffi_backend --hidden-import=_scrypt --onefile
```
You will found the exetuable file on `silkaj/dist` folder.

View File

@ -0,0 +1,31 @@
# Install Silkaj on the system
## Retrieve sources
Clone repository:
```bash
git clone https://github.com/duniter/silkaj.git
```
## Dependencies
You may install dependencies.
You could install all dependencies from `pip`.
If you choose to install from distribution packages, some dependencies could be missing.
You will have to install them with `pip`.
### From pip
```bash
sudo pip3 install -r requirements.txt
```
Use `pip` command if `pip3` is not present.
Upgrade `pip` adding `--upgrade pip` to previous command.
### From distributions package managers
#### Debian-like
```bash
sudo apt-get install python-tabulate python-ipaddress
```
#### Fedora
```bash
sudo dnf install python-devel python-ipaddress python3-tabulate python3-pynacl python3-devel python-pyaes
```

View File

@ -0,0 +1,39 @@
# Install Silkaj on a Python environment
## Install Pyenv
### Install pyenv tools
```bash
curl -L https://raw.githubusercontent.com/pyenv/pyenv-installer/master/bin/pyenv-installer | bash
```
### Handle shell modifications: point 2,3 and 4.
- [Follow pyenv install documentation](https://github.com/pyenv/pyenv#installation)
### Install latest Python version and create pyenv
```bash
pyenv install 3.6.0
pyenv shell 3.6.0
pyenv virtualenv silkaj-env
```
## Install Silkaj
### Retrieve silkaj sources
```bash
git clone https://github.com/duniter/silkaj.git
cd silkaj
```
### Install dependencies and store them on pyenv environement
```bash
pip install -r requirements.txt --upgrade
pyenv rehash
```
### Activate pyenv and run silkaj
```bash
pyenv activate silkaj-env
./silkaj
```

2
silkaj/licence-G1/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
.idea/
Thumbs.db

View File

@ -0,0 +1,13 @@
# inspiré de : https://forum.duniter.org/t/doppler-gitlab/3183/30
# GITHUB_URL_AND_KEY should look like https://duniter-gitlab:TOKEN@github.com/chemin/vers/ton/depot/github
mirror_to_github:
script:
- git remote add github $GITHUB_URL_AND_KEY
- git config --global user.email "contact@duniter.org"
- git config --global user.name "Duniter"
- git push --force --mirror github
npm:
script:
- echo TODO
only:
tags

View File

@ -0,0 +1,5 @@
# Licence Ǧ1 ([fr](license/license_g1-fr-FR.rst)) ([en](license/license_g1-en.rst))
Dernière version : (consulter la licence)
// TODO : import depuis npm, version npm publié automatiquement selon les tags

View File

@ -0,0 +1,78 @@
License Ğ1 - v0.2.5
===================
:date: 2017-08-21 16:59
:modified: 2018-01-24 19:20
**Money licensing and liability commitment.**
Any certification operation of a new member of Ğ1 must first be accompanied by the transmission of this license of the currency Ğ1 whose certifier must ensure that it has been studied, understood and accepted by the person who will be certified.
Money Ğ1
--------
Ğ1 occurs via a Universal Dividend (DU) for any human member, which is of the form:
* 1 DU per person per day
The amount of DU is identical each day until the next equinox, where the DU will then be reevaluated according to the formula:
* DU <sub>day</sub> (the following equinox) = DU <day>(equinox) + c² (M / N) (equinox) / (15778800 seconds)</day>
With as parameters:
* c = 4.88% / equinox
* UD (0) = 10.00 Ğ1
And as variables:
* _M_ the total monetary mass at the equinox
* _N_ the number of members at the equinox
Web of Trust Ğ1 (WoT Ğ1)
------------------------
**Warning:** Certifying is not just about making sure you've met the person, it's ensuring that the community Ğ1 knows the certified person well enough and Duplicate account made by a person certified by you, or other types of problems (disappearance ...), by cross-checking that will reveal the problem if necessary.
When you are a member of Ğ1 and you are about to certify a new account:
**You are assured:**
1°) The person who declares to manage this public key (new account) and to have personally checked with him that this is the public key is sufficiently well known (not only to know this person visually) that you are about to certify.
2a°) To meet her physically to make sure that it is this person you know who manages this public key.
2b°) Remotely verify the public person / key link by contacting the person via several different means of communication, such as social network + forum + mail + video conference + phone (acknowledge voice).
Because if you can hack an email account or a forum account, it will be much harder to imagine hacking four distinct means of communication, and mimic the appearance (video) as well as the voice of the person .
However, the 2 °) is preferable to 3 °, whereas the 1 °) is always indispensable in all cases.
3 °) To have verified with the person concerned that he has indeed generated his Duniter account revocation document, which will enable him, if necessary, to cancel his account (in case of account theft, ID, an incorrectly created account, etc.).
**Abbreviated WoT rules:**
Each member has a stock of 100 possible certifications, which can only be issued at the rate of 1 certification / 5 days.
Valid for 2 months, certification for a new member is definitively adopted only if the certified has at least 4 other certifications after these 2 months, otherwise the entry process will have to be relaunched.
To become a new member of WoT Ğ1 therefore 5 certifications must be obtained at a distance < 5 of 80% of the WoT sentinels.
A member of the TdC Ğ1 is sentinel when he has received and issued at least Y [N] certifications where N is the number of members of the TdC and Y [N] = ceiling N ^ (1/5). Examples:
* For 1024 < N ≤ 3125 we have Y [N] = 5
* For 7776 < N ≤ 16807 we have Y [N] = 7
* For 59049 < N ≤ 100 000 we have Y [N] = 10
Once the new member is part of the WoT Ğ1 his certifications remain valid for 2 years.
To remain a member, you must renew your agreement regularly with your private key (every 12 months) and make sure you have at least 5 certifications valid after 2 years.
Software Ğ1 and license Ğ1
--------------------------
The software Ğ1 allowing users to manage their use of Ğ1 must transmit this license with the software and all the technical parameters of the currency Ğ1 and TdC Ğ1 which are entered in block 0 of Ğ1.
For more details in the technical details it is possible to consult directly the code of Duniter which is a free software and also the data of the blockchain Ğ1 by retrieving it via a Duniter instance or node Ğ1.
More information on the Duniter Team website [https://www.duniter.org](https://www.duniter.org)

View File

@ -0,0 +1,90 @@
Licence Ğ1 - v0.2.5
===================
:date: 2017-04-04 12:59
:modified: 2018-01-24 19:20
**Licence de la monnaie et engagement de responsabilité.**
Toute opération de certification d'un nouveau membre de Ğ1 doit préalablement s'accompagner de la transmission de cette licence de la monnaie Ğ1 dont le certificateur doit s'assurer qu'elle a été étudiée, comprise et acceptée par la personne qui sera certifiée.
Tout événement de rencontre concernant Ğ1 devrait s'accompagner de la transmission de cette licence, qui peut être lue à haute voix, et transmise par tout moyen.
Toile de confiance Ğ1 (TdC Ğ1)
------------------------------
**Avertissement :** Certifier n'est pas uniquement s'assurer que vous avez rencontré la personne, c'est assurer à la communauté Ğ1 que vous connaissez suffisamment bien la personne certifiée et que vous saurez ainsi la contacter facilement, et être en mesure de repérer un double compte effectué par une personne certifiée par vous-même, ou d'autres types de problèmes (disparition...), en effectuant des recoupements qui permettront de révéler le problème le cas échéant.
**Conseils fortement recommandés**
Ne certifiez jamais seul, mais accompagné d'au moins un autre membre de la TdC Ğ1 afin d'éviter toute erreur de manipulation. En cas d'erreur, prévenez immédiatement d'autres membres de la TdC Ğ1.
Avant toute certification, assurez vous de vérifier si son compte (qu'il soit en cours de validation ou déjà membre) a déjà reçu une ou plusieurs certifications. Le cas échéant demandez des informations pour entrer en contact avec ces autres certifieurs afin de vérifier ensemble que vous connaissez bien la personne concernée par la création du nouveau compte, ainsi que la clé publique correspondante.
Vérifiez que vos contacts ont bien étudié et compris la licence Ğ1 à jour.
Si vous vous rendez compte qu'un certifieur effectif ou potentiel du compte concerné ne connaît pas la personne concernée, alertez immédiatement des experts du sujet au sein de vos connaissance de la TdC Ğ1, afin que la procédure de validation soit vérifiée par la TdC Ğ1.
Lorsque vous êtes membre de la TdC Ğ1 et que vous vous apprêtez à certifier un nouveau compte :
**Vous êtes vous assuré :**
1°) D'avoir bien vérifié avec la personne concernée qu'elle a bien généré son document Duniter de révocation de compte, qui lui permettra le cas échéant de pouvoir annuler son compte (cas d'un vol de compte, d'un changement de ID, d'un compte créé à tort etc.).
2°) De suffisamment bien connaître (pas seulement de la connaître "de visu") la personne qui déclare gérer cette clé publique (nouveau compte) et d'avoir personnellement vérifié avec elle qu'il s'agit bien de cette clé publique que vous vous apprêtez à certifier (voir les conseils fortement recommandés ci-dessus pour s'assurer de "bien connaître").
3a°) De la rencontrer physiquement pour vous assurer que c'est bien cette personne que vous connaissez qui gère cette clé publique.
3b°) Ou bien de vérifer à distance le lien personne / clé publique en contactant la personne par plusieurs moyens de communication différents, comme réseau social + forum + mail + vidéo conférence + téléphone (reconnaître la voix). Car si l'on peut pirater un compte mail ou un compte forum, il sera bien plus difficile d'imaginer pirater quatre moyens de communication distincts, et imiter l'apparence (vidéo) ainsi que la voix de la personne en plus.
Le 3a°) restant toutefois préférable au 3b°), tandis que le 1°) et 2°) est toujours indispensable dans tous les cas.
**Règles abrégées de la TdC :**
Chaque membre a un stock de 100 certifications possibles, qu'il ne peut émettre qu'au rythme de 1 certification / 5 jours.
Valable 2 mois, une certification pour un nouveau membre n'est définitivement adoptée que si le certifié possède au moins 4 autres certifications au bout de ces 2 mois, sinon le processus d'entrée devra être relancé.
Pour devenir un nouveau membre de la TdC Ğ1 il faut donc obtenir 5 certifications et ne pas se trouver à une distance < 5 de 80% des membres référents de la TdC.
Un membre de la TdC Ğ1 est membre référent lorsqu'il a reçu et émis au moins Y[N] certifications où N est le nombre de membres de la TdC et Y[N] = plafond N^(1/5). Exemples :
* Pour 1024 < N ≤ 3125 on a Y[N] = 5
* Pour 7776 < N ≤ 16807 on a Y[N] = 7
* pour 59049 < N ≤ 100 000 on a Y[N] = 10
Une fois que le nouveau membre est partie prenante de la TdC Ğ1 ses certifications restent valables 2 ans.
Pour rester membre il faut renouveler son accord régulièrement avec sa clé privée (tous les 12 mois) et s'assurer d'avoir toujours au moins 5 certifications valides au delà des 2 ans.
Monnaie Ğ1
----------
Ğ1 se produit via un Dividende Universel (DU) pour tout être humain membre de la Toile de Confiance Ğ1, qui est de la forme :
* 1 DU par personne et par jour
**Code de la monnaie Ğ1**
Le montant en Ğ1 du DU est identique chaque jour jusqu'au prochain équinoxe où le DU sera alors réévalué selon la formule (avec 1 jour = 86 400 secondes) :
* DUjour(équinoxe suivant) = DUjour(équinoxe) + c² (M/N)(équinoxe) / (182,625 jours)
Avec comme paramètres :
* c = 4,88% / équinoxe
* DU(0) = 10,00 Ğ1
Et comme variables :
* *M* la masse monétaire totale à l'équinoxe
* *N* le nombre de membres à l'équinoxe
Logiciels Ğ1 et licence Ğ1
--------------------------
Les logiciels Ğ1 permettant aux utilisateurs de gérer leur utilisation de Ğ1 doivent transmettre cette licence avec le logiciel ainsi que l'ensemble des paramètres techniques de la monnaie Ğ1 et de la TdC Ğ1 qui sont inscrits dans le bloc 0 de Ğ1.
Pour plus de précisions dans les détails techniques il est possible de consulter directement le code de Duniter qui est un logiciel libre ansi que les données de la blockchain Ğ1 en la récupérant via une instance (ou noeud) Duniter Ğ1.
Plus d'informations sur le site de l'équipe Duniter https://www.duniter.org

View File

@ -0,0 +1,24 @@
{
"name": "licence-g1",
"version": "1.0.0",
"description": "Licence de la Ǧ1",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@git.duniter.org:communication/licence-G1.git"
},
"keywords": [
"licence",
"crypto-currency",
"monnaie",
"libre",
"June",
"G1",
"Ǧ1"
],
"author": "Duniter community",
"license": "ISC"
}

67
silkaj/release.sh Normal file
View File

@ -0,0 +1,67 @@
#!/bin/bash
VERSION=$1
check_argument_specified() {
if [[ -z $VERSION ]]; then
error_message "You should specify a version number as argument"
fi
}
check_version_format() {
if [[ ! $VERSION =~ ^[0-9]+.[0-9]+.[0-9]+[0-9A-Za-z]*$ ]]; then
error_message "Wrong format version"
fi
}
check_branch() {
branch=`git rev-parse --abbrev-ref HEAD`
if [[ "$branch" != "master" ]]; then
error_message "Current branch should be 'master'"
fi
}
update_version() {
sed -i "s/SILKAJ_VERSION = \"silkaj.*\"/SILKAJ_VERSION = \"silkaj $VERSION\"/" src/constants.py
git diff
}
commit_tag() {
git commit src/constants.py -m "v$VERSION"
git tag "v$VERSION" -a -m "$VERSION"
}
build() {
if [[ -z $VIRTUAL_ENV ]]; then
error_message "Activate silkaj-env"
fi
exec_installed pyinstaller
pyinstaller src/silkaj.py --hidden-import=_cffi_backend --hidden-import=_scrypt --onefile
}
checksum() {
# Generate sha256 checksum file
exec_installed sha256sum
cd dist
sha256sum silkaj > silkaj_sha256sum
}
exec_installed() {
if [[ ! `command -v $1` ]]; then
error_message "'$1' is not install on your machine"
fi
}
error_message() {
echo $1
exit
}
check_argument_specified
check_version_format
check_branch
update_version
commit_tag
build
checksum
error_message "Build and checksum can be found in 'dist' folder"

7
silkaj/requirements.txt Normal file
View File

@ -0,0 +1,7 @@
setuptools
commandlines
ipaddress
tabulate
pynacl
scrypt
pyaes

1
silkaj/silkaj Symbolic link
View File

@ -0,0 +1 @@
src/silkaj.py

201
silkaj/src/auth.py Normal file
View File

@ -0,0 +1,201 @@
from tools import get_publickey_from_seed, b58_decode, xor_bytes, message_exit
from nacl import encoding
import nacl.hash
from scrypt import hash
import pyaes
from getpass import getpass
from os import path
from re import compile, search
def auth_method(cli_args):
if cli_args.contains_switches('auth-scrypt'):
return auth_by_scrypt(cli_args)
if cli_args.contains_switches('auth-seed'):
return auth_by_seed()
if cli_args.contains_switches('auth-file'):
return auth_by_auth_file(cli_args)
if cli_args.contains_switches('auth-wif'):
return auth_by_wif()
message_exit("Error: no authentication method")
def generate_auth_file(cli_args):
if cli_args.contains_definitions('file'):
file = cli_args.get_definition('file')
else:
file = "authfile"
seed = auth_method(cli_args)
with open(file, "w") as f:
f.write(seed)
# G1SMS:: Remove verbose text
#print("Authfile generated for the public key: ", get_publickey_from_seed(seed))
print(get_publickey_from_seed(seed))
def auth_by_auth_file(cli_args):
if cli_args.contains_definitions('file'):
file = cli_args.get_definition('file')
else:
file = "authfile"
if not path.isfile(file):
message_exit("Error: the file \"" + file + "\" does not exist")
with open(file) as f:
filetxt = f.read()
regex_seed = compile('^[0-9a-fA-F]{64}$')
regex_gannonce = compile('^pub: [1-9A-HJ-NP-Za-km-z]{43,44}\nsec: [1-9A-HJ-NP-Za-km-z]{88,90}.*$')
# Seed Format
if search(regex_seed, filetxt):
seed = filetxt[0:64]
# gannonce.duniter.org Format
elif search(regex_gannonce, filetxt):
private_key = filetxt.split("sec: ")[1].split("\n")[0]
seed = encoding.HexEncoder.encode(b58_decode(private_key))[0:64].decode("utf-8")
else:
message_exit("Error: the format of the file is invalid")
return seed
def auth_by_seed():
seed = input("Please enter your seed on hex format: ")
regex = compile('^[0-9a-fA-F]{64}$')
if not search(regex, seed):
message_exit("Error: the format of the seed is invalid")
return seed
def auth_by_scrypt(cli_args):
# G1SMS:: Accept salt & password from "cli_args"
if cli_args.contains_definitions('salt') and cli_args.contains_definitions('password'):
salt = cli_args.get_definition('salt')
password = cli_args.get_definition('password')
else:
salt = getpass.getpass("Please enter your Scrypt Salt (Secret identifier): ")
password = getpass.getpass("Please enter your Scrypt password (masked): ")
if cli_args.contains_definitions('n') and cli_args.contains_definitions('r') and cli_args.contains_definitions('p'):
n, r, p = cli_args.get_definition('n'), cli_args.get_definition('r'), cli_args.get_definition('p')
if n.isnumeric() and r.isnumeric() and p.isnumeric():
n, r, p = int(n), int(r), int(p)
if n <= 0 or n > 65536 or r <= 0 or r > 512 or p <= 0 or p > 32:
message_exit("Error: the values of Scrypt parameters are not good")
else:
message_exit("one of n, r or p is not a number")
else:
# G1SMS:: Remove text
#print("Using default values. Scrypt parameters not specified or wrong format")
n, r, p = 4096, 16, 1
#print("Scrypt parameters used: N: {0}, r: {1}, p: {2}".format(n, r, p))
return get_seed_from_scrypt(salt, password, n, r, p)
def auth_by_wif():
wif = input("Please enter your WIF or Encrypted WIF address: ")
regex = compile('^[1-9A-HJ-NP-Za-km-z]*$')
if not search(regex, wif):
message_exit("Error: the format of WIF is invalid")
wif_bytes = b58_decode(wif)
fi = wif_bytes[0:1]
if fi == b'\x01':
return get_seed_from_wifv1(wif)
elif fi == b'\x02':
password = getpass("Please enter the " +
"password of WIF (masked): ")
return get_seed_from_ewifv1(wif, password)
message_exit("Error: the format of WIF is invalid or unknown")
def get_seed_from_scrypt(salt, password, N=4096, r=16, p=1):
seed = hash(password, salt, N, r, p, 32)
seedhex = encoding.HexEncoder.encode(seed).decode("utf-8")
return seedhex
def get_seed_from_wifv1(wif):
regex = compile('^[1-9A-HJ-NP-Za-km-z]*$')
if not search(regex, wif):
message_exit("Error: the format of WIF is invalid")
wif_bytes = b58_decode(wif)
if len(wif_bytes) != 35:
message_exit("Error: the size of WIF is invalid")
checksum_from_wif = wif_bytes[-2:]
fi = wif_bytes[0:1]
seed = wif_bytes[1:-2]
seed_fi = wif_bytes[0:-2]
if fi != b'\x01':
message_exit("Error: It's not a WIF format")
# checksum control
checksum = nacl.hash.sha256(
nacl.hash.sha256(seed_fi, encoding.RawEncoder),
encoding.RawEncoder)[0:2]
if checksum_from_wif != checksum:
message_exit("Error: bad checksum of the WIF")
seedhex = encoding.HexEncoder.encode(seed).decode("utf-8")
return seedhex
def get_seed_from_ewifv1(ewif, password):
regex = compile('^[1-9A-HJ-NP-Za-km-z]*$')
if not search(regex, ewif):
message_exit("Error: the format of EWIF is invalid")
wif_bytes = b58_decode(ewif)
if len(wif_bytes) != 39:
message_exit("Error: the size of EWIF is invalid")
wif_no_checksum = wif_bytes[0:-2]
checksum_from_ewif = wif_bytes[-2:]
fi = wif_bytes[0:1]
salt = wif_bytes[1:5]
encryptedhalf1 = wif_bytes[5:21]
encryptedhalf2 = wif_bytes[21:37]
if fi != b'\x02':
message_exit("Error: It's not a EWIF format")
# Checksum Control
checksum = nacl.hash.sha256(
nacl.hash.sha256(wif_no_checksum, encoding.RawEncoder),
encoding.RawEncoder)[0:2]
if checksum_from_ewif != checksum:
message_exit("Error: bad checksum of EWIF address")
# SCRYPT
password = password.encode("utf-8")
scrypt_seed = hash(password, salt, 16384, 8, 8, 64)
derivedhalf1 = scrypt_seed[0:32]
derivedhalf2 = scrypt_seed[32:64]
# AES
aes = pyaes.AESModeOfOperationECB(derivedhalf2)
decryptedhalf1 = aes.decrypt(encryptedhalf1)
decryptedhalf2 = aes.decrypt(encryptedhalf2)
# XOR
seed1 = xor_bytes(decryptedhalf1, derivedhalf1[0:16])
seed2 = xor_bytes(decryptedhalf2, derivedhalf1[16:32])
seed = seed1+seed2
seedhex = encoding.HexEncoder.encode(seed).decode("utf-8")
# Password Control
salt_from_seed = nacl.hash.sha256(
nacl.hash.sha256(
b58_decode(get_publickey_from_seed(seedhex)),
encoding.RawEncoder),
encoding.RawEncoder)[0:4]
if salt_from_seed != salt:
message_exit("Error: bad Password of EWIF address")
return seedhex

88
silkaj/src/cert.py Normal file
View File

@ -0,0 +1,88 @@
import webbrowser
import urllib
from sys import exit
from pydoc import pager
from tabulate import tabulate
from auth import auth_method
from tools import get_publickey_from_seed, message_exit, sign_document_from_seed
from network_tools import get_current_block, post_request
from constants import NO_MATCHING_ID
from wot import is_member, get_pubkey_from_id, get_pubkeys_from_id,\
get_uid_from_pubkey
def send_certification(ep, cli_args):
current_blk = get_current_block(ep)
certified_uid = cli_args.subsubcmd
certified_pubkey = get_pubkey_from_id(ep, certified_uid)
# Check that the id is present on the network
if (certified_pubkey is NO_MATCHING_ID):
message_exit(NO_MATCHING_ID)
# Display license and ask for confirmation
license_approval(current_blk["currency"])
# Authentication
seed = auth_method(cli_args)
# Check whether current user is member
issuer_pubkey = get_publickey_from_seed(seed)
issuer_id = get_uid_from_pubkey(ep, issuer_pubkey)
if not is_member(ep, issuer_pubkey, issuer_id):
message_exit("Current identity is not member.")
# Check if this certification is already present on the network
id_lookup = get_pubkeys_from_id(ep, certified_uid)[0]
for certifiers in id_lookup["uids"][0]["others"]:
if certifiers["pubkey"] == issuer_pubkey:
message_exit("Identity already certified by " + issuer_id)
# Certification confirmation
if not certification_confirmation(issuer_id, issuer_pubkey, certified_uid, certified_pubkey):
return
cert_doc = generate_certification_document(id_lookup, current_blk, issuer_pubkey, certified_uid)
cert_doc += sign_document_from_seed(cert_doc, seed) + "\n"
# Send certification document
post_request(ep, "wot/certify", "cert=" + urllib.parse.quote_plus(cert_doc))
print("Certification successfully sent.")
def license_approval(currency):
if currency != "g1":
return
language = input("In which language would you like to display Ğ1 license [en/fr]? ")
if (language == "en"):
if not webbrowser.open("https://duniter.org/en/get-g1/"):
pager(open("licence-G1/license/license_g1-en.rst").read())
else:
if not webbrowser.open("https://duniter.org/fr/wiki/licence-g1/"):
pager(open("licence-G1/license/license_g1-fr-FR.rst").read())
if (input("Do you approve Ğ1 license [yes/no]? ") != "yes"):
exit(1)
def certification_confirmation(issuer_id, issuer_pubkey, certified_uid, certified_pubkey):
cert = list()
cert.append(["Cert", "From", ">", "To"])
cert.append(["ID", issuer_id, ">", certified_uid])
cert.append(["Pubkey", issuer_pubkey, ">", certified_pubkey])
if input(tabulate(cert, tablefmt="fancy_grid") +
"\nDo you confirm sending this certification? [yes/no]: ") == "yes":
return True
def generate_certification_document(id_lookup, current_blk, issuer_pubkey, certified_uid):
return "Version: 10\n\
Type: Certification\n\
Currency: " + current_blk["currency"] + "\n\
Issuer: " + issuer_pubkey + "\n\
IdtyIssuer: " + id_lookup["pubkey"] + "\n\
IdtyUniqueID: " + certified_uid + "\n\
IdtyTimestamp: " + id_lookup["uids"][0]["meta"]["timestamp"] + "\n\
IdtySignature: " + id_lookup["uids"][0]["self"] + "\n\
CertTimestamp: " + str(current_blk["number"]) + "-" + current_blk["hash"] + "\n"

249
silkaj/src/commands.py Normal file
View File

@ -0,0 +1,249 @@
from datetime import datetime
from time import sleep
from os import system, popen
from collections import OrderedDict
from tabulate import tabulate
from operator import itemgetter
from wot import get_uid_from_pubkey
from network_tools import discover_peers, get_request, best_node, get_current_block
from tools import convert_time, get_currency_symbol, message_exit
from constants import NO_MATCHING_ID
def currency_info(ep):
info_type = ["newcomers", "certs", "actives", "leavers", "excluded", "ud", "tx"]
i, info_data = 0, dict()
while (i < len(info_type)):
info_data[info_type[i]] = get_request(ep, "blockchain/with/" + info_type[i])["result"]["blocks"]
i += 1
current = get_current_block(ep)
system("clear")
print("Connected to node:", ep[best_node(ep, 1)], ep["port"],
"\nCurrent block number:", current["number"],
"\nCurrency name:", get_currency_symbol(current["currency"]),
"\nNumber of members:", current["membersCount"],
"\nMinimal Proof-of-Work:", current["powMin"],
"\nCurrent time:", convert_time(current["time"], "all"),
"\nMedian time:", convert_time(current["medianTime"], "all"),
"\nDifference time:", convert_time(current["time"] - current["medianTime"], "hour"),
"\nNumber of blocks containing: \
\n- new comers:", len(info_data["newcomers"]),
"\n- Certifications:", len(info_data["certs"]),
"\n- Actives (members updating their membership):", len(info_data["actives"]),
"\n- Leavers:", len(info_data["leavers"]),
"\n- Excluded:", len(info_data["excluded"]),
"\n- UD created:", len(info_data["ud"]),
"\n- transactions:", len(info_data["tx"]))
def match_pattern(pow, match='', p=1):
while pow > 0:
if pow >= 16:
match += "0"
pow -= 16
p *= 16
else:
match += "[0-" + hex(15 - pow)[2:].upper() + "]"
p *= pow
pow = 0
return match + '*', p
def power(nbr, pow=0):
while nbr >= 10:
nbr /= 10
pow += 1
return "{0:.1f} × 10^{1}".format(nbr, pow)
def difficulties(ep):
while True:
diffi = get_request(ep, "blockchain/difficulties")
levels = [OrderedDict((i, d[i]) for i in ("uid", "level")) for d in diffi["levels"]]
diffi["levels"] = levels
current = get_current_block(ep)
issuers, sorted_diffi = 0, sorted(diffi["levels"], key=itemgetter("level"), reverse=True)
for d in diffi["levels"]:
if d["level"] / 2 < current["powMin"]:
issuers += 1
d["match"] = match_pattern(d["level"])[0][:20]
d["Π diffi"] = power(match_pattern(d["level"])[1])
d["Σ diffi"] = d.pop("level")
system("clear")
print("Minimal Proof-of-Work: {0} to match `{1}`\nDifficulty to generate next block n°{2} for {3}/{4} nodes:\n{5}"
.format(current["powMin"], match_pattern(int(current["powMin"]))[0], diffi["block"], issuers, len(diffi["levels"]),
tabulate(sorted_diffi, headers="keys", tablefmt="orgtbl", stralign="center")))
sleep(5)
network_sort_keys = ["block", "member", "diffi", "uid"]
def set_network_sort_keys(some_keys):
global network_sort_keys
if some_keys.endswith(","):
message_exit("Argument 'sort' ends with a comma, you have probably inserted a space after the comma, which is incorrect.")
network_sort_keys = some_keys.split(",")
def get_network_sort_key(endpoint):
t = list()
for akey in network_sort_keys:
if akey == 'diffi' or akey == 'block' or akey == 'port':
t.append(int(endpoint[akey]) if akey in endpoint else 0)
else:
t.append(str(endpoint[akey]) if akey in endpoint else "")
return tuple(t)
def network_info(ep, discover):
rows, columns = popen('stty size', 'r').read().split()
# print(rows, columns) # debug
wide = int(columns)
if wide < 146:
message_exit("Wide screen need to be larger than 146. Current wide: " + wide)
# discover peers
# and make sure fields are always ordered the same
endpoints = [OrderedDict((i, p.get(i, None)) for i in ("domain", "port", "ip4", "ip6", "pubkey")) for p in discover_peers(ep, discover)]
# Todo : renommer endpoints en info
diffi = get_request(ep, "blockchain/difficulties")
i, members = 0, 0
print("Getting informations about nodes:")
while (i < len(endpoints)):
print("{0:.0f}%".format(i/len(endpoints) * 100, 1), end=" ")
best_ep = best_node(endpoints[i], 0)
print(best_ep if best_ep is None else endpoints[i][best_ep], end=" ")
print(endpoints[i]["port"])
try:
endpoints[i]["uid"] = get_uid_from_pubkey(ep, endpoints[i]["pubkey"])
if endpoints[i]["uid"] is NO_MATCHING_ID:
endpoints[i]["uid"] = None
else:
endpoints[i]["member"] = "yes"
members += 1
except:
pass
if endpoints[i].get("member") is None:
endpoints[i]["member"] = "no"
endpoints[i]["pubkey"] = endpoints[i]["pubkey"][:5] + ""
# Todo: request difficulty from node point of view: two nodes with same pubkey id could be on diffrent branches and have different difficulties
# diffi = get_request(endpoints[i], "blockchain/difficulties") # super long, doit être requetté uniquement pour les nœuds dune autre branche
for d in diffi["levels"]:
if endpoints[i].get("uid") is not None:
if endpoints[i]["uid"] == d["uid"]:
endpoints[i]["diffi"] = d["level"]
if len(endpoints[i]["uid"]) > 10:
endpoints[i]["uid"] = endpoints[i]["uid"][:9] + ""
current_blk = get_current_block(endpoints[i])
if current_blk is not None:
endpoints[i]["gen_time"] = convert_time(current_blk["time"], "hour")
if wide > 171:
endpoints[i]["mediantime"] = convert_time(current_blk["medianTime"], "hour")
if wide > 185:
endpoints[i]["difftime"] = convert_time(current_blk["time"] - current_blk["medianTime"], "hour")
endpoints[i]["block"] = current_blk["number"]
endpoints[i]["hash"] = current_blk["hash"][:10] + ""
endpoints[i]["version"] = get_request(endpoints[i], "node/summary")["duniter"]["version"]
if endpoints[i].get("domain") is not None and len(endpoints[i]["domain"]) > 20:
endpoints[i]["domain"] = "" + endpoints[i]["domain"][-20:]
if endpoints[i].get("ip6") is not None:
if wide < 156:
endpoints[i].pop("ip6")
else:
endpoints[i]["ip6"] = endpoints[i]["ip6"][:8] + ""
i += 1
system("clear")
print(len(endpoints), "peers ups, with", members, "members and", len(endpoints) - members, "non-members at", datetime.now().strftime("%H:%M:%S"))
endpoints = sorted(endpoints, key=get_network_sort_key)
print(tabulate(endpoints, headers="keys", tablefmt="orgtbl", stralign="center"))
def list_issuers(ep, nbr, last):
current_blk = get_current_block(ep)
current_nbr = current_blk["number"]
if nbr == 0:
nbr = current_blk["issuersFrame"]
url = "blockchain/blocks/" + str(nbr) + "/" + str(current_nbr - nbr + 1)
blocks, list_issuers, j = get_request(ep, url), list(), 0
issuers_dict = dict()
while j < len(blocks):
issuer = OrderedDict()
issuer["pubkey"] = blocks[j]["issuer"]
if last or nbr <= 30:
issuer["block"] = blocks[j]["number"]
issuer["gentime"] = convert_time(blocks[j]["time"], "hour")
issuer["mediantime"] = convert_time(blocks[j]["medianTime"], "hour")
issuer["hash"] = blocks[j]["hash"][:10]
issuers_dict[issuer["pubkey"]] = issuer
list_issuers.append(issuer)
j += 1
for pubkey in issuers_dict.keys():
issuer = issuers_dict[pubkey]
uid = get_uid_from_pubkey(ep, issuer["pubkey"])
for issuer2 in list_issuers:
if issuer2.get("pubkey") is not None and issuer.get("pubkey") is not None and \
issuer2["pubkey"] == issuer["pubkey"]:
issuer2["uid"] = uid
issuer2.pop("pubkey")
system("clear")
print("Issuers for last {0} blocks from block n°{1} to block n°{2}".format(nbr, current_nbr - nbr + 1, current_nbr), end=" ")
if last or nbr <= 30:
sorted_list = sorted(list_issuers, key=itemgetter("block"), reverse=True)
print("\n{0}".format(tabulate(sorted_list, headers="keys", tablefmt="orgtbl", stralign="center")))
else:
i, list_issued = 0, list()
while i < len(list_issuers):
j, found = 0, 0
while j < len(list_issued):
if list_issued[j].get("uid") is not None and \
list_issued[j]["uid"] == list_issuers[i]["uid"]:
list_issued[j]["blocks"] += 1
found = 1
break
j += 1
if found == 0:
issued = OrderedDict()
issued["uid"] = list_issuers[i]["uid"]
issued["blocks"] = 1
list_issued.append(issued)
i += 1
i = 0
while i < len(list_issued):
list_issued[i]["percent"] = list_issued[i]["blocks"] / nbr * 100
i += 1
sorted_list = sorted(list_issued, key=itemgetter("blocks"), reverse=True)
print("from {0} issuers\n{1}".format(len(list_issued),
tabulate(sorted_list, headers="keys", tablefmt="orgtbl", floatfmt=".1f", stralign="center")))
def argos_info(ep):
info_type = ["newcomers", "certs", "actives", "leavers", "excluded", "ud", "tx"]
pretty_names = {'g1': 'Ğ1', 'gtest': 'Ğtest'}
i, info_data = 0, dict()
while (i < len(info_type)):
info_data[info_type[i]] = get_request(ep, "blockchain/with/" + info_type[i])["result"]["blocks"]
i += 1
current = get_current_block(ep)
pretty = current["currency"]
if current["currency"] in pretty_names:
pretty = pretty_names[current["currency"]]
print(pretty, "|")
print("---")
href = 'href=http://%s:%s/' % (ep[best_node(ep, 1)], ep["port"])
print("Connected to node:", ep[best_node(ep, 1)], ep["port"], "|", href,
"\nCurrent block number:", current["number"],
"\nCurrency name:", get_currency_symbol(current["currency"]),
"\nNumber of members:", current["membersCount"],
"\nMinimal Proof-of-Work:", current["powMin"],
"\nCurrent time:", convert_time(current["time"], "all"),
"\nMedian time:", convert_time(current["medianTime"], "all"),
"\nDifference time:", convert_time(current["time"] - current["medianTime"], "hour"),
"\nNumber of blocks containing… \
\n-- new comers:", len(info_data["newcomers"]),
"\n-- Certifications:", len(info_data["certs"]),
"\n-- Actives (members updating their membership):", len(info_data["actives"]),
"\n-- Leavers:", len(info_data["leavers"]),
"\n-- Excluded:", len(info_data["excluded"]),
"\n-- UD created:", len(info_data["ud"]),
"\n-- transactions:", len(info_data["tx"]))

5
silkaj/src/constants.py Normal file
View File

@ -0,0 +1,5 @@
SILKAJ_VERSION = "silkaj 0.5.0"
NO_MATCHING_ID = "No matching identity"
G1_SYMBOL = "Ğ1"
GTEST_SYMBOL = "ĞTest"
G1_DEFAULT_ENDPOINT = "duniter.moul.re", "443"

119
silkaj/src/money.py Normal file
View File

@ -0,0 +1,119 @@
from network_tools import get_request, get_current_block
from tools import get_currency_symbol, get_publickey_from_seed
from auth import auth_method
from wot import check_public_key
def cmd_amount(ep, cli_args):
if not cli_args.subsubcmd.startswith("--"):
pubkeys = cli_args.subsubcmd.split(":")
for pubkey in pubkeys:
pubkey = check_public_key(pubkey, True)
if not pubkey:
return
total = [0, 0]
for pubkey in pubkeys:
value = get_amount_from_pubkey(ep, pubkey)
show_amount_from_pubkey(ep, pubkey, value)
total[0] += value[0]
total[1] += value[1]
if (len(pubkeys) > 1):
show_amount_from_pubkey(ep, "Total", total)
else:
seed = auth_method(cli_args)
pubkey = get_publickey_from_seed(seed)
show_amount_from_pubkey(ep, pubkey, get_amount_from_pubkey(ep, pubkey))
def show_amount_from_pubkey(ep, pubkey, value):
totalAmountInput = value[0]
amount = value[1]
# output
UDvalue = get_last_ud_value(ep)
current_blk = get_current_block(ep)
currency_symbol = get_currency_symbol(current_blk["currency"])
"""
if totalAmountInput - amount != 0:
print("Blockchain:")
print("-----------")
print("Relative =", round(amount / UDvalue, 2), "UD", currency_symbol)
print("Quantitative =", round(amount / 100, 2), currency_symbol + "\n")
print("Pending Transaction:")
print("--------------------")
print("Relative =", round((totalAmountInput - amount) / UDvalue, 2), "UD", currency_symbol)
print("Quantitative =", round((totalAmountInput - amount) / 100, 2), currency_symbol + "\n")
print("Total amount of: " + pubkey)
print("----------------------------------------------------------------")
print("Total Relative =", round(totalAmountInput / UDvalue, 2), "UD", currency_symbol)
print("Total Quantitative =", round(totalAmountInput / 100, 2), currency_symbol + "\n")
"""
# G1SMS:: SEND WALLET TOTAL AMOUNT
print(round(totalAmountInput / 100, 2))
def get_amount_from_pubkey(ep, pubkey):
sources = get_request(ep, "tx/sources/" + pubkey)["sources"]
listinput = []
amount = 0
for source in sources:
if source["conditions"] == "SIG(" + pubkey + ")":
amount += source["amount"] * 10 ** source["base"]
listinput.append(str(source["amount"]) + ":" +
str(source["base"]) + ":" +
str(source["type"]) + ":" +
str(source["identifier"]) + ":" +
str(source["noffset"]))
# pending source
history = get_request(ep, "tx/history/" + pubkey + "/pending")["history"]
pendings = history["sending"] + history["receiving"] + history["pending"]
# print(pendings)
current_blk = get_current_block(ep)
last_block_number = int(current_blk["number"])
# add pending output
for pending in pendings:
blockstamp = pending["blockstamp"]
block_number = int(blockstamp.split("-")[0])
# if it's not an old transaction (bug in mirror node)
if block_number >= last_block_number - 3:
identifier = pending["hash"]
i = 0
for output in pending["outputs"]:
outputsplited = output.split(":")
if outputsplited[2] == "SIG(" + pubkey + ")":
inputgenerated = (
str(outputsplited[0]) + ":" +
str(outputsplited[1]) + ":T:" +
identifier + ":" + str(i)
)
if inputgenerated not in listinput:
listinput.append(inputgenerated)
i += 1
# remove input already used
for pending in pendings:
blockstamp = pending["blockstamp"]
block_number = int(blockstamp.split("-")[0])
# if it's not an old transaction (bug in mirror node)
if block_number >= last_block_number - 3:
for input in pending["inputs"]:
if input in listinput:
listinput.remove(input)
totalAmountInput = 0
for input in listinput:
inputsplit = input.split(":")
totalAmountInput += int(inputsplit[0]) * 10 ** int(inputsplit[1])
return int(totalAmountInput), int(amount)
def get_last_ud_value(ep):
blockswithud = get_request(ep, "blockchain/with/ud")["result"]
NBlastUDblock = blockswithud["blocks"][-1]
lastUDblock = get_request(ep, "blockchain/block/" + str(NBlastUDblock))
return lastUDblock["dividend"] * 10 ** lastUDblock["unitbase"]

162
silkaj/src/network_tools.py Normal file
View File

@ -0,0 +1,162 @@
from __future__ import unicode_literals
from ipaddress import ip_address
from json import loads
import socket
import urllib.request
from sys import exit, stderr
def discover_peers(ep, discover):
"""
From first node, discover his known nodes.
Remove from know nodes if nodes are down.
If discover option: scan all network to know all nodes.
display percentage discovering.
"""
endpoints = parse_endpoints(get_request(ep, "network/peers")["peers"])
if discover:
print("Discovering network")
for i, ep in enumerate(endpoints):
if discover:
print("{0:.0f}%".format(i / len(endpoints) * 100))
if best_node(ep, 0) is None:
endpoints.remove(ep)
elif discover:
endpoints = recursive_discovering(endpoints, ep)
return endpoints
def recursive_discovering(endpoints, ep):
"""
Discover recursively new nodes.
If new node found add it and try to found new node from his known nodes.
"""
news = parse_endpoints(get_request(ep, "network/peers")["peers"])
for new in news:
if best_node(new, 0) is not None and new not in endpoints:
endpoints.append(new)
recursive_discovering(endpoints, new)
return endpoints
def parse_endpoints(rep):
"""
endpoints[]{"domain", "ip4", "ip6", "pubkey"}
list of dictionaries
reps: raw endpoints
"""
i, j, endpoints = 0, 0, []
while (i < len(rep)):
if (rep[i]["status"] == "UP"):
while j < len(rep[i]["endpoints"]):
ep = parse_endpoint(rep[i]["endpoints"][j])
j += 1
if ep is None:
break
ep["pubkey"] = rep[i]["pubkey"]
endpoints.append(ep)
i += 1
j = 0
return endpoints
def parse_endpoint(rep):
"""
rep: raw endpoint, sep: split endpoint
domain, ip4 or ip6 could miss on raw endpoint
"""
ep, sep = {}, rep.split(" ")
if sep[0] == "BASIC_MERKLED_API":
if check_port(sep[-1]):
ep["port"] = sep[-1]
if len(sep) == 5 and check_ip(sep[1]) == 0 and check_ip(sep[2]) == 4 and check_ip(sep[3]) == 6:
ep["domain"], ep["ip4"], ep["ip6"] = sep[1], sep[2], sep[3]
if len(sep) == 4:
ep = endpoint_type(sep[1], ep)
ep = endpoint_type(sep[2], ep)
if len(sep) == 3:
ep = endpoint_type(sep[1], ep)
return ep
else:
return None
def endpoint_type(sep, ep):
typ = check_ip(sep)
if typ == 0:
ep["domain"] = sep
elif typ == 4:
ep["ip4"] = sep
elif typ == 6:
ep["ip6"] = sep
return ep
def check_ip(address):
try:
return ip_address(address).version
except:
return 0
def get_request(ep, path):
address = best_node(ep, 0)
if address is None:
return address
url = "http://" + ep[address] + ":" + ep["port"] + "/" + path
if ep["port"] == "443":
url = "https://" + ep[address] + "/" + path
request = urllib.request.Request(url)
response = urllib.request.urlopen(request)
encoding = response.info().get_content_charset('utf8')
return loads(response.read().decode(encoding))
def post_request(ep, path, postdata):
address = best_node(ep, 0)
if address is None:
return address
url = "http://" + ep[address] + ":" + ep["port"] + "/" + path
if ep["port"] == "443":
url = "https://" + ep[address] + "/" + path
request = urllib.request.Request(url, bytes(postdata, 'utf-8'))
try:
response = urllib.request.urlopen(request)
except urllib.error.URLError as e:
print(e, file=stderr)
exit(1)
encoding = response.info().get_content_charset('utf8')
return loads(response.read().decode(encoding))
def best_node(ep, main):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
addresses, port = {"ip6", "ip4", "domain"}, int(ep["port"])
for address in addresses:
if address in ep:
try:
s.connect((ep[address], port))
s.close()
return address
except:
pass
if main:
print("Wrong node gived as argument", file=stderr)
exit(1)
return None
def check_port(port):
try:
port = int(port)
except:
print("Port must be an integer", file=stderr)
exit(1)
if (port < 0 or port > 65536):
print("Wrong port number", file=stderr)
exit(1)
return 1
def get_current_block(ep):
return get_request(ep, "blockchain/current")

137
silkaj/src/silkaj.py Normal file
View File

@ -0,0 +1,137 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sys import stderr
from commandlines import Command
from tx import send_transaction
from money import cmd_amount
from cert import send_certification
from commands import currency_info, difficulties, set_network_sort_keys,\
network_info, argos_info, list_issuers
from tools import message_exit
from network_tools import check_port, best_node
from wot import received_sent_certifications, id_pubkey_correspondence
from auth import generate_auth_file
from constants import SILKAJ_VERSION, G1_DEFAULT_ENDPOINT
def usage():
message_exit("Silkaj: command line Duniter client \
\n\nhelp: -h, --help, --usage \
\nversion: -v, --version \
\n \
\nCustom endpoint with option `-p` and <domain>:<port>\
\n \
\nCommands: \
\n - info: Display information about currency \
\n \
\n - amount: Get amount of accounts \
\n pubkeys and/or ids separated with colon: <pubkey:id:pubkey>\
\n --auth-scrypt [script parameters -n <N> -r <r> -p <p>] (default: 4096,16,1)\
\n --auth-seed | --auth-file [--file=<path file>] | --auth-wif\
\n \
\n - tx/transaction: Send transaction\
\n - authentication:\
\n --auth-scrypt [script parameters -n <N> -r <r> -p <p>] (default: 4096,16,1)\
\n --auth-seed | --auth-file [--file=<path file>] | --auth-wif\
\n - amount:\
\n --amountUD=<relative value> | --amount=<quantitative value>\
\n [--allSources] \
\n --output=<public key>[:checksum] \
\n [--comment=<comment>] \
\n [--outputBackChange=<public key[:checksum]>] \
\n [-y | --yes], don't ask for prompt confirmation \
\n \
\n - cert: Send certification\
\n - e.g.: silkaj cert <id> <auth>\
\n - authentication:\
\n --auth-scrypt [script parameters -n <N> -r <r> -p <p>] (default: 4096,16,1)\
\n --auth-seed | --auth-file [--file=<path file>] | --auth-wif\
\n \
\n - net/network: Display current network with many information \
\n [--discover] Discover all network (could take a while), optional \
\n [-s | --sort] Sort column names comma-separated (for example \"-s block,diffi\"), optional \
\n Default sort is block,member,diffi,uid \
\n \
\n - diffi: list proof-of-work difficulty to generate next block \
\n \
\n - issuers n: display last n issuers (`0` for current window size) \
\n last issuers are displayed under n <= 30.\
\n To force display last ones, use `--last` option\
\n \
\n - argos: display currency information formated for Argos or BitBar\
\n \
\n - generate_auth_file: Generate file to store the seed of the account\
\n --auth-scrypt [script parameters -n <N> -r <r> -p <p>] (default: 4096,16,1)\
\n --auth-seed | --auth-file [--file=<path file>] | --auth-wif\
\n \
\n - id/identities <pubkey> or <identity>: get corresponding identity or pubkey from pubkey or identity.\
\n it could autocomplete the pubkey corresponding to an identity with three or four following characters.\
\n \
\n - wot <pubkey> or <identity>: display received and sent certifications for an account.")
def cli():
# ep: endpoint, node's network interface
ep, cli_args = dict(), Command()
subcmd = ["info", "diffi", "net", "network", "issuers", "argos", "amount", "tx", "transaction", "cert", "generate_auth_file", "id", "identities", "wot"]
if cli_args.is_version_request():
message_exit(SILKAJ_VERSION)
if cli_args.is_help_request() or cli_args.is_usage_request() or cli_args.subcmd not in subcmd:
usage()
ep["domain"], ep["port"] = G1_DEFAULT_ENDPOINT
try:
ep["domain"], ep["port"] = cli_args.get_definition('p').rsplit(':', 1)
except:
# G1SMS:: Remove verbose text
#print("Requested default node: <{}:{}>".format(ep["domain"], ep["port"]), file=stderr)
pass
if ep["domain"].startswith('[') and ep["domain"].endswith(']'):
ep["domain"] = ep["domain"][1:-1]
return ep, cli_args
def manage_cmd(ep, c):
if cli_args.subcmd == "info":
currency_info(ep)
elif cli_args.subcmd == "diffi":
difficulties(ep)
elif cli_args.subcmd == "net" or cli_args.subcmd == "network":
if cli_args.contains_switches("sort"):
set_network_sort_keys(cli_args.get_definition("sort"))
if cli_args.contains_switches("s"):
set_network_sort_keys(cli_args.get_definition("s"))
network_info(ep, cli_args.contains_switches("discover"))
elif cli_args.subcmd == "issuers" and cli_args.subsubcmd and int(cli_args.subsubcmd) >= 0:
list_issuers(ep, int(cli_args.subsubcmd), cli_args.contains_switches('last'))
elif cli_args.subcmd == "argos":
argos_info(ep)
elif cli_args.subcmd == "amount" and cli_args.subsubcmd:
cmd_amount(ep, cli_args)
elif cli_args.subcmd == "tx" or cli_args.subcmd == "transaction":
send_transaction(ep, cli_args)
elif cli_args.subcmd == "cert":
send_certification(ep, c)
elif cli_args.subcmd == "generate_auth_file":
generate_auth_file(cli_args)
elif cli_args.subcmd == "id" or cli_args.subcmd == "identities":
id_pubkey_correspondence(ep, cli_args.subsubcmd)
elif cli_args.subcmd == "wot":
received_sent_certifications(ep, cli_args.subsubcmd)
if __name__ == '__main__':
ep, cli_args = cli()
check_port(ep["port"])
best_node(ep, 1)
manage_cmd(ep, cli_args)

140
silkaj/src/tools.py Normal file
View File

@ -0,0 +1,140 @@
from datetime import datetime
from nacl import encoding, signing, hash, bindings
from re import compile, search
from sys import exit
from constants import G1_SYMBOL, GTEST_SYMBOL
def convert_time(timestamp, kind):
ts = int(timestamp)
date = "%Y-%m-%d"
hour = "%H:%M"
second = ":%S"
if kind == "all":
pattern = date + " " + hour + second
elif kind == "date":
pattern = date
elif kind == "hour":
pattern = hour
if ts >= 3600:
pattern += second
return datetime.fromtimestamp(ts).strftime(pattern)
def get_currency_symbol(currency):
if currency == "g1":
return G1_SYMBOL
elif currency == "g1-test":
return GTEST_SYMBOL
def sign_document_from_seed(document, seed):
seed = bytes(seed, 'utf-8')
signing_key = signing.SigningKey(seed, encoding.HexEncoder)
signed = signing_key.sign(bytes(document, 'utf-8'))
signed_b64 = encoding.Base64Encoder.encode(signed.signature)
return signed_b64.decode("utf-8")
def get_publickey_from_seed(seed):
seed = bytes(seed, 'utf-8')
seed = encoding.HexEncoder.decode(seed)
public_key, secret_key = bindings.crypto_sign_seed_keypair(seed)
return b58_encode(public_key)
def check_public_key(pubkey, display_error):
"""
Check public key format
Check pubkey checksum which could be append after the pubkey
If check pass: return pubkey
"""
regex = compile('^[1-9A-HJ-NP-Za-km-z]{43,44}$')
regex_checksum = compile('^[1-9A-HJ-NP-Za-km-z]{43,44}' +
':[1-9A-HJ-NP-Za-km-z]{3}$')
if search(regex, pubkey):
return pubkey
elif search(regex_checksum, pubkey):
pubkey, checksum = pubkey.split(":")
pubkey_byte = b58_decode(pubkey)
checksum_calculed = b58_encode(hash.sha256(
hash.sha256(pubkey_byte, encoding.RawEncoder),
encoding.RawEncoder))[:3]
if checksum_calculed == checksum:
return pubkey
else:
print("error: bad checksum of the public key")
return False
elif display_error:
print("Error: the format of the public key is invalid")
return False
b58_digits = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
def b58_encode(b):
# Convert big-endian bytes to integer
n = int('0x0' + encoding.HexEncoder.encode(b).decode('utf8'), 16)
# Divide that integer into base58
res = []
while n > 0:
n, r = divmod(n, 58)
res.append(b58_digits[r])
res = ''.join(res[::-1])
# Encode leading zeros as base58 zeros
czero = 0
pad = 0
for c in b:
if c == czero:
pad += 1
else:
break
return b58_digits[0] * pad + res
def b58_decode(s):
if not s:
return b''
# Convert the string to an integer
n = 0
for c in s:
n *= 58
if c not in b58_digits:
raise InvalidBase58Error('Character %r is not a ' +
'valid base58 character' % c)
digit = b58_digits.index(c)
n += digit
# Convert the integer to bytes
h = '%x' % n
if len(h) % 2:
h = '0' + h
res = encoding.HexEncoder.decode(h.encode('utf8'))
# Add padding back.
pad = 0
for c in s[:-1]:
if c == b58_digits[0]:
pad += 1
else:
break
return b'\x00' * pad + res
def xor_bytes(b1, b2):
result = bytearray()
for b1, b2 in zip(b1, b2):
result.append(b1 ^ b2)
return result
def message_exit(message):
print(message)
exit(1)

279
silkaj/src/tx.py Normal file
View File

@ -0,0 +1,279 @@
from re import compile, search
import math
from time import sleep
from sys import exit
import urllib
from tabulate import tabulate
from network_tools import get_request, post_request, get_current_block
from tools import get_currency_symbol, get_publickey_from_seed, sign_document_from_seed,\
check_public_key, message_exit
from auth import auth_method
from wot import get_uid_from_pubkey
from money import get_last_ud_value, get_amount_from_pubkey
from constants import NO_MATCHING_ID
def send_transaction(ep, cli_args):
"""
Main function
"""
ud = get_last_ud_value(ep)
amount, output, comment, allSources, outputBackChange = cmd_transaction(cli_args, ud)
check_transaction_values(comment, output, outputBackChange)
seed = auth_method(cli_args)
issuer_pubkey = get_publickey_from_seed(seed)
tx_confirmation = transaction_confirmation(ep, cli_args, issuer_pubkey, amount, ud, output, comment)
if cli_args.contains_switches('yes') or cli_args.contains_switches('y') or \
input(tabulate(tx_confirmation, tablefmt="fancy_grid") +
"\nDo you confirm sending this transaction? [yes/no]: ") == "yes":
generate_and_send_transaction(ep, seed, issuer_pubkey, amount, output, comment, allSources, outputBackChange)
def cmd_transaction(cli_args, ud):
"""
Retrieve values from command line interface
"""
if not (cli_args.contains_definitions('amount') or cli_args.contains_definitions('amountUD')):
message_exit("--amount or --amountUD is not set")
if not cli_args.contains_definitions('output'):
message_exit("--output is not set")
if cli_args.contains_definitions('amount'):
amount = float(cli_args.get_definition('amount')) * 100
if cli_args.contains_definitions('amountUD'):
amount = float(cli_args.get_definition('amountUD')) * ud
output = cli_args.get_definition('output')
comment = cli_args.get_definition('comment') if cli_args.contains_definitions('comment') else ""
allSources = cli_args.contains_switches('allSources')
if cli_args.contains_definitions('outputBackChange'):
outputBackChange = cli_args.get_definition('outputBackChange')
else:
outputBackChange = None
return amount, output, comment, allSources, outputBackChange
def check_transaction_values(comment, output, outputBackChange):
checkComment(comment)
output = check_public_key(output, True)
if outputBackChange:
outputBackChange = check_public_key(outputBackChange, True)
if output is False or outputBackChange is False:
exit(1)
def transaction_confirmation(ep, c, issuer_pubkey, amount, ud, output, comment):
"""
Generate transaction confirmation
"""
tx = list()
currency_symbol = get_currency_symbol(get_current_block(ep)["currency"])
tx.append(["amount (" + currency_symbol + ")", amount / 100])
tx.append(["amount (UD " + currency_symbol + ")", amount / ud])
tx.append(["from", issuer_pubkey])
id_from = get_uid_from_pubkey(ep, issuer_pubkey)
if id_from is not NO_MATCHING_ID:
tx.append(["from (id)", id_from])
tx.append(["to", output])
id_to = get_uid_from_pubkey(ep, output)
if id_to is not NO_MATCHING_ID:
tx.append(["to (id)", id_to])
tx.append(["comment", comment])
return tx
def generate_and_send_transaction(ep, seed, issuers, AmountTransfered, outputAddr, Comment="", all_input=False, OutputbackChange=None):
totalamount = get_amount_from_pubkey(ep, issuers)[0]
if totalamount < AmountTransfered:
# G1SMS :: Format simple data output
#message_exit("the account: " + issuers + " don't have enough money for this transaction")
print("KO|" + str(totalamount / 100))
sys.exit(1)
while True:
listinput_and_amount = get_list_input_for_transaction(ep, issuers, AmountTransfered, all_input)
intermediatetransaction = listinput_and_amount[2]
if intermediatetransaction:
totalAmountInput = listinput_and_amount[1]
"""
print("Generate Change Transaction")
print(" - From: " + issuers)
print(" - To: " + issuers)
print(" - Amount: " + str(totalAmountInput / 100))
"""
transaction = generate_transaction_document(ep, issuers, totalAmountInput, listinput_and_amount, issuers, "Change operation")
transaction += sign_document_from_seed(transaction, seed) + "\n"
post_request(ep, "tx/process", "transaction=" + urllib.parse.quote_plus(transaction))
#print("Change Transaction successfully sent.")
print("Solde : " + format(totalamount) + " " + get_current_block(ep)["currency"] )
sleep(1) # wait 1 second before sending a new transaction
else:
"""
print("Generate Transaction:")
print(" - From: " + issuers)
print(" - To: " + outputAddr)
if all_input:
print(" - Amount: " + str(listinput_and_amount[1] / 100))
else:
print(" - Amount: " + str(AmountTransfered / 100))
"""
transaction = generate_transaction_document(ep, issuers, AmountTransfered, listinput_and_amount, outputAddr, Comment, OutputbackChange)
transaction += sign_document_from_seed(transaction, seed) + "\n"
post_request(ep, "tx/process", "transaction=" + urllib.parse.quote_plus(transaction))
#print("Transaction successfully sent.")
print( str(AmountTransfered / 100) + "|" + str( (totalamount - AmountTransfered)/100 ) )
break
def generate_transaction_document(ep, issuers, AmountTransfered, listinput_and_amount, outputaddr, Comment="", OutputbackChange=None):
check_public_key(outputaddr, True)
if OutputbackChange:
OutputbackChange = check_public_key(OutputbackChange, True)
listinput = listinput_and_amount[0]
totalAmountInput = listinput_and_amount[1]
current_blk = get_current_block(ep)
currency_name = current_blk["currency"]
blockstamp_current = str(current_blk["number"]) + "-" + str(current_blk["hash"])
curentUnitBase = current_blk["unitbase"]
if not OutputbackChange:
OutputbackChange = issuers
# if it's not a foreign exchange transaction, we remove units after 2 digits after the decimal point.
if issuers != outputaddr:
AmountTransfered = (AmountTransfered // 10 ** curentUnitBase) * 10 ** curentUnitBase
# Generate output
################
listoutput = []
# Outputs to receiver (if not himself)
rest = AmountTransfered
unitbase = curentUnitBase
while rest > 0:
outputAmount = truncBase(rest, unitbase)
rest -= outputAmount
if outputAmount > 0:
outputAmount = int(outputAmount / math.pow(10, unitbase))
listoutput.append(str(outputAmount) + ":" + str(unitbase) + ":SIG(" + outputaddr + ")")
unitbase = unitbase - 1
# Outputs to himself
unitbase = curentUnitBase
rest = totalAmountInput - AmountTransfered
while rest > 0:
outputAmount = truncBase(rest, unitbase)
rest -= outputAmount
if outputAmount > 0:
outputAmount = int(outputAmount / math.pow(10, unitbase))
listoutput.append(str(outputAmount) + ":" + str(unitbase) + ":SIG(" + OutputbackChange + ")")
unitbase = unitbase - 1
# Generate transaction document
##############################
transaction_document = "Version: 10\n"
transaction_document += "Type: Transaction\n"
transaction_document += "Currency: " + currency_name + "\n"
transaction_document += "Blockstamp: " + blockstamp_current + "\n"
transaction_document += "Locktime: 0\n"
transaction_document += "Issuers:\n"
transaction_document += issuers + "\n"
transaction_document += "Inputs:\n"
for input in listinput:
transaction_document += input + "\n"
transaction_document += "Unlocks:\n"
for i in range(0, len(listinput)):
transaction_document += str(i) + ":SIG(0)\n"
transaction_document += "Outputs:\n"
for output in listoutput:
transaction_document += output + "\n"
transaction_document += "Comment: " + Comment + "\n"
return transaction_document
def get_list_input_for_transaction(ep, pubkey, TXamount, allinput=False):
# real source in blockchain
sources = get_request(ep, "tx/sources/" + pubkey)["sources"]
if sources is None:
return None
listinput = []
for source in sources:
if source["conditions"] == "SIG(" + pubkey + ")":
listinput.append(str(source["amount"]) + ":" + str(source["base"]) + ":" + str(source["type"]) + ":" + str(source["identifier"]) + ":" + str(source["noffset"]))
# pending source
history = get_request(ep, "tx/history/" + pubkey + "/pending")["history"]
pendings = history["sending"] + history["receiving"] + history["pending"]
current_blk = get_current_block(ep)
last_block_number = int(current_blk["number"])
# add pending output
for pending in pendings:
blockstamp = pending["blockstamp"]
block_number = int(blockstamp.split("-")[0])
# if it's not an old transaction (bug in mirror node)
if block_number >= last_block_number - 3:
identifier = pending["hash"]
i = 0
for output in pending["outputs"]:
outputsplited = output.split(":")
if outputsplited[2] == "SIG("+pubkey+")":
inputgenerated = str(outputsplited[0]) + ":" + str(outputsplited[1]) + ":T:" + identifier + ":" + str(i)
if inputgenerated not in listinput:
listinput.append(inputgenerated)
i += 1
# remove input already used
for pending in pendings:
blockstamp = pending["blockstamp"]
block_number = int(blockstamp.split("-")[0])
# if it's not an old transaction (bug in mirror node)
if block_number >= last_block_number - 3:
for input in pending["inputs"]:
if input in listinput:
listinput.remove(input)
# generate final list source
listinputfinal = []
totalAmountInput = 0
intermediatetransaction = False
for input in listinput:
listinputfinal.append(input)
inputsplit = input.split(":")
totalAmountInput += int(inputsplit[0]) * 10 ** int(inputsplit[1])
TXamount -= int(inputsplit[0]) * 10 ** int(inputsplit[1])
# if more 40 sources, it's an intermediate transaction
if len(listinputfinal) >= 40:
intermediatetransaction = True
break
if TXamount <= 0 and not allinput:
break
if TXamount > 0 and not intermediatetransaction:
message_exit("Error: you don't have enough money")
return listinputfinal, totalAmountInput, intermediatetransaction
def checkComment(Comment):
if len(Comment) > 255:
message_exit("Error: Comment is too long")
regex = compile('^[0-9a-zA-Z\ \-\_\:\/\;\*\[\]\(\)\?\!\^\+\=\@\&\~\#\{\}\|\\\<\>\%\.]*$')
if not search(regex, Comment):
message_exit("Error: the format of the comment is invalid")
def truncBase(amount, base):
pow = math.pow(10, base)
if amount < pow:
return 0
return math.trunc(amount / pow) * pow

112
silkaj/src/wot.py Normal file
View File

@ -0,0 +1,112 @@
from os import system
from tabulate import tabulate
from collections import OrderedDict
from network_tools import get_request
from tools import message_exit, check_public_key, convert_time
from constants import NO_MATCHING_ID
def get_sent_certifications(certs, time_first_block, params):
sent = list()
expire = list()
if certs["signed"]:
for cert in certs["signed"]:
sent.append(cert["uid"])
expire.append(expiration_date_from_block_id(cert["cert_time"]["block"], time_first_block, params))
return sent, expire
def received_sent_certifications(ep, id):
"""
check id exist
many identities could exist
retrieve the one searched
get id of received and sent certifications
display on a chart the result with the numbers
"""
params = get_request(ep, "blockchain/parameters")
time_first_block = get_request(ep, "blockchain/block/1")["time"]
if get_pubkeys_from_id(ep, id) == NO_MATCHING_ID:
message_exit(NO_MATCHING_ID)
certs_req = get_request(ep, "wot/lookup/" + id)["results"]
for certs_id in certs_req:
if certs_id['uids'][0]['uid'].lower() == id.lower():
id_certs = certs_id
break
certifications = OrderedDict()
system("clear")
for certs in id_certs["uids"]:
if certs["uid"].lower() == id.lower():
certifications["received_expire"] = list()
certifications["received"] = list()
for cert in certs["others"]:
certifications["received_expire"].append(expiration_date_from_block_id(cert["meta"]["block_number"], time_first_block, params))
certifications["received"].append(cert["uids"][0])
certifications["sent"], certifications["sent_expire"] = get_sent_certifications(id_certs, time_first_block, params)
print("{0} ({1}) from block #{2}\nreceived {3} and sent {4} certifications:\n{5}\n"
.format(id, id_certs["pubkey"][:5] + "", certs["meta"]["timestamp"][:15] + "",
len(certifications["received"]), len(certifications["sent"]),
tabulate(certifications, headers="keys", tablefmt="orgtbl", stralign="center")))
def expiration_date_from_block_id(block_id, time_first_block, params):
return convert_time(date_approximation(block_id, time_first_block, params["avgGenTime"]) + params["sigValidity"], "date")
def date_approximation(block_id, time_first_block, avgentime):
return time_first_block + block_id * avgentime
def id_pubkey_correspondence(ep, id_pubkey):
if check_public_key(id_pubkey, False):
# print("{} public key corresponds to identity: {}".format(id_pubkey, get_uid_from_pubkey(ep, id_pubkey)))
print("")
else:
pubkeys = get_pubkeys_from_id(ep, id_pubkey)
if pubkeys == NO_MATCHING_ID:
print(NO_MATCHING_ID)
else:
# G1SMS:: print("Public keys found matching '{}':\n".format(id_pubkey))
for pubkey in pubkeys:
print("", pubkey["pubkey"], end=" ")
try:
print("" + get_request(ep, "wot/identity-of/" + pubkey["pubkey"])["uid"])
except:
print("")
def get_uid_from_pubkey(ep, pubkey):
try:
results = get_request(ep, "wot/lookup/" + pubkey)
except:
return NO_MATCHING_ID
i, results = 0, results["results"]
while i < len(results):
if results[i]["uids"][0]["uid"] != pubkey:
return results[i]["uids"][0]["uid"]
i += 1
def get_pubkeys_from_id(ep, uid):
try:
results = get_request(ep, "wot/lookup/" + uid)
except:
return NO_MATCHING_ID
return results["results"]
def is_member(ep, pubkey, uid):
members = get_request(ep, "wot/members")["results"]
for member in members:
if (pubkey in member["pubkey"] and uid in member["uid"]):
return(True)
return(False)
def get_pubkey_from_id(ep, uid):
members = get_request(ep, "wot/members")["results"]
for member in members:
if (uid in member["uid"]):
return(member["pubkey"])
return(NO_MATCHING_ID)