G1 to ZEN into IPFS for SSB

This commit is contained in:
qo-op 2020-03-18 01:47:10 +01:00
parent 0c45f1062f
commit 5cfb84bdf9
16 changed files with 8848 additions and 48 deletions

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

7776
zen/diceware-wordlist.txt Normal file

File diff suppressed because it is too large Load Diff

17
zen/diceware.sh Executable file
View File

@ -0,0 +1,17 @@
#!/usr/bin/env bash
MOTS=$(echo "$1" | grep -E "^\-?[0-9]+$")
# Default to 6 words passphrase
if [[ "$MOTS" == "" ]]; then MOTS=6; 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

106
zen/duniter_getnode.sh Executable file
View File

@ -0,0 +1,106 @@
#!/bin/bash
################################################################################
# Authors: @jytou (https://git.duniter.org/jytou)
# Modified by Fred (support@qo-op.com)
# Version: 0.1
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
################################################################################
# Checks the current block number of /tmp/zen/duniter_nodes.txt (is run in parallel)
# and output random (from last synchronized) node
checkonenode()
{
# Timeout in seconds for https nodes
httpsTimeout=1
# Timeout in seconds for http nodes
httpTimeout=1
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/zen/gnodewatch
export DIR
mkdir -p $DIR/chains
### /tmp/zen/duniter_nodes.txt REFRESH
find /tmp/zen/ -cmin +20 -type f -name "duniter_*" -exec rm -f '{}' \;
if [[ ! -f /tmp/zen/duniter_nodes.txt ]]; then
[[ -f /tmp/zen/good.nodes.txt ]] && DUNITER=$(head -n1 /tmp/zen/good.nodes.txt) || DUNITER="g1.duniter.org:443"
# echo "___ REFRESH /tmp/zen/duniter_nodes.txt from $DUNITER ___"
curl -s https://$DUNITER/network/peers | jq '.peers[] | .endpoints' | grep BMAS | awk '{print $2,$3}' | sed s/\"//g | sed s/\,//g | sed s/\ /:/g > /tmp/zen/duniter_nodes.txt
fi
# Grab the nodes we are actively watching - they will be in bold in the final output
watched=`grep -v "#" /tmp/zen/duniter_nodes.txt|egrep "\!$"|awk '{print "#" $1 "#"}'`
# All nodes we are watching
nodes=`grep -v "#" /tmp/zen/duniter_nodes.txt|awk '{print $1}'`
# The index to generate separate file names
index=0
# Wipe out the output directory
rm $DIR/*out $DIR/*done $DIR/chains/* $DIR/NODE.* 2>/dev/null
# 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
# 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 most recent consensus to "good.nodes.txt"
nb=0
for chain in $chains
do
echo "$curs" | egrep "^$chain " | awk '{print $2}' >> $DIR/chains/$nb;
((nb++))
done
longchain=$(ls -S $DIR/chains/ | head -n 1)
cp $DIR/chains/$longchain /tmp/zen/good.nodes.txt
# WRITE OUT shuffle Duniter Node Sync with longest chain
echo $(shuf -n 1 /tmp/zen/good.nodes.txt)

36
zen/dunitey2secret.sh Executable file
View File

@ -0,0 +1,36 @@
#!/bin/bash
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 1.0
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
###########################################################################################
# This script convert secret.dunikey into ~/.ssb/secret.ssb
DUNKEYFILE="$1"
[[ ! ${DUNIKEYFILE} ]] && DUNKEYFILE="./secret.dunikey"
[[ ! ${DUNIKEYFILE} ]] && DUNKEYFILE="~/.ssb/secret.dunikey"
[[ ! -f ${DUNIKEYFILE} ]] && exit
pub=$(cat ${DUNIKEYFILE} | grep "pub" | cut -d ' ' -f 2)
priv=$(cat ${DUNIKEYFILE} | grep "sec" | cut -d ' ' -f 2)
ssbpub=$(echo $pub | base58 -d | base64)
ssbpriv=$(echo $priv | base58 -d | base64)
cat > ~/.ssb/secret.ssb <<EOF
# This secret generated by duniter2secret.sh
# G1 Wallet ACCOUNT BALANCE:
# silkaj balance $pub
#
# THIS KEY IS YOURS!
# NEVER show this to anyone!!!
{
"curve": "ed25519",
"public": "$ssbpub.ed25519",
"private": "$ssbpriv.ed25519",
"id": "@$ssbpub.ed25519"
}
# WARNING! It's vital that you DO NOT edit OR share your secret name
# instead, share your public name
# your public name: @$ssbpub.ed25519
EOF

31
zen/ipfs_PUBLISH.sh Executable file
View File

@ -0,0 +1,31 @@
#!/bin/bash
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 1.0
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
###########################################################################################
# ipfs_TASK.sh SYNC SWARM PEERS AND RUN TASKS
me=`basename "$0"`
IPFSNODEID=$(ipfs id -f='<id>\n')
########################################################################
### IPFS ADD ~/.zen/wallets
IWALLETS=$(ipfs add -rHq '~/.zen/wallets' | tail -n 1)
# CHAIN STATE FOR $IPFSNODEID
if [[ -f ~/.zen/wallets/.$IPFSNODEID.chain ]]; then
cat ~/.zen/wallets/.$IPFSNODEID.chain > ~/.zen/wallets/.$IPFSNODEID.chain.prev
INC=$(cat ~/.zen/wallets/.$IPFSNODEID.n)
((INC++))
echo $INC > ~/.zen/wallets/.$IPFSNODEID.n
else
echo "" > ~/.zen/wallets/.$IPFSNODEID.chain.prev
echo "0" > ~/.zen/wallets/.$IPFSNODEID.n
fi
### IPFS ADD ~/.zen/wallets
echo $IWALLETS > ~/.zen/wallets/.$IPFSNODEID.chain
IWALLETS=$(ipfs add -rHq '~/.zen/wallets' | tail -n 1)
# PUBLISH IPNS NODE WALLETS
NODEWALLETS=$(ipfs name publish --quieter /ipfs/$IWALLETS)
echo $IWALLETS

38
zen/ipfs_TASK.sh Executable file
View File

@ -0,0 +1,38 @@
#!/bin/bash
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 1.0
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
###########################################################################################
# ipfs_TASK.sh SYNC SWARM PEERS AND RUN TASKS
IPFSNODEID=$(ipfs id -f='<id>\n')
########################################################################
### SYNC IPFS SWARM PEERS
count=0
for id in $(ipfs swarm peers | awk -F '/' '{print $7}');
do
count=$((count+1))
id=$(echo $id | cut -d '.' -f 3 | cut -d '/' -f 1)
echo "REFRESH ~/.zen/wallets_swarm/.$id ..."
rm -Rf ~/.zen/wallets_swarm/.$id
./timeout.sh -t 10 ipfs get --output=~/.zen/wallets_swarm/ /ipns/$id > /dev/null 2>&1
done
echo "~/.zen/wallets_swarm/ RENEW from $count peers .........FINISH!!!"
########################################################################
# MAKE LOCAL ~/.zen/wallets/.$IPFSNODEID/TASK/ directory
[[ ! -d ~/.zen/wallets/.$IPFSNODEID/TASK/ ]] && mkdir -p ~/.zen/wallets/.$IPFSNODEID/TASK/
### SEARCH FOR RECEIVED TASK .todo FROM SWARM
for todo in $(ls ~/.zen/wallets_swarm/.$IPFSNODEID/TASK/*.todo 2>/dev/null);
do
TODO=$(cat $todo)
CMD=$(echo $TODO | cut -d ':' -f 1)
SUB=$(echo $TODO | cut -d ':' -f 2)
ACTION=$(echo $TODO | cut -d ':' -f 3)
done
# ./ipfs_PUBLISH.sh

28
zen/key_create_dunikey.py Executable file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env python3
# This Python script gets Duniter creddentials as arguments, and writes a PubSec file that should be compatible with Cesium and Silkaj(DuniterPy) clients.
# launch with :
# python3 key_create_dnuikey.py <id> <mdp>
# depends on duniterpy 0.56
### Licence - WTFPL
# This script was written my Matograine, in the hope that it will be helpful.
# Do What The Fuck you like with it. There is :
# * no guarantee that this will work
# * no support of any kind
#
# If this is helpful, please consider making a donation to the developper's pubkey : 78ZwwgpgdH5uLZLbThUQH7LKwPgjMunYfLiCfUCySkM8
# Have fun
from sys import argv
from duniterpy.key import SigningKey
# path to save to
path = "./.secret.dunikey"
key = SigningKey.from_credentials(argv[1], argv[2], None)
key.save_pubsec_file(path)
print(
"G1 Wallet: ",
key.pubkey,
)

112
zen/natools.py Executable file
View File

@ -0,0 +1,112 @@
#!/usr/bin/env python3
"""
CopyLeft 2020 Pascal Engélibert <tuxmain@zettascript.org>
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 <https://www.gnu.org/licenses/>.
"""
import os, sys, duniterpy.key, libnacl.sign
def getargv(arg:str, default:str="", n:int=1, args:list=sys.argv) -> str:
if arg in args and len(args) > args.index(arg)+n:
return args[args.index(arg)+n]
else:
return default
def read_data(data_path, b=True):
if data_path == "-":
if b:
return sys.stdin.read().encode()
else:
return sys.stdin.read()
else:
return open(os.path.expanduser(data_path), "rb" if b else "r").read()
def write_data(data, result_path):
if result_path == "-":
sys.stdout.write(data.decode())
else:
open(os.path.expanduser(result_path), "wb").write(data)
def encrypt(data, pubkey):
return duniterpy.key.PublicKey(pubkey).encrypt_seal(data)
def decrypt(data, privkey):
return privkey.decrypt_seal(data)
def sign(data, privkey):
return privkey.sign(data)
def verify(data, pubkey):
try:
sys.stderr.write("Signature OK!\n")
return libnacl.sign.Verifier(duniterpy.key.PublicKey(pubkey).hex_pk()).verify(data)
except ValueError:
sys.stderr.write("Bad signature!\n")
exit(1)
def get_privkey(privkey_path, pubsec):
if pubsec:
return duniterpy.key.SigningKey.from_pubsec_file(privkey_path)
else:
return duniterpy.key.SigningKey.from_seedhex(read_data(privkey_path, False))
def show_help():
print("""Usage:
python3 natools.py <command> [options]
Commands:
encrypt Encrypt data
decrypt Decrypt data
sign Sign data
verify Verify data
Options:
-i <path> Input file path (default: -)
-k <path> Privkey file path (default: authfile.key)
--pubsec Use pub/sec format for -p
-p <str> Pubkey (base58)
-o <path> Output file path (default: -)
Note: "-" means stdin or stdout.
""")
if __name__ == "__main__":
if "--help" in sys.argv:
show_help()
exit()
data_path = getargv("-i", "-")
privkey_path = getargv("-k", "authfile.key")
pubsec = "--pubsec" in sys.argv
pubkey = getargv("-p")
result_path = getargv("-o", "-")
try:
if sys.argv[1] == "encrypt":
write_data(encrypt(read_data(data_path), pubkey), result_path)
elif sys.argv[1] == "decrypt":
write_data(decrypt(read_data(data_path), get_privkey(privkey_path, pubsec)), result_path)
elif sys.argv[1] == "sign":
write_data(sign(read_data(data_path), get_privkey(privkey_path, pubsec)), result_path)
elif sys.argv[1] == "verify":
write_data(verify(read_data(data_path), pubkey), result_path)
else:
show_help()
except Exception as e:
sys.stderr.write("Error: {}\n".format(e))
show_help()
exit(1)

27
zen/secret2dunikey.sh Executable file
View File

@ -0,0 +1,27 @@
#!/bin/bash
########################################################################
# Author: Fred (support@qo-op.com)
# Version: 1.0
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
########################################################################
# This script creates ~/.ssb/secret.dunikey from your scuttlebutt secret
# You can use it https://cesium.app / https://silkaj.duniter.org/
# Python API https://pypi.org/project/duniterpy/
########################################################################
[[ ! -f ~/.ssb/secret ]] && echo "Your SSB secret is missing... EXIT" && exit 1
rm -f ~/.ssb/secret.dunikey
ssbpub=$(cat ~/.ssb/secret | grep public\" | cut -d ' ' -f 4 | cut -d '.' -f 1 | sed s/\"//g)
ssbpriv=$(cat ~/.ssb/secret | grep private\" | cut -d ' ' -f 4 | cut -d '.' -f 1 | sed s/\"//g)
g1pub=$(echo $ssbpub | base64 -d | base58)
g1priv=$(echo $ssbpriv | base64 -d | base58)
cat > ~/.ssb/secret.dunikey <<EOF
Type: PubSec
Version: 1
pub: $g1pub
sec: $g1priv
EOF
echo "Your G1 Wallet PubKey is :
$g1pub
Your KEY is located in ~/.ssb/secret.dunikey
Use it with https://cesium.app "

91
zen/timeout.sh Executable file
View File

@ -0,0 +1,91 @@
#!/bin/bash
#
# The Bash shell script executes a command with a time-out.
# Upon time-out expiration SIGTERM (15) is sent to the process. If the signal
# is blocked, then the subsequent SIGKILL (9) terminates it.
#
# Based on the Bash documentation example.
# Hello Chet,
# please find attached a "little easier" :-) to comprehend
# time-out example. If you find it suitable, feel free to include
# anywhere: the very same logic as in the original examples/scripts, a
# little more transparent implementation to my taste.
#
# Dmitry V Golovashkin <Dmitry.Golovashkin@sas.com>
scriptName="${0##*/}"
declare -i DEFAULT_TIMEOUT=20
declare -i DEFAULT_INTERVAL=1
declare -i DEFAULT_DELAY=1
# Timeout.
declare -i timeout=DEFAULT_TIMEOUT
# Interval between checks if the process is still alive.
declare -i interval=DEFAULT_INTERVAL
# Delay between posting the SIGTERM signal and destroying the process by SIGKILL.
declare -i delay=DEFAULT_DELAY
function printUsage() {
cat <<EOF
Synopsis
$scriptName [-t timeout] [-i interval] [-d delay] command
Execute a command with a time-out.
Upon time-out expiration SIGTERM (15) is sent to the process. If SIGTERM
signal is blocked, then the subsequent SIGKILL (9) terminates it.
-t timeout
Number of seconds to wait for command completion.
Default value: $DEFAULT_TIMEOUT seconds.
-i interval
Interval between checks if the process is still alive.
Positive integer, default value: $DEFAULT_INTERVAL seconds.
-d delay
Delay between posting the SIGTERM signal and destroying the
process by SIGKILL. Default value: $DEFAULT_DELAY seconds.
As of today, Bash does not support floating point arithmetic (sleep does),
therefore all delay/time values must be integers.
EOF
}
# Options.
while getopts ":t:i:d:" option; do
case "$option" in
t) timeout=$OPTARG ;;
i) interval=$OPTARG ;;
d) delay=$OPTARG ;;
*) printUsage; exit 1 ;;
esac
done
shift $((OPTIND - 1))
# $# should be at least 1 (the command to execute), however it may be strictly
# greater than 1 if the command itself has options.
if (($# == 0 || interval <= 0)); then
printUsage
exit 1
fi
# kill -0 pid Exit code indicates if a signal may be sent to $pid process.
(
((t = timeout))
while ((t > 0)); do
sleep $interval
kill -0 $$ || exit 0
((t -= interval))
done
# Be nice, post SIGTERM first.
# The 'exit 0' below will be executed if any preceeding command fails.
kill -s SIGTERM $$ && kill -0 $$ || exit 0
sleep $delay
kill -s SIGKILL $$
) 2> /dev/null &
exec "$@"

111
zen/cron_G1TXtoZenTag.sh → zen/zen_G1TXtoZenTag.sh Normal file → Executable file
View File

@ -5,8 +5,9 @@
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
########################################################################
# == Transform incoming G1 TX into IPFS ZenTAG ==
# SCAN G1PUBKEY WALLET FOR COMMAND in received/pending TX/IN COMMENT
# SCAN NODE G1 Wallet FOR "ZEN" Command received (or pending) TX/IN
########################################################################
#
########################################################################
# _(_)_ _(_)_
# @@@@ (_)@(_) @@@@ (_)@(_) @@@@
@ -16,12 +17,9 @@
# \ | \ |/ | / \ | \ |/ | / \ | \ |/
# \\|// \\|/// \\\|// \\|// \\|/// \\\|// \\|// \\|///
#^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# [ASTROPORT](https://astroport.com)
########################################################################
me=`basename "$0"`
# http://cb.vu/unixtoolbox.xhtml
# Create RAM disk
# mkdir -p ~/.zen/tmp && sudo mount -t tmpfs -osize=64m tmpfs ~/.zen/tmp
# Symetric Encrypt and decrypt
# openssl aes-256-cbc -k $mysecretpassword -salt -in file -out file.aes
@ -31,17 +29,17 @@ me=`basename "$0"`
# openssl aes-128-cbc -d -salt -in directory.tar.gz.aes | tar -xz -f - # Decrypt
if [[ ! $(which silkaj) ]]; then
echo "$USER Install SILKAJ !!" && exit 1
echo "$USER please Install SILKAJ !!" && exit 1
fi
DUNITERURL="https://duniter-g1.p2p.legal" # ATTENTION PAS DE / FINAL !!!
#DUNITERURL="https://duniter.g1.1000i100.fr" # METTRE EN LOAD BALANCING....
# GET DUNITER SERVER
DUNITERURL="https://$(./duniter_getnode.sh)"
IPFSNODEID=$(ipfs id -f='<id>\n')
[[ $IPFSNODEID == "" ]] && echo "$USER Install IPFS !!" && exit
[[ ! -d ~/.ssb/zen/scan ]] && mkdir -p ~/.ssb/zen/scan
[[ ! -d ~/.ssb/zen/wallets ]] && mkdir -p ~/.ssb/zen/wallets
[[ ! -d ~/.ssb/zen/wallets_swarm ]] && mkdir -p ~/.ssb/zen/wallets_swarm
[[ $IPFSNODEID == "" ]] && echo "$USER Please Install IPFS !!" && exit 1
[[ ! -d ~/.zen/scan ]] && mkdir -p ~/.zen/scan
[[ ! -d ~/.zen/wallets ]] && mkdir -p ~/.zen/wallets
[[ ! -d ~/.zen/wallets_swarm ]] && mkdir -p ~/.zen/wallets_swarm
#########################################################################################################
# GET G1 PUBKEY FROM SCUTTLEBUTT or $2 (DEBUG)
@ -56,84 +54,101 @@ if [[ $NODE_G1PUBKEY == "" ]]; then
ssbpriv=$(cat ~/.ssb/secret | grep private\" | cut -d ' ' -f 4 | cut -d '.' -f 1 | sed s/\"//g)
NODE_G1PUBKEY=$(echo $ssbpub | base64 -d | base58)
NODE_G1PRIVKEY=$(echo $ssbpriv | base64 -d | base58)
echo "pub: $NODE_G1PUBKEY" > ~/.ipfs/g1.pubsec.dunikey
echo "sec: $NODE_G1PRIVKEY" >> ~/.ipfs/g1.pubsec.dunikey
if [[ ! -f ~/.ssb/secret.dunikey ]]; then
echo "pub: $NODE_G1PUBKEY" > ~/.ssb/secret.dunikey
echo "sec: $NODE_G1PRIVKEY" >> ~/.ssb/secret.dunikey
fi
else
NODE_G1PUBKEY=$(cat ~/.ipfs/g1.pubsec.dunikey | grep 'pub:' | cut -d ' ' -f 2)
NODE_G1PRIVKEY=$(cat ~/.ipfs/g1.pubsec.dunikey | grep 'sec:' | cut -d ' ' -f 2)
NODE_G1PUBKEY=$(cat ~/.ssb/secret.dunikey | grep 'pub:' | cut -d ' ' -f 2)
NODE_G1PRIVKEY=$(cat ~/.ssb/secret.dunikey | grep 'sec:' | cut -d ' ' -f 2)
fi
fi
[[ "$NODE_G1PUBKEY" == "" ]] && echo "$USER Missing ~/.ipfs/g1.pubsec.dunikey : Install SSB Scuttlebot !" && exit;
[[ "$NODE_G1PUBKEY" == "" ]] && echo "$USER Missing ~/.ssb/secret : Please Install Scuttlebutt server !" && exit 1;
#########################################################################################################
echo "CHECKING G1WALLET LAST TX/IN ($DELAY)"
echo "======================================="
echo "IPFSNODEID = $IPFSNODEID"
echo "NODE_G1PUBKEY = $NODE_G1PUBKEY"
# TODO: REDUCE TIME WINDOW & SCAN history.pending
TIMEBEFORE=$(date --date="-$DELAY" +"%s")
TIMESTAMP=$(date +"%s")
echo "DUNITER URL = $DUNITERURL"
echo "G1 PUBKEY = $NODE_G1PUBKEY"
echo "SSB ID = %$ssbpub.ed25519"
echo "IPFS ID = $IPFSNODEID"
# SPECIAL ONE LINE BASH BONUS
# HOW MUCH = silkaj -p $(./duniter_getnode.sh) balance $(cat ~/.ssb/secret.dunikey | grep 'pub:' | cut -d ' ' -f 2)"
# GET BLOCKCHAIN TX DURING TIME WINDOW
curl -s $DUNITERURL/tx/history/$NODE_G1PUBKEY/times/$TIMEBEFORE/$TIMESTAMP > /tmp/g1zen.scan
# PREPARE TIMESTAMP LIMITS
TIMEBEFORE=$(date -u --date="-$DELAY" +"%s")
TIMESTAMP=$(date -u +"%s")
# GET BLOCKCHAIN TX FOR TIME WINDOW
curl -s $DUNITERURL/tx/history/$NODE_G1PUBKEY/times/$TIMEBEFORE/$TIMESTAMP > ~/.zen/g1zen.scan
## TODO VERIFY ~/.zen/g1zen.scan IS GOOD ?! AND RETRY... $DUNITERURL
#########################
# LONG DELAY = received
###########################################################################
# TX EXTRACTION
###########################################################################
# MORE THAN MINUTE DELAY = history.received
if [[ $DELAYUNIT != "minutes" && $DELAYUNIT != "minute" ]]; then
# HOW MANY TX DO WE HAVE...
TXnb=$(cat /tmp/g1zen.scan | jq '.history.received[].hash' | wc -l)
TXnb=$(cat ~/.zen/g1zen.scan | jq '.history.received[].hash' | wc -l)
echo "DETECTED $TXnb TX... Checking TX/IN..."
# PARSE $TXnb TX
line=1
while [[ $line -le $TXnb ]]; do
TXhash=$(cat /tmp/g1zen.scan | jq '.history.received[].hash' | head -n $line | tail -n 1 | sed s/\"//g)
# IT IS A NEW TX/IN?
if [[ ! -f ~/.ssb/zen/scan/zen.$TXhash ]]; then
# GET LAST RX ISSUER
ISSUER=$(cat /tmp/g1zen.scan | jq '.history.received[].issuers[0]' | head -n $line | tail -n 1 | sed s/\"//g)
# GET TX HASH
TXhash=$(cat ~/.zen/g1zen.scan | jq -r '.history.received[].hash' | head -n $line | tail -n 1 )
# IT IS A NEW TX?
if [[ ! -f ~/.zen/scan/zen.$TXhash ]]; then
# GET LAST TX ISSUER
ISSUER=$(cat ~/.zen/g1zen.scan | jq -r '.history.received[].issuers[0]' | head -n $line | tail -n 1)
[[ $ISSUER == $NODE_G1PUBKEY ]] && ((line++)) && continue ## TX/OUT CONTINUE
echo $ISSUER > ~/.ssb/zen/scan/zen.$TXhash
# GET OUTPUTS AND MAKE ZEN SUM
ZEN=$(cat /tmp/g1zen.scan | jq '.history.received[].outputs[]' | grep $NODE_G1PUBKEY | head -n $line | tail -n 1 | sed s/\"//g | cut -d ':' -f 1)
echo $ISSUER > ~/.zen/scan/zen.$TXhash
# GET OUTPUTS AND MAKE ZEN=G1*100 SUM
ZEN=$(cat ~/.zen/g1zen.scan | jq -r '.history.received[].outputs[]' | grep $NODE_G1PUBKEY | head -n $line | tail -n 1 | cut -d ':' -f 1)
# GET COMMENT
COMMENT=$(cat /tmp/g1zen.scan | jq '.history.received' | jq '.[].comment' | head -n $line | tail -n 1 | sed s/\"//g)
COMMENT=$(cat ~/.zen/g1zen.scan | jq '.history.received' | jq -r '.[].comment' | head -n $line | tail -n 1)
# echo "TX-IN $ISSUER => $NODE_G1PUBKEY"
echo "TX/IN :: $ZEN ZEN from $ISSUER :: $COMMENT ($TXhash)"
CMD=$(echo "$TEXT" | awk '{print toupper($1)}')
[[ $CMD == "ZEN" ]] && ./zen_MAKE.sh $ZEN $TXhash
./zen_MAKE.sh $ZEN $TXhash $ISSUER
###### CREATE ZEN VALUE IN IPFS #########
[[ $CMD == "ZEN" ]] && ./zen_MAKE.sh $ZEN $TXhash $ISSUER
############################################
echo "DEBUG! ./zen_MAKE.sh $ZEN $TXhash $ISSUER"
############################################
else
# STILL OLD TX
[[ $TXhash != "" ]] && echo "ALREADY TREATED TX/IN: $TXhash $(cat ~/.ssb/zen/scan/zen.$TXhash)" || echo "NO TX"
[[ $TXhash != "" ]] && echo "ALREADY TREATED TX/IN: $TXhash $(cat ~/.zen/scan/zen.$TXhash)" || echo "NO TX"
fi
((line++))
done
else
# MINUTE DELAY = pending
# MINUTE DELAY = pending // TODO: if anyone succeed in passing $VAR in jq command, both can be merge...
# HOW MANY TX DO WE HAVE...
TXnb=$(cat /tmp/g1zen.scan | jq '.history.pending[].hash' | wc -l)
TXnb=$(cat ~/.zen/g1zen.scan | jq '.history.pending[].hash' | wc -l)
echo "DETECTED $TXnb TX... Checking TX/IN..."
# PARSE $TXnb TX
line=1
while [[ $line -le $TXnb ]]; do
TXhash=$(cat /tmp/g1zen.scan | jq '.history.pending[].hash' | head -n $line | tail -n 1 | sed s/\"//g)
TXhash=$(cat ~/.zen/g1zen.scan | jq -r '.history.pending[].hash' | head -n $line | tail -n 1)
# IT IS A NEW TX/IN?
if [[ ! -f ~/.ssb/zen/scan/zen.$TXhash ]]; then
if [[ ! -f ~/.zen/scan/zen.$TXhash ]]; then
# GET LAST RX ISSUER
ISSUER=$(cat /tmp/g1zen.scan | jq '.history.pending[].issuers[0]' | head -n $line | tail -n 1 | sed s/\"//g)
ISSUER=$(cat ~/.zen/g1zen.scan | jq -r '.history.pending[].issuers[0]' | head -n $line | tail -n 1)
[[ $ISSUER == $NODE_G1PUBKEY ]] && ((line++)) && continue ## TX/OUT CONTINUE
echo $ISSUER > ~/.ssb/zen/scan/zen.$TXhash
echo $ISSUER > ~/.zen/scan/zen.$TXhash
# GET OUTPUTS AND MAKE ZEN SUM
ZEN=$(cat /tmp/g1zen.scan | jq '.history.pending[].outputs[]' | grep $NODE_G1PUBKEY | head -n $line | tail -n 1 | sed s/\"//g | cut -d ':' -f 1)
ZEN=$(cat ~/.zen/g1zen.scan | jq -r '.history.pending[].outputs[]' | grep $NODE_G1PUBKEY | head -n $line | tail -n 1 | cut -d ':' -f 1)
# GET COMMENT
COMMENT=$(cat /tmp/g1zen.scan | jq '.history.pending' | jq '.[].comment' | head -n $line | tail -n 1 | sed s/\"//g)
COMMENT=$(cat ~/.zen/g1zen.scan | jq '.history.pending' | jq -r '.[].comment' | head -n $line | tail -n 1)
# echo "TX-IN $ISSUER => $NODE_G1PUBKEY"
echo "TX/IN :: $ZEN ZEN from $ISSUER :: $COMMENT ($TXhash)"
CMD=$(echo "$TEXT" | awk '{print toupper($1)}')
###### CREATE ZEN VALUE IN IPFS #########
[[ $CMD == "ZEN" ]] && ./zen_MAKE.sh $ZEN $TXhash
############################################
echo "DEBUG! ./zen_MAKE.sh $ZEN $TXhash $ISSUER"
############################################
else
# STILL OLD TX
[[ $TXhash != "" ]] && echo "ALREADY TREATED TX/IN: $TXhash $(cat ~/.ssb/zen/scan/zen.$TXhash)" || echo "NO TX"
[[ $TXhash != "" ]] && echo "ALREADY TREATED TX/IN: $TXhash $(cat ~/.zen/scan/zen.$TXhash)" || echo "NO TX"
fi
((line++))
done

123
zen/zen_MAKE.sh Executable file
View File

@ -0,0 +1,123 @@
#!/bin/bash
# TODO CLEAN IPFS: ipfs pin ls -q --type recursive | xargs ipfs pin rm
###########################################################################################
# Script appelé depuis zen_G1TXIN pour créer des QRCode IPNS + Clef associé à un ZenTag
# rempli des centimes de June reçues.#
###########################################################################################
###########################################################################################
# ZenTag Draft Format
# fred@ONELOVE:~/workspace/ZEN$ ipfs ls /ipns/QmZxwgScLyLjitE1mrUFqpTw27gk6tMdfKQ7QTEo28dE2u
# QmVkur97Pqpgt7cy71FCNacPd5Z1eD9QVfw5tu4LdXHavk 47 _chain
# QmUQcSjQx2bg4cSe2rUZyQi6F8QtJFJb74fWL7D784UWf9 2 _chain.n
# QmRPdapkSVeYeRcC6X7freVo8vrGYjKcGsa96V5GsMg36p 20 _chain.nanodate
# Qmc5m94Gu7z62RC8waSKkZUrCCBJPyHbkpmGzEePxy2oXJ 1 _chain.prev
# Qmb8gYFmno4QeEpaPTi969qQNyVJK9VyfBbsXtyMA3PMow 45 _g1.creator
# QmQo6ghBGdkGCnGoB22cYmraR76q44K1mjVXqQQ3UVn2T1 45 _g1.issuer
# QmfUFk27ZvHaGfEwBeqResw2qQ9SCu4tsY69SkVuCdWAxB 65 _g1.txhash
# QmaKa7FGwmMshE7RACrWAFCsWETu1HcHnV1eak7HcUk6Cs 47 _ipfs.creator
# QmfCL14hnVnm3mrYT7fRjveMRTEoSp2axqCVp3JYoxXXgn 1300 _ipfs.publishkey.B.gpg
# QmUQ7WsACNYYWAw4QW8hKTCq8MM8oYGV7HJuxW7QTGj9qS 1243 _ipfs.publishkey.crypt
# QmdvRknZWSZUyS9SfmFWcvySv1tgi2PTF711rsGPN6ftL1 65 _tag.B.sha
# QmXA1zSxA3dh1dxFtkKaH5iomN3BsKMSAo2qhruA58AU81 34 _tag.uid
# QmPrumas2N5DuwcqUz9mayAU6oDL2bLjhpkVZ8hCRq9rpx 5 _tag.zen
###########################################################################################
###########################################################################################
me=`basename "$0"`
ZEN=$1
TXhash=$2
[[ ! -f ~/.zen/scan/zen.$TXhash ]] && echo "TX/IN NON RECONNUE... ARRET" && exit
ISSUER=$(cat ~/.zen/scan/zen.$TXhash)
#########################################################################################################
IPFSNODEID=$(ipfs id -f='<id>\n')
if [[ -f ~/.ipfs/g1.pubsec.dunikey ]]; then
NODE_G1PUBKEY=$(cat ~/.ipfs/g1.pubsec.dunikey | grep 'pub:' | cut -d ' ' -f 2)
else
echo "MISSING NODE_G1PUBKEY ~/.ipfs/g1.pubsec.dunikey ... Ciao"
exit
fi
#########################################################################################################
# CREATE ZEN TAG
# ZenTag NAMES
AA=$(./diceware.sh 6 | xargs); # Nom = Diceware de 6 mots
SHAA=$(echo -n $AA | sha256sum | cut -d ' ' -f 1)
RR=$(echo ${AA} | sed s/\ //g ); # Nom concaténé
PR=$(echo ${AA} | cut -d ' ' -f 1 ); # Prénom du G1Tag
# Create Unique G1tag in all SWARM! TODO BETTER
while [[ -f ~/.zen/tag/${SHAA} ]]; do
AA=$(./diceware.sh 6 | xargs);
SHAA=$(echo -n $AA | sha256sum | cut -d ' ' -f 1)
RR=$(echo ${AA} | sed s/\ //g );
PR=$(echo ${AA} | cut -d ' ' -f 1 );
done
# PASSWORD FOR HUMAN ACTION
BB=$(./diceware.sh 4 | xargs);
SHABB=$(echo -n "$BB" | sha256sum | cut -d ' ' -f 1)
####################
# WRITE ZENTAG
mkdir -p ~/.zen/tag/${SHAA}
echo "CREATING ZenTag ($ZEN zen): ls -al ~/.zen/tag/${SHAA}"
echo "$AA | $BB"
# ZenTag Create files
echo "$AA" > ~/.zen/tag/${SHAA}/_tag.uid # Nom du ZenTAG
echo "$ZEN" > ~/.zen/tag/${SHAA}/_tag.zen # Tag ZEN amount
echo "${IPFSNODEID}" > ~/.zen/tag/${SHAA}/_ipfs.creator # NODE IPFS ID
echo "$TXhash" > ~/.zen/tag/${SHAA}/_g1.txhash # HASH G1 TX/IN
echo "$NODE_G1PUBKEY" > ~/.zen/tag/${SHAA}/_g1.creator # CREATOR IPFS NODE G1PUBKEY
echo "$ISSUER" > ~/.zen/tag/${SHAA}/_g1.issuer # TX ISSUER G1PUBKEY
####################################################
# ${RR} IPNS publishkey CYPHER *BB & **NODE_G1PUBKEY
[[ ! -f ~/.ipfs/keystore/_${RR} ]] && J=$(ipfs key gen -t rsa -s 2048 _${RR})
# WRITE SHABB for QRCode BB verification
echo "$SHABB" > ~/.zen/tag/${SHAA}/_tag.B.sha
# BB pgp symetric publishkey
echo "${BB}" | gpg -q --output ~/.zen/tag/${SHAA}/_ipfs.publishkey.B.gpg --yes --pinentry-mode loopback --symmetric --passphrase-fd 0 ~/.ipfs/keystore/_${RR}
# GIVE IPFS CREATOR NODE ACCESS TO ZEN TAG
./natools.py encrypt -p $NODE_G1PUBKEY -i ~/.ipfs/keystore/_${RR} -o ~/.zen/tag/${SHAA}/_ipfs.publishkey.crypt
###########################################################
# TAG IPFS STORAGE & G1Tag IPNS PUBLISHING
###########################################################
# TAG CHAIN DATA
echo "0" > ~/.zen/tag/${SHAA}/_chain.n # Tag modification number (0 first)
NANODATE=$(date -u +%s%N)
echo "$NANODATE" > ~/.zen/tag/${SHAA}/_chain.nanodate # Nanodate notification
echo "" > ~/.zen/tag/${SHAA}/_chain.prev
I=$(ipfs add -qr ~/.zen/tag/${SHAA} | tail -n 1)
# MEMORIZE FOR CHAINING FUTURE CHANGES
echo "${I}" > ~/.zen/tag/${SHAA}/_chain
# Activate chain
I=$(ipfs add -qr ~/.zen/tag/${SHAA} | tail -n 1)
# IPFS Hash for Immutable G1tag data
J=$(ipfs name publish -k _${RR} --quieter /ipfs/${I})
echo "${J}" > ~/.zen/tag/${SHAA}/_ipns
echo "ZENTAG MADE: ipfs ls /ipns/${J}"
ipfs ls /ipns/${J}
####################################################################################
### G1TAG PRINT
# QR CODE LECTURE
qrencode -s 5 -o ~/.zen/tag/${SHAA}/.QRCODE.pub.png "RJ:${SHAA}#${J}"
# QR CODE ECRITURE + ISSUER CYPHER (TODO : SHABB ou BB?)
qrencode -s 5 -o ~/.zen/tag/${SHAA}/.QRCODE.priv.png "BJ:${SHABB}#${J}"
##############################################################################
# TODO: PRINT LOCAL OR SEND "PRINT TASK" TO DAB MACHINE $ISSUER PREFERING ...
# DESTNODE=$(grep -Rwl "$ISSUER" ~/.zen/wallets_swarm/*/_pub)
# [[ $DESTNODE != "" ]] && DESNODEIPFSFILE=$(echo $DESTNODE | cut -d '_' -f 1)_ipfsid || exit
# DESTIPFS=$(cat $DESNODEIPFSFILE)
# ./natools.py encrypt -p $DESTIPFS -i ~/.zen/tag/${SHAA}/.QRCODE.priv.png -o ~/.zen/tag/${SHAA}/.QRCODE.crypt.png && rm ~/.zen/tag/${SHAA}/.QRCODE.priv.png
# CREATE TASK
# mkdir -p ~/.zen/wallets/.$DESTIPFS/TASK/
# echo "PRINT:ZENTAG:${J}" > ~/.zen/wallets/.$DESTIPFS/TASK/$NANODATE.$IPFSNODEID.todo
# ./ipfs_PUBLISH.sh
###

98
zen/zen_OP.sh Executable file
View File

@ -0,0 +1,98 @@
#!/bin/bash
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 1.0
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
###########################################################################################
# tag_OP.sh OPERATION ON ZenTAG...
###########################################################################################
# fred@ONELOVE:~/workspace/ZEN$ ipfs ls /ipns/QmZxwgScLyLjitE1mrUFqpTw27gk6tMdfKQ7QTEo28dE2u
# QmVkur97Pqpgt7cy71FCNacPd5Z1eD9QVfw5tu4LdXHavk 47 _chain
# QmUQcSjQx2bg4cSe2rUZyQi6F8QtJFJb74fWL7D784UWf9 2 _chain.n
# QmRPdapkSVeYeRcC6X7freVo8vrGYjKcGsa96V5GsMg36p 20 _chain.nanodate
# Qmc5m94Gu7z62RC8waSKkZUrCCBJPyHbkpmGzEePxy2oXJ 1 _chain.prev
# Qmb8gYFmno4QeEpaPTi969qQNyVJK9VyfBbsXtyMA3PMow 45 _g1.creator
# QmQo6ghBGdkGCnGoB22cYmraR76q44K1mjVXqQQ3UVn2T1 45 _g1.issuer
# QmfUFk27ZvHaGfEwBeqResw2qQ9SCu4tsY69SkVuCdWAxB 65 _g1.txhash
# QmaKa7FGwmMshE7RACrWAFCsWETu1HcHnV1eak7HcUk6Cs 47 _ipfs.creator
# QmfCL14hnVnm3mrYT7fRjveMRTEoSp2axqCVp3JYoxXXgn 1300 _ipfs.publishkey.B.gpg
# QmUQ7WsACNYYWAw4QW8hKTCq8MM8oYGV7HJuxW7QTGj9qS 1243 _ipfs.publishkey.crypt
# QmdvRknZWSZUyS9SfmFWcvySv1tgi2PTF711rsGPN6ftL1 65 _tag.B.sha
# QmXA1zSxA3dh1dxFtkKaH5iomN3BsKMSAo2qhruA58AU81 34 _tag.uid
# QmPrumas2N5DuwcqUz9mayAU6oDL2bLjhpkVZ8hCRq9rpx 5 _tag.zen
############################################################################################
# TRANSFERT $VALUE ZEN FROM $JSOURCE ZenTag to $JDEST ZenTag
JSOURCE=$1
JDEST=$2
VALUE=$3
IPFSNODEID=$(ipfs id -f='<id>\n')
NANODATE=$(date -u +%s%N)
############################################
echo "############################################
zen_OP.sh ZenTag TRANSFER $NANODATE
############################################
SOURCE(1): $JSOURCE
DEST(2): $JDEST
VALUE(3): $VALUE ZEN
############################################"
#############################################################################################################
# SOURCE
#############################################################################################################
############## SOURCE EXTRACTION
JSOURCEUID=$(ipfs cat /ipns/$JSOURCE/_tag.uid)
JSOURCERR=$(echo "$JSOURCEUID" | sed s/\ //g)
#############################################
############## GOOD or BAD ?
[[ $JSOURCERR == "" ]] && echo "NO G1Tag /ipns/$JSOURCE ... Ciao!" && exit
[[ ! -d /tmp/$JSOURCERR ]] && mkdir -p /tmp/$JSOURCERR || rm -f /tmp/$JSOURCERR/*
ipfs get --output=/tmp/${JSOURCERR}/ /ipns/$JSOURCE > /dev/null 2>&1
# echo "Retrieving SOURCE G1Tag: ipfs get --output=/tmp/${JSOURCERR}/ /ipns/$JSOURCE"
JSOURCECREATOR=$(cat /tmp/${JSOURCERR}/_ipfs.creator)
JSOURCEVALUE=$(cat /tmp/${JSOURCERR}/_tag.zen)
#############################################
############## No JDEST, then return $JSOURCEVALUE
[[ "$JDEST" == "" ]] && echo "ZenTAG ($JSOURCEUID) VALUE = $JSOURCEVALUE Zen" && exit
#############################################
#############################################
############## TEST IF $VALUE IS AVAILABLE
FINALSOURCE=$(echo "${JSOURCEVALUE} - ${VALUE}" | bc -l)
[[ $FINALSOURCE -lt 0 ]] && echo "Manque $FINALSOURCE Zen à ce ZenTAG... Ciao!" && exit
#############################################################################################################
# DEST
#############################################################################################################
############## DESTINATION EXTRACTION
JDESTUID=$(ipfs cat /ipns/$JDEST/_tag.uid)
JDESTRR=$(echo "$JDESTUID" | sed s/\ //g);
#############################################
############## GOOD or BAD ?
[[ $JDESTRR == "" ]] && echo "NO G1Tag /ipns/$JDEST ... Ciao!" && exit
[[ ! -d /tmp/$JDESTRR ]] && mkdir -p /tmp/$JDESTRR || rm -f /tmp/$JDESTRR/*
ipfs get --output=/tmp/$JDESTRR/ /ipns/$JDEST > /dev/null 2>&1
JDESTCREATOR=$(cat /tmp/${JDESTRR}/_ipfs.creator)
JDESTVALUE=$(cat /tmp/${JDESTRR}/_tag.zen);
FINALDEST=$(echo "${JDESTVALUE} + ${VALUE}" | bc -l)
######################################################################################################
# CHECK NANODATE
LAST=$(cat /tmp/${JSOURCERR}/_chain.nanodate)
timediff=$( echo "${NANODATE} - ${LAST}" | bc -l )
# NODE TIME SYNC 600 milliards de nanosecondes = 600 s = 10 mn
if [[ $timediff -lt 600000000000 ]]; then
echo "LAST OPERATION NOT FINISHED YET... RETRY IN A FEW MINUTES"
exit
fi
echo "OK. OPERATION ALLOWED...
$JSOURCERR (/ipns/$JSOURCE) : $JSOURCEVALUE => $FINALSOURCE
$JDESTRR (/ipns/$JDEST) : $JDESTVALUE => $FINALDEST"
# TODO: SEND TASK TO $JSOURCECREATOR AND $JDESTCREATOR

302
zen/zen_READ.sh Executable file
View File

@ -0,0 +1,302 @@
#!/bin/bash
################################################################################
# Author: Fred (support@qo-op.com)
# Version: 0.1
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
###########################################################################################
###########################################################################################
# Lit les données reçues depuis un lecteur de QR Code branché en USB/SERIE (/dev/ttyACM0)
# Interpète les G1QRcodes et les G1Tag (R/W)
# Saisie du montant à transférer par pavé numérique
###########################################################################################
echo "__SUB:tag_READ_XY.sh: QRCODE READER : START"
function log () {
echo "$line
$1" >> /tmp/tag_READ_XY.log
}
#############################################
# No external dependance !!!!
#source ./shell/init.sh
#source ./shell/functions.sh
##############################################
# NODE ENVIRONEMENT DETECTION
##############################################
YOU=$(ps auxf --sort=+utime | grep -w ipfs | grep -v -E 'color=auto|grep' | tail -n 1 | cut -d " " -f 1);
IPFSNODEID=$(su $YOU -c "ipfs id -f='<id>\n'")
NODE_UIDNA=$(cat "./wallets/.$IPFSNODEID/_uidna")
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
SWARM_G1PUBKEY=$(cat "${GPATH}/g1sms.pub.key")
SWARM_G1AUTHFILE="${GPATH}/g1sms.priv.key"
if [[ ! -f $SWARM_G1AUTHFILE ]]; then echo "ERREUR CLEF DECHIFFRAGE!"; exit; fi
## INIT NODE G1 PUB & PRIV KEY
NODE_G1PUBKEY=$(cat "${GPATH}/g1sms.preoni.pub.key")
NODE_G1AUTHFILE="${GPATH}/g1sms.preoni.priv.key"
if [[ ! -e "/dev/ttyACM0" ]]; then echo "Branchez votre lecteur de QR code!"; exit; fi
##############################################
# DOUCHETTE ES TU LA?
./shell/tools/4LETTER.scroll.py "G1TX START"
./shell/tools/4LETTER.clock.py &
clockpid=$!
# TABLEAU MEMOIRE DE SCAN
declare -a act
declare -a obj
declare -a val
cat /dev/ttyACM0 | while read line; do
kill $clockpid
lon=${#line}
pref=$(echo $line | cut -d ":" -f 1)
qrvalue=$(echo $line | cut -d ":" -f 2)
log "__SUB:tag_READ_X.sh: SCAN /dev/ttyACM0 ($lon) :: $line"
case $pref in
RJ)
R=$(echo $qrvalue | cut -d '#' -f 1)
J=$(echo $qrvalue | cut -d '#' -f 2)
log "__SUB:tag_READ_X.sh: Lecture G1Tag $R $J"
# IPFS READ
ID=$(su $YOU -c "ipfs cat /ipns/$J/TAG_id");
if [[ "$ID" == "" ]]; then
./shell/tools/4LETTER.scroll.py ">> BAD G1TAG <<"
continue
fi
# Get First R Tag name word and remove space for RR
FID=$(echo $ID | awk '{print toupper($1)}')
RR=$(echo $ID | sed s/\ //g)
./shell/tools/4LETTER.scroll.py "${#act[@]} $FID > "
RVALUE=$(su $YOU -c "ipfs cat /ipns/$J/TAG_amount");
CURRENCY=$(su $YOU -c "ipfs cat /ipns/$J/TAG_currency" | awk '{print tolower($1)}')
PASSENGER=$(su $YOU -c "ipfs cat /ipns/$J/TAG_passenger");
if [[ "$PASSENGER" != "" ]]; then
./shell/tools/4LETTER.scroll.py "G1TAG PASSENGER $RVALUE ZEN"
else
G1VAL=$(bc -l <<< "scale=2; $RVALUE / 100" | cut -d '.' -f 1)
log "__SUB:tag_READ_X.sh: G1Tag $FID. Valeur $RVALUE $CURRENCY = $G1VAL G1"
./shell/tools/4LETTER.scroll.py "$RVALUE ZEN *** $G1VAL G1"
fi
cmd="RJ"
CASHBACK=""
val+=("$RVALUE")
;;
BJ)
BB=$(echo $qrvalue | cut -d '#' -f 1)
J=$(echo $qrvalue | cut -d '#' -f 2)
log "__SUB:tag_READ_X.sh: Ouverture G1Tag $BB $J"
#
ID=$(su $YOU -c "ipfs cat /ipns/$J/TAG_id");
if [[ "$ID" == "" ]]; then
./shell/tools/4LETTER.scroll.py ">> BAD G1TAG <<"
continue
fi
FID=$(echo $ID | awk '{print toupper($1)}')
RR=$(echo $ID | sed s/\ //g)
./shell/tools/4LETTER.scroll.py "${#act[@]} $FID TX >>"
BVALUE=$(su $YOU -c "ipfs cat /ipns/$J/TAG_amount")
CURRENCY=$(su $YOU -c "ipfs cat /ipns/$J/TAG_currency" | awk '{print tolower($1)}')
PASSENGER=$(su $YOU -c "ipfs cat /ipns/$J/TAG_passenger");
# DIG PUBLISHING KEY
if [[ -f /home/$YOU/.ipfs/keystore/$RR ]]; then
log "__SUB:tag_READ_X.sh: Clef de publication IPFS $RR déjà présente"
else
rm /tmp/TAG_publishkey.B.gpg
su $YOU -c "ipfs get -o /tmp/ /ipns/$J/TAG_publishkey.B.gpg"
./shell/tools/4LETTER.scroll.py "** GPG **"
gpg -d --output /tmp/ipns.key --pinentry-mode=loopback --passphrase $BB /tmp/TAG_publishkey.B.gpg
# CHECK IF OK
if [[ ! -f /tmp/ipns.key ]]; then
./shell/tools/4LETTER.scroll.py ">> BAD GPG KEY <<"
continue
fi
mv /tmp/ipns.key /home/$YOU/.ipfs/keystore/$RR
log "__SUB:tag_READ_X.sh: Récupération de la clef de publication $RR"
fi
if [[ "$PASSENGER" != "" ]]; then
log "__SUB:tag_READ_X.sh: !!!! $FID REC Tag = $BVALUE $CURRENCY"
./shell/tools/4LETTER.scroll.py "G1TAG PASSENGER $BVALUE ZEN"
else
G1VAL=$(bc -l <<< "scale=2; $BVALUE / 100" | cut -d '.' -f 1)
log "__SUB:tag_READ_X.sh: Ce G1 Tag $FID contient $BVALUE $CURRENCY"
./shell/tools/4LETTER.scroll.py "$BVALUE ZEN *** $G1VAL G1 MAX"
fi
cmd="BJ"
val+=("$BVALUE")
;;
*)
if [[ $lon -eq 44 ]]; then
./shell/tools/4LETTER.scroll.py "PORTEFEUILLE G1 >>>>>>>> ${#act[@]}" &
J=$qrvalue
if [[ "$J" != "${obj[0]}" ]]; then
VALUE=$(./shell/timeout.sh -t 25 ./silkaj/silkaj amount $J)
if [[ "$(echo $VALUE | cut -d ':' -f 1)" != "Error" && "$VALUE" != "" ]]; then
log "__SUB:tag_READ_X.sh: Ce compte monnaie libre contient $VALUE G1"
NOPOINT=$(echo $VALUE | cut -d '.' -f 1)
./shell/tools/4LETTER.scroll.py " $NOPOINT G1 *** $NOPOINT G1 "
CASHBACK="$J"
cmd="G1"
val+=("$VALUE")
else
if [[ "$VALUE" == "" ]]; then
DUNITER=$(./shell/checknodes.sh 'BAN')
log "__SUB:tag_READ_X.sh: ERREUR TIMEOUT. CHANGE SILKAJ SERVER: $DUNITER"
./shell/tools/4LETTER.scroll.py "ERREUR TIMEOUT SILKAJ"
./shell/timeout.sh -t 1 ./shell/tools/4LETTER.spinner.py
CASHBACK=""
else
log "__SUB:tag_READ_X.sh: ERREUR QRCODE ILLISIBLE. longueur $J = ${#J}"
./shell/tools/4LETTER.scroll.py "ERREUR QRCODE INCONNU"
./shell/timeout.sh -t 1 ./shell/tools/4LETTER.spinner.py
CASHBACK=""
fi
fi
else
./shell/tools/4LETTER.scroll.py " 2 X "
fi
else
./shell/tools/4LETTER.scroll.py "ERREUR QRCODE INCONNU"
fi
;;
esac
###############################################################
# APRES G1 CASHBACK : G1 Tag BJ WRITE => ENCAISSEMENT
if [[ "${cmd}" == "BJ" && "$CASHBACK" != "" && -f /home/$YOU/.ipfs/keystore/${RR} ]]; then
./shell/tools/4LETTER.scroll.py "ZEN -> G1"
log "__SUB:tag_READ_X.sh: G1 tag de $BVALUE G1 ! /ipns/$J Virement vers $CASHBACK? "
./shell/tools/4LETTER.spinner.py &
spinnerpid=$!
# ipfs get G1Tag vers ./TAG/${RR}
mkdir -p ./TAG/${RR}; rm -f ./TAG/${RR}/*; chown -R $YOU ./TAG/${RR}/
log "__SUB:tag_READ_X.sh: ipfs get --output=./TAG/${RR} /ipns/$J"
su $YOU -c "ipfs get --output=./TAG/${RR} /ipns/$J"
if [[ $(cat ./TAG/${RR}/TAG_passenger) != "" ]]; then ./shell/tools/4LETTER.scroll.py "IMPOSSIBLE TAG PASSENGER $BVALUE ZEN"; continue; fi
# Make Silkaj TX
G1VAL=$(bc -l <<< "scale=2; $BVALUE / 100" | cut -d '.' -f 1)
log "__SUB:tag_READ_X.sh: Silkaj TX $SWARM_G1AUTHFILE ($G1VAL) -> $CASHBACK"
PAY=$(./silkaj/silkaj transaction --auth-file -file="$SWARM_G1AUTHFILE" --amount=$G1VAL --output=$CASHBACK --comment="[G1sms+] G1Tag $RR ZEN -> G1" -y)
log "__SUB:tag_READ_X.sh: Silkaj output = $PAY"
# Stop 1LETTER.spinner.py
kill $spinnerpid
if [[ "$(echo $PAY | cut -d '|' -f 1)" == "KO" && "$PAY" != "" ]]; then
new=$(./shell/checknodes.sh "BAN")
sms_ERROR "$ADMINPHONE" "Il est survenu un problème avec un virement. Retour silkaj: $PAY ... $new";
./shell/tools/4LETTER.scroll.py "ERREUR SILKAJ ERREUR"
else
# ENCAISSEMENT G1Tag
./shell/tools/4LETTER.scroll.py "VIR ${FID} $G1VAL G1 -> OK "
# CAPTURE / DESTRUCTION du G1 Tag
echo "0" > "./TAG/${RR}/TAG_amount"
echo "${J}" > "./TAG/${RR}/TAG_ipns"
# Iterate
if [[ -f ./TAG/${RR}/TAG_n ]]; then NN=$(cat ./TAG/${RR}/TAG_n); ((NN++)); else NN=0; fi
# TAG_actions
echo "$NN" > "./TAG/${RR}/TAG_n"
echo "${NANODATE}" > "./TAG/${RR}/TAG_nanodate"
echo "${IPFSNODEID}" > "./TAG/${RR}/TAG_writerid"
# EMPTY G1TAG ID AND REMOVE PUBLISHKEYS
echo "" > "./TAG/${RR}/TAG_id"
rm -f ./TAG/TAG_publishkey.*
log "__SUB:tag_READ_X.sh: Destruction G1Tag TAG_id $NN.${NANODATE} (par NODE ${IPFSNODEID}) => Value = 0"
I=$(su $YOU -c "ipfs add -qr ./TAG/${RR} | tail -n 1")
# TAG_chain
echo "$I" > "./TAG/${RR}/TAG_chain"
I=$(su $YOU -c "ipfs add -qr ./TAG/${RR} | tail -n 1")
# IPNS $RR PUBLISH
J=$(su $YOU -c "ipfs name publish -k ${RR} --quieter /ipfs/${I}")
log "__SUB:tag_READ_X.sh: Destruction de ce G1 Tag publish -k ${RR} --quieter /ipfs/${I} :: ipfs ls /ipns/$J"
./shell/tools/4LETTER.scroll.py "DETRUIRE G1TAG ${FID}"
# CLEAN IPFS keystore: remove NOT created NODE keys
SOURCENODEID=$(cat "./TAG/${RR}/TAG_nodeid")
if [[ "${SOURCENODEID}" != "${IPFSNODEID}" ]]; then
rm -f /home/$YOU/.ipfs/keystore/${RR}
fi
fi
else
# AJOUT MEMOIRE SCAN
./shell/timeout.sh -t 1 ./shell/tools/4LETTER.spinner.py
act+=("$cmd")
obj+=("$J")
fi
# FLUSH MEMOIRE 2 SCAN
if [[ ${#act[@]} -eq 2 ]]; then
echo "${act[@]}"
echo "${obj[@]}"
echo "${val[@]}"
###############################################################
# PRESENTATION RJ puis BJ différents Tag WRITE = TRANSFERT G1 TAG
if [[ "${act[0]}" == "RJ" && "${act[1]}" == "BJ" && "${obj[0]}" != "${obj[1]}" ]]; then
PASSENGER=$(su $YOU -c "ipfs cat /ipns/${obj[1]}/TAG_passenger");
if [[ "$PASSENGER" != "" ]]; then
./shell/tools/4LETTER.scroll.py "IMPOSSIBLE TAG PASSENGER";
else
###########################################################
# READ KEYBOARD VALUE !!! 4 DIGIT REMOVING LEADING 0
COMBIEN=$(./shell/tools/matrixKeypad.py | sed 's/^0*//')
if [[ $COMBIEN -le ${val[1]} ]]; then
COMBIENZEN=$(bc -l <<< "$COMBIEN * 100")
log "__SUB:tag_READ_X.sh: Transfert de G1 Tag à G1 Tag. $COMBIEN"
./shell/tools/4LETTER.scroll.py "G1TAG ${FID} -> TX $COMBIENZEN ZEN *** $COMBIEN G1"
log "__SUB:tag_READ_X.sh: ./shell/tag_OP.sh ${obj[1]} ${obj[0]} $COMBIENZEN $SWARM_G1AUTHFILE"
./shell/tag_OP.sh ${obj[1]} ${obj[0]} $COMBIENZEN "$SWARM_G1AUTHFILE"
else
./shell/tools/4LETTER.scroll.py "ERREUR $COMBIEN > VALEUR DE ${FID} *** ${val[1]} ZEN"
fi
fi
CASHBACK=""
fi
###############################################################
# PRESENTATION BJ identiques TRANSFORMATION G1 TAG en REC TAG
if [[ "${act[0]}" == "BJ" && "${act[1]}" == "BJ" && "${obj[0]}" == "${obj[1]}" ]]; then
PASSENGER=$(su $YOU -c "ipfs cat /ipns/${obj[0]}/TAG_passenger");
if [[ "$PASSENGER" != "" ]]; then
./shell/tools/4LETTER.scroll.py "DEJA TAG PASSENGER";
else
log "__SUB:tag_READ_X.sh: Transformation du G1 Tag en Rec Tag. ${val[0]} = ${val[1]}"
./shell/tools/4LETTER.scroll.py "TRASNFORMATION G1TAG ${val[0]} ZEN EN PASSENGER ${FID}";
log "__SUB:tag_READ_X.sh: $(./shell/tag_OP.sh ${obj[0]} ${obj[0]} 0 $SWARM_G1AUTHFILE)"
fi
CASHBACK=""
fi
act=()
obj=()
val=()
# END OF 2-PASS READ
./shell/timeout.sh -t 2 ./shell/tools/4LETTER.spinner.py
fi
./shell/tools/4LETTER.blink.py
./shell/tools/4LETTER.clock.py &
clockpid=$!
done