G1sms/shell/functions.sh

673 lines
30 KiB
Bash
Executable File

#!/bin/bash
# License: AGPL-3.0 (https://choosealicense.com/licenses/agpl-3.0/)
# G1SMS COMMUN FUNCTIONS
# TODO: REWRITE AND MAKE FULL IPFS get wallet value through IPNS links
# ipfs cat /ipns/QmUrUdfz5hWJ6354D3N6DT64tbs5CLEndSYYiqrj9Wa4Ax/+33647683646/+33647683646.uidna
###################################################################################################################################
###################################################################################################################################
MY_PATH="`dirname \"$0\"`" # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`" # absolutized and normalized
## Récupère les données du profile
[[ -f $MY_PATH/.profile ]] && source $MY_PATH/.profile
function sms_SEND () {
# sms_SEND ($1=phone, $2=message)
local dest="$1"
local dhash=$(echo -n $dest | sha256sum | cut -d ' ' -f 1)
local mess="$2"
# IF $dest looks like a phone number
if [[ ${#dest} -eq 10 || ${#dest} -eq 12 ]]; then
# Search it in wallets_swarm
if [[ -d ./wallets_swarm/PHONE/$dhash ]]; then
DESTNODEID=$(cat ./wallets_swarm/PHONE/$dhash/MASTERPHONE.ipfsid)
# Other Node is managing wallet, write SMS task to it
if [[ "$DESTNODEID" != "" && "$DESTNODEID" != "$IPFSNODEID" ]]; then
log "$dest is managed by NODE: $DESTNODEID)"
mkdir -p "./wallets/.$DESTNODEID/SMS"
echo $mess > "./wallets/.$DESTNODEID/SMS/$dest.sms2send"
# Push changes to IPFS
I=$(ipfs_node_wallets_add)
else
# Send SMS from here
gammu-smsd-inject TEXT "$dest" -text "$mess" 1>&2
fi
else
# Send SMS from here
gammu-smsd-inject TEXT "$dest" -text "$mess" 1>&2
fi
else
log "${c_red}>>>>>>>>>>SMS ERROR BAD DESTINATION $dest$c_"
fi
log "${c_green}>>>>>>>>>> SENDING SMS$c_ \n$mess TO $dest via $DESTNODEID"
}
#################################################################################################################################
function sms_ERROR () {
# sms_ERROR ($1=phone, $2=message)
local dest="$1"
local mess="[ERREUR]
$2"
if [[ ${#dest} -eq 10 || ${#dest} -eq 12 ]]; then
gammu-smsd-inject TEXT "$dest" -text "$mess" 1>&2
else
log "${c_red}>>>>>>>>>>SMS ERROR BAD DESTINATION$c_ $dest"
fi
log "${c_red}>>>>>>>>>> SENDING SMS$c_ \n$mess TO $dest"
# SEND ERROR COPY TO ADMINPHONE
if [[ "$CPERROR" == "YES" ]]; then sms_SEND "$ADMINPHONE" "ADMIN! ERROR ($dest): $mess"; fi
}
#################################################################################################################################
function log_history () {
log "__SUB:log_history: history ($1, $2)"
PHONE="$1"
HISTFILE="./history.$IPFSNODEID.log.csv"
echo "$(date +%Y%m%d), $(date +%H:%M:%S), $1, $2" >> "$HISTFILE"
}
#################################################################################################################################
function security () {
if [[ "$G1SMS" == "YES" ]]; then # ONLY OF gammu is really sending SMS on that NODE
# No Reply to MySelf (or enjoy SMS LOOP of the death) Nobody neither
if [[ "$PHONE" == "$MASTERPHONE" || "$PHONE" == "" ]]; then log "${c_red}__SUB:security: SMS REJECTED !!$c_ $PHONE $TEXT"; exit; fi
# ADAPT TO YOUR PHONE COMPANY / ADVERT ANNOYANCE
if [[ "$PHONE" == "Orange Info" ]]; then log "${c_red}__SUB:security: SMS REJECTED !! $PHONE ADVERT$c_ $TEXT"; exit; fi
if [[ ${#PHONE} -ne 12 && ${#PHONE} -ne 46 ]]; then log "${c_red}!! SMS REJECTED !! $PHONE BAD$c_ $TEXT"; exit; fi
fi
# ANTI SPAM SMS (1 mn entre chaque commande)
find /tmp -cmin +1 -type f -name "sms_received_*" -exec rm -f '{}' \;
# Do not consider SPAM, Delivered notification
if [[ "$CMD" != "DELIVERED" && "$CMD" != "PENDING" ]]; then
if [[ -f "/tmp/sms_received_$PHONE" ]]; then
# Send response SMS
if [[ ! -f "/tmp/sms_SPAM_$PHONE" ]]; then
sms_ERROR "$PHONE" "Je ne le dirai pas 2 fois... Laissez moi au moins 1 minute entre chacune de vos commandes SMS! Autrement je n'y répondrai pas. Merci!"
echo $(date) > "/tmp/sms_SPAM_$PHONE"
fi
log "__SUB:security: ################################"
log "${c_red}__SUB:security: $PHONE COMMAND REJECTED:$c_ $TEXT"
exit
fi
echo "$TEXT" > "/tmp/sms_received_$PHONE"
# Remove SPAM flag older than one day
find /tmp -ctime +1 -type f -name "sms_SPAM_*" -exec rm -f '{}' \;
else
# THIS IS AN AKNOWLEGEMENT
log "__SUB:security: ################################"
log "${c_red}__SUB:security: $PHONE COMMAND REJECTED:$c_ $TEXT"
exit
fi
# Remove SPAM flag older than one day
find /tmp -ctime +1 -type f -name "sms_SPAM_*" -exec rm -f '{}' \;
}
#################################################################################################################################
function ipfs_swarm_wallets_refresh (){
# Refresh CURRENT NODE wallets STATUS
I=$(ipfs_node_wallets_add)
# REFRESH SWARM MEMORY
mkdir -p "./wallets_swarm"
chown -R $YOU "./wallets_swarm"
log "${yellow}__SUB:ipfs_swarm_wallets_refresh: REFRESHING SWARM $HASHLINK ($PHONE) shared memory...$c_"
if [[ $HASHLINK ]]; then rm -Rf ./wallets_swarm/PHONE/$HASHLINK; fi
# GET IPNS published wallets from ALL SWARM NODES / TODO: IF NODES MISSING, check ./wallets_swarm/.QmNODES...
#log "__SUB:ipfs_swarm_wallets_refresh: IPFS: ipfs get --output=./wallets_swarm/ /ipns/$IPFSNODEID"
su $YOU -c "ipfs get --output=./wallets_swarm/ /ipns/$IPFSNODEID"
count=1
# Search for All peers Nodes. TODO: To be changed when Swarm is too big and stable
for id in ./wallets_swarm/.Qm*/;
#for id in $(su $YOU -c "ipfs swarm peers" | awk -F '/' '{print $7}');
do
count=$((count+1))
id=$(echo $id | cut -d '.' -f 3 | cut -d '/' -f 1)
log "__SUB:ipfs_swarm_wallets_refresh: IPFS REFRESHING ./wallets_swarm/.$id"
rm -Rf ./wallets_swarm/.$id
su $YOU -c "ipfs get --output=./wallets_swarm/ /ipns/$id"
done
log "${c_green}__SUB:ipfs_swarm_wallets_refresh: ./wallets_swarm/ RENEW from $count peers .........OK!!!$c_"
############################################################################"
# TODO: MOVE AS GENERIC IPFS NODE DIALOG FUNCTION
# TREAT move_g1cents Tasks in ./wallets/.$IPFSNODEID
# IF NODE find in ./wallets_swarm/.$IPFSNODEID/TASK directory && Have it's G1 Wallet already (for natools crypto)
if [[ "$1" != "SIMPLE" && -d ./wallets_swarm/.$IPFSNODEID/TASK && -f "./wallets/.$IPFSNODEID/$IPFSNODEID.authfile.GPGPASS.gpg" ]]; then
############################################################################"
for task in $(ls ./wallets_swarm/.$IPFSNODEID/TASK/*.move_g1cents.*); # ./wallets/.$IPFSNODEID/TASK/$NANODATE.move_g1cents.$DESTPHONE.NODEPUB.crypt OR "done.$NANODATE" FILES
do
FTASK=$( echo $task | cut -d '/' -f 5 ) # "$NANODATE.move_g1cents.$DESTPHONE.NODEPUB.crypt"
TNANO=$( echo $FTASK | cut -d '.' -f 1) # $NANODATE
TTYPE=$( echo $FTASK | cut -d '.' -f 2) # move_g1cents
TDEST=$( echo $FTASK | cut -d '.' -f 3) # $DESTPHONE
HDEST=$(echo -n $TDEST | sha256sum | cut -d ' ' -f 1)
log "${c_yellow}__SUB:ipfs_swarm_wallets_refresh:$c_ .$IPFSNODEID($FTASK) FOUND TASK $TNANO:$TTYPE:$TDEST"
# MAKE LOCAL .$IPFSNODEID directory
mkdir -p ./wallets/.$IPFSNODEID/TASK/
# TODO: CHECK BETTER NOT DONE YET and $NANODATE > $TNANO (=> detect NODES writing in the future!!)
if [[ ! -f "./wallets/.$IPFSNODEID/TASK/done.$TNANO" ]]; then # NOT DONE YET: NEW TASK!
tdiff=$(bc -l <<< "$NANODATE - $TNANO")
if [[ $tdiff -gt 0 ]]; then
# GET BACK MY NODE G1 Wallet authfile from my LOCAL ./wallets
echo "${GPGPASS}" | gpg -q -d --output "./NODEG1Wallet.authfile" --yes --pinentry-mode loopback --symmetric --passphrase-fd 0 "./wallets/.$IPFSNODEID/$IPFSNODEID.authfile.GPGPASS.gpg"
# DECRYPT and CAT move_g1cents VALUE
./shell/natools.py decrypt -k "./NODEG1Wallet.authfile" -i "$task" -o "/tmp/move_g1cents.$TDEST"
ZENVAL=$(cat "/tmp/move_g1cents.$TDEST")
log "__SUB:ipfs_swarm_wallets_refresh: tdiff=$tdiff .$IPFSNODEID G1 = ./NODEG1Wallet.authfile :decrypt: Found $ZENVAL Zen to ADD"
rm -f "./NODEG1Wallet.authfile"
if [[ $ZENVAL -gt 0 ]]; then
curvalue=$(cat ./wallets/PHONE/$HDEST/_g1cents)
newvalue=$(bc -l <<< "$curvalue + $ZENVAL")
echo $newvalue > ./wallets/PHONE/$HDEST/_g1cents
echo "OK.$tdiff" > ./wallets/.$IPFSNODEID/TASK/done.$TNANO
log "${c_green}__SUB:ipfs_swarm_wallets_refresh: .$IPFSNODEID($FTASK) DONE!$c_ OPERATION: ($curvalue + $ZENVAL) = $newvalue Zen <=> ./wallets/PHONE/$HDEST/_g1cents:: OK"
# REFRESH ./wallets and PUBLISH
I=$(ipfs_node_wallets_add)
else
echo "KO.$tdiff" > ./wallets/.$IPFSNODEID/TASK/done.$TNANO
log "${red}__SUB:ipfs_swarm_wallets_refresh: .$IPFSNODEID($FTASK) ERROR!$c_ BAD: ($curvalue + $ZENVAL) = $newvalue Zen <=> ./wallets/PHONE/$HDEST/_g1cents :: ${red}KO$c_"
I=$(ipfs_node_wallets_add)
sms_SEND "$ADMINPHONE" "ADMIN! TASK ERROR: .$IPFSNODEID($FTASK) ERROR! BAD: ($curvalue + $ZENVAL) = $newvalue Zen <=> ./wallets/PHONE/$HDEST/_g1cents :: KO"
fi
else
# TODO: Bad NODE in the Future task !!! Make better BAD Node detection = Swarm Banish?
echo "KO.$tdiff" > ./wallets/.$IPFSNODEID/TASK/done.$TNANO
log "${red}__SUB:ipfs_swarm_wallets_refresh: .$IPFSNODEID($FTASK) ERROR!$c_ DATE PROBLEM: $NANODATE < $TNANO :: ${red}KO$c_"
I=$(ipfs_node_wallets_add)
sms_SEND "$ADMINPHONE" "ADMIN! .$IPFSNODEID($FTASK) ERROR! DATE PROBLEM: $NANODATE < $TNANO :: KO"
fi
fi
done
log "${c_yellow}__SUB:ipfs_swarm_wallets_refresh:$c_ REMOVE OLD TASK MARKED AS DONE"
for scan in ./wallets_swarm/.Qm*/TASK/done.*; do
lscan=$(echo $scan | sed s/_swarm//g )
lid=$(echo $scan | cut -d '/' -f 3 | cut -d '.' -f 2 )
lnano=$(echo $scan | cut -d '/' -f 5 | cut -d '.' -f 2 )
if [[ "$lid" != "$IPFSNODEID" ]]; then
log "__SUB:ipfs_swarm_wallets_refresh: CLEANING done OLD TASK ${lscan} SENT to $lid ($lnano.bin)"
rm -f ./wallets/.$lid/TASK/$lnano.*
I=$(ipfs_node_wallets_add)
fi
done
else
log "${c_yellow}__SUB:ipfs_swarm_wallets_refresh:$c_ .$IPFSNODEID :: NO TASK !"
############################################################################"
fi
}
#################################################################################################################################
function ipfs_node_wallets_add (){
##########################
##########################
IWALLETS=$(su $YOU -c "ipfs add -rHq './wallets' | tail -n 1")
# CHAIN STATE FOR $IPFSNODEID
echo $IWALLETS > ./wallets/.$IPFSNODEID.wallets.chain
log "${c_yellow}__SUB:ipfs_node_wallets_add:$c_ NEW './wallets' HASH ipfs ls /ipfs/$IWALLETS"
# PUBLISH IPNS NODE WALLETS
NODEWALLETS=$(su $YOU -c "ipfs name publish --quieter /ipfs/$IWALLETS")
log "__SUB:ipfs_node_wallets_add: G1smsWallet = ipfs cat /ipns/$NODEWALLETS/PHONE/$HASHLINK/_g1cents Zen"
echo $IWALLETS
}
#################################################################################################################################
function sms_uid2pubkey (){
## USE $PHONE link instead of real local $HASHLINK directory
RIBFILE="./wallets/PHONE/$PHONE/_uidrib"
NAMEFILE="./wallets/PHONE/$PHONE/_uidname"
UIDNAFILE="./wallets/PHONE/$PHONE/_uidna"
# ASKWALLET is
ASKWALLET="$1"
#For Micro Payement to DESTRIB (for easy G1sms wallet find in Cesium wallet History)
PHONE="$2"
PIN="$3"
# Get PHONE wallet UIDNA name
if [[ -f "$UIDNAFILE" ]]; then UIDNA=$(cat "$UIDNAFILE"); else UIDNA=""; fi
log "__SUB:sms_uid2pubkey: $UIDNA Wallet ($PHONE) is trying to associate to $ASKWALLET... SEARCHING..."
# Link to itSelf
if [[ $UIDNA && "$ASKWALLET" == "$UIDNA" ]]; then
log "__SUB:sms_uid2pubkey: "$ASKWALLET" == "$UIDNA" !!"
sms_SEND "$PHONE" "[G1sms+] $UIDNA est le nom de portefeuille G1sms. Il ne peut pas être associé à lui même!"
fi
# Test if _uidname file exists
if [ -f "$NAMEFILE" ]; then
# Actuel related wallet
UIDNAME=$(cat "$NAMEFILE")
log "__SUB:sms_uid2pubkey: Actual $UIDNA Wallet Related to $UIDNAME. Ask change to $ASKWALLET"
if [["$UIDNAME" != "$ASKWALLET" ]]; then
sms_SEND "$ADMINPHONE" "ADMIN! INFO: $PHONE Wallet associé à $UIDNAME change en $ASKWALLET !!"
sms_SEND "$PHONE" "[G1sms+] Votre portefeuille associé va passer de $UIDNAME à $ASKWALLET!"
fi
fi
# Search fo duplicate (TODO: choose $PHONE result
DUP=$(grep -Rwl "$ASKWALLET" ./wallets/PHONE/*/_uidname | tail -n 1 | cut -f 4 -d '/')
if [[ "$DUP" != "" ]]; then
sms_SEND "$ADMINPHONE" "ADMIN! INFO: $PHONE prend le même $ASKWALLET, que $DUP"
sms_SEND "$DUP" "Votre portefeuille associé $ASKWALLET vient d'être associé à $PHONE également!"
fi
###########################################################
# FIND ASKWALLET into wallets, wallest_swarm OR duniter (silkaj)
DESTMEM="$VIRDEST"
# SEARCH IN WALLETS
LOCAL=$(grep -Rwl "$ASKWALLET" ./wallets/PHONE/*/_uidna | tail -n 1 | cut -f 4 -d '/')
if [[ "$LOCAL" != "" ]]; then
# LOCAL G1sms account
DESTRIB=$(cat ./wallets/PHONE/$LOCAL/_pub)
DESTPHONE=$LOCAL
log "${c_yellow}__SUB:sms_uid2pubkey:$c_ FOUND LOCAL ($MASTERPHONE) G1sms Wallet: $DESTRIB ($DESTPHONE)"
else
# SEARCH IN WALLETS SWARM
INSWARM=$(grep -Rwl "$ASKWALLET" ./wallets_swarm/PHONE/*/_uidna | tail -n 1 | cut -f 4 -d '/')
if [[ "$INSWARM" != "" ]]; then
REMOTENODE=$(cat ./wallets_swarm/PHONE/$INSWARM/MASTERPHONE.sms)
REMOTENODEIPFSID=$(cat ./wallets_swarm/PHONE/$INSWARM/MASTERPHONE.ipfsid)
DESTRIB=$(cat ./wallets_swarm/PHONE/$INSWARM/_pub)
DESTPHONE=$INSWARM
log "${c_green}__SUB:sms_uid2pubkey: FOUND SWARM ($REMOTENODE) G1sms+ wallet: $DESTRIB ($DESTPHONE)$c_"
else
# SEARCH FOR DUNITER MEMBER WITH SILKAJ
log "__SUB:sms_uid2pubkey: GETTING FROM SILKAJ MEMBER ID"
DESTRIB=$(./silkaj/silkaj id "$ASKWALLET" | grep -w "$ASKWALLET" | awk '{print $2}')
log "__SUB:sms_uid2pubkey: OUT OFF SWARM MEMBER wallet: $DESTRIB"
# GET CESIUM+ geoPoint DATA (TODO: cron for GCHANGE SMS Alert)
curl -s ${CESIUM}/user/profile/${DESTRIB} | jq '._source.geoPoint' > "./wallets/PHONE/$PHONE/_uidgeo.json"
log "__SUB:sms_uid2pubkey: GET CESIUM+ geoPoint and AVATAR : $(cat ./wallets/PHONE/$PHONE/_uidgeo.json)"
curl -s ${CESIUM}/user/profile/${DESTRIB} | jq '._source.avatar._content' | sed 's/\"//g' | base64 -d > "./wallets/PHONE/$PHONE/_avatar.png"
fi
fi
if [ "$DESTRIB" != "" ]; then
echo "$DESTRIB" > "$RIBFILE"
echo "$ASKWALLET" > "$NAMEFILE"
log "${c_yellow}__SUB:sms_uid2pubkey:$c_ NEW RELATED $DESTRIB FOR G1sms WALLET = $ASKWALLET - INIT 0.1 TX"
INIT=$(./silkaj/silkaj transaction --auth-scrypt -salt="$UIDNA" -password="$PIN" --amount="0.1" --output=$DESTRIB --comment="[G1sms+] Porte Monnaie $(cat $UIDNAFILE) -> $(cat $NAMEFILE)" -y)
log "__SUB:sms_uid2pubkey: INIT = $INIT | Create Connection with related Wallet."
log_history "$PHONE" "MEMBER, $ASKWALLET"
sms_SEND "$ADMINPHONE" "ADMIN! LOG: $PHONE ($UIDNA) Compte relié >> $ASKWALLET ($INIT)"
else
sms_SEND "$ADMINPHONE" "ADMIN! LOG: $PHONE ($UIDNA) RELIER A $ASKWALLET INCONNU"
fi
log "__SUB:sms_uid2pubkey: $MEMBER($DESTRIB)"
echo "$DESTRIB"
}
#################################################################################################################################
function sms_INIT_ACCOUNT () {
log "${c_yellow}__SUB:sms_INIT_ACCOUNT:$c_ ($1=phone, $2=NOSMS)"
PHONE="$1"
UNKNOWN=0
# Initiate PHONE settings files and values
# WALLETS INTO ./wallets/CHANNEL/sha256sum(PHONE)
HASHLINK=$(echo -n $PHONE | sha256sum | cut -d ' ' -f 1)
# WALLETS INTO ./wallets/CHANNEL/sha256sum(PHONE)
IPFSNODEIDFILE="./wallets/PHONE/$PHONE/MASTERPHONE.ipfsid" # Contains G1sms+ NODE IPFS id
SMSNODE="./wallets/PHONE/$PHONE/MASTERPHONE.sms" # Contains G1sms+ SMS phone number
PINFILE="./wallets/PHONE/$PHONE/_pin" # Contains phone wallet diceware password
GPGPINFILE="./wallets/PHONE/$PHONE/_pin.gpg" # Contains g1smsnode cypher phone wallet diceware password
AUTHCRYPTFILE="./wallets/PHONE/$PHONE/_authfile.node.crypt" # authfile backup cyphered by Node G1 Pubkey
PUBKEYFILE="./wallets/PHONE/$PHONE/_pub" # Contains phone wallet public key (RIB)
UNITFILE="./wallets/PHONE/$PHONE/_unit" # Contains phone wallet prefered unit (LOVE,G1,DU)
RIBFILE="./wallets/PHONE/$PHONE/_uidrib" # Contains phone wallet related UID Pubkey
NAMEFILE="./wallets/PHONE/$PHONE/_uidname" # Contains Related MEMBER UID or Wallet UIDNA
MAILFILE="./wallets/PHONE/$PHONE/_email" # Contains the member EMAIL (Send BILLET)
GPGMAILFILE="./wallets/PHONE/$PHONE/_email.gpg" # Contains the member EMAIL (Send BILLET)
UIDNAFILE="./wallets/PHONE/$PHONE/_uidna" # Contains the G1sms+ UID Name for recursive VIR
GEOFILE="./wallets/PHONE/$PHONE/_uidgeo.json" # Contains the member GeoPoint from member Cesium+ related to wallet
RECFILE="./wallets/PHONE/$PHONE/VIREMENTS" # File showing recurrent payements are left to be done with this G1sms Wallet
GPGRECFILE="./wallets/PHONE/$PHONE/VIREMENTS.gpg" # Cypher file with GPGPASS (Node .Identity.PrivKey)
G1COUNTFILE="./wallets/PHONE/$PHONE/_g1cents" # Last sms_COUNT.sh call value
CHAINFILE="./wallets/PHONE/$PHONE/_chain" # Contains wallet last IPFS hash before ZEN value change
NNFILE="./wallets/PHONE/$PHONE/_n" # Contains Changes Number
DABUIDF="./wallets/PHONE/$PHONE/uidna.G1TAGNODE" # Contains G1Dab Name
# GET CURRENT NODE UIDNA (default DABUID)
NODEUIDNA=$(cat "./wallets/.$IPFSNODEID/_uidna")
######################################################################
######################################################################
# (NO $PINFILE) = FIRST ACCOUNT: Create wallet
######################################################################
if [ ! -f "$PINFILE" ]; then
# NOSMS mode? = DO NOT CREATE
if [[ $2 == "NOSMS" ]]; then UNKNOWN="unknown"; return; fi
#######################
# Create Account Files
#######################
if [[ ! -d ./wallets/PHONE/$HASHLINK ]]; then
mkdir -p ./wallets/PHONE/$HASHLINK
ln -s ./wallets/PHONE/$HASHLINK ./wallets/PHONE/$PHONE
fi
# LINKS ARE NOT REPLICATED INTO IPFS ;)
#######################
# GIVE NAME TO WALLET
#######################
# 4 derniers chiffres du numéro de téléphone
TAIL=${PHONE:8:4}
# No UIDNA yet. Create new
UID=$(./shell/diceware.sh 1 | xargs)
# Check if already existing among all swarm wallets
while [[ $(grep -Rwl $UID$TAIL ./wallets_swarm/*/*.uidna) ]]; do UID=$(./shell/diceware.sh 1 | xargs); done
UIDNA=$UIDNA$TAIL
echo "$UIDNA" > "$UIDNAFILE"
PIN=$(./shell/diceware.sh | xargs)
PUBKEY=$(./silkaj/silkaj generate_auth_file --auth-scrypt -salt="$UIDNA" -password="$PIN")
# BACKUP authfile available to authfile or PIN owner (DOUBLON AVEC PIN) TEST
log "__SUB:sms_INIT_ACCOUNT: ./shell/natools.py encrypt -p $NODE_G1PUBKEY -i ""./authfile"" -o ""$AUTHCRYPTFILE"""
./shell/natools.py encrypt -p $NODE_G1PUBKEY -i "./authfile" -o "$AUTHCRYPTFILE"
rm -f ./authfile
log "__SUB:sms_INIT_ACCOUNT: !! G1 Wallet CREATED: $PHONE $PIN : $PUBKEY (HASHLINK=$HASHLINK)"
#######################
# ACTIVATE G1SMS WALLET
#######################
# log "$NODE_G1AUTHFILE $PUBKEY THIRD_PARTY_MANAGER:$NODE_G1PUBKEY"
TX_IN=$(./silkaj/silkaj transaction --auth-file -file="$NODE_G1AUTHFILE" --amount=3.24 --output=$PUBKEY --comment="[G1sms+] $UIDNA 3RD:$NODE_G1PUBKEY " -y)
log "__SUB:sms_INIT_ACCOUNT: G1 Wallet TX IN: $TX_IN"
sleep 2
TX_OUT=$(./silkaj/silkaj transaction --auth-scrypt -salt="$UIDNA" -password="$PIN" --amount=0.1 --output=$NODE_G1PUBKEY --comment="[G1sms+] $UIDNA 3RD:$NODE_G1PUBKEY:ACK" -y)
log "__SUB:sms_INIT_ACCOUNT: G1 Wallet TX OUT: $TX_OUT"
################
# GPG cypher PIN (ONLY CREATOR NODE CAN ACCESS IT !)
################
echo "$PIN" > "$PINFILE"
# echo "${GPGPASS}" | gpg -q --output "$GPGPINFILE" --yes --pinentry-mode loopback --symmetric --passphrase-fd 0 "$PINFILE"
./shell/natools.py encrypt -p $NODE_G1PUBKEY -i "$PINFILE" -o "$PINFILE.node.crypt"
./shell/natools.py encrypt -p $SWARM_G1PUBKEY -i "$PINFILE" -o "$PINFILE.swarm.crypt"
# EMPTY CLEAR PIN
echo "" > "$PINFILE"
# WRITE G1sms WALLET FILES
echo "314" > "$G1COUNTFILE"
echo "0" > "$NNFILE"
echo "$PUBKEY" > "$PUBKEYFILE"
echo "$COIN" > "$UNITFILE"
echo "$MASTERPHONE" > "$SMSNODE"
log_history "$PHONE" "NEW, $PUBKEY"
# PUSH WALLET TO IPFS
I=$(ipfs_node_wallets_add)
fi
#################################################
# PUBLISH G1sms+ WALLET PROPERTIES MAIN PROCESS
#################################################
######################################################################
log "__SUB:sms_INIT_ACCOUNT: decrypting PIN..."
# GPG decypher PIN
# TODO make decypher less stress on filesystem, use /tmp and ramdisk
# echo "${GPGPASS}" | gpg -d -q --output "$PINFILE" --yes --pinentry-mode loopback --passphrase-fd 0 "$GPGPINFILE"
[[ "$PIN" == "" ]] && ./shell/natools.py decrypt -k "$NODE_G1AUTHFILE" -i "$PINFILE.node.crypt" -o "$PINFILE" && PIN=$(cat "$PINFILE" | xargs) && echo "" > "$PINFILE";
# DECYPHER MAIL
[[ -f "$MAILFILE.node.crypt" ]] && ./shell/natools.py decrypt -k "$NODE_G1AUTHFILE" -i "$MAILFILE.node.crypt" -o "$MAILFILE" && MAIL=$(cat "$MAILFILE") && echo "" > "$MAILFILE";
# PUBLISH GLOBAL VARS FROM ACCOUNT FILES
echo $IPFSNODEID > $IPFSNODEIDFILE
PUBKEY=$(cat "$PUBKEYFILE" | xargs)
UNIT=$(cat "$UNITFILE" | xargs)
if [ -f "$G1COUNTFILE" ]; then AMOUNTG1=$(bc <<< "scale=2; $(cat $G1COUNTFILE) / 100"); fi
if [ -f "$NAMEFILE" ]; then MEMBER=$(cat "$NAMEFILE"); else MEMBER=""; fi
if [ -f "$RIBFILE" ]; then MEMRIB=$(cat "$RIBFILE"); else MEMRIB=""; fi
if [ -f "$UIDNAFILE" ]; then UIDNA=$(cat "$UIDNAFILE"); else UIDNA=""; fi
if [ -f "$DABUIDF" ]; then DABID=$(cat "$DABUIDF"); else DABID="$NODEUIDNA"; fi
AMOUNTDU=$(bc <<< "scale=2; $AMOUNTG1 / $DUFACTOR")
AMOUNTLOVE=$(bc <<< "$AMOUNTG1 * 100 / $DUFACTOR")
case "$UNIT" in
G1)
AMOUNT=$AMOUNTG1
;;
DU)
AMOUNT=$AMOUNTDU
;;
*)
AMOUNT=$AMOUNTLOVE
;;
esac
log "__SUB:sms_INIT_ACCOUNT: $AMOUNTG1 = $AMOUNT $UNIT"
# LOG # TODO REMOVE PIN LOG!!
log "${c_yellow}#####################$c_"
log "PHONE: $PHONE"
# log "PIN: $PIN"
log "PUBKEY: $PUBKEY"
log "G1: $AMOUNTG1"
log "AMOUNT: $AMOUNT $UNIT"
log "UIDNA: $UIDNA"
log "MEMBER: $MEMBER"
log "MEMRIB: $MEMRIB"
log "MAIL: $MAIL"
log "DABID: $DABID"
log "${c_yellow}#####################$c_"
log "${c_green}__SUB:sms_INIT_ACCOUNT: END$c_"
}
#################################################################################################################################
function check_account (){
log "__SUB:check_account: SILKAJ...... max 21 sec....."
AMOUNTG1=$(./shell/timeout.sh -t 21 ./silkaj/silkaj amount "$PUBKEY")
AMOUNTDU=$(bc <<< "scale=2; $AMOUNTG1 / $DUFACTOR")
AMOUNTLOVE=$(bc <<< "$AMOUNTG1 * 100 / $DUFACTOR")
case "$UNIT" in
G1)
AMOUNT=$AMOUNTG1
;;
DU)
AMOUNT=$AMOUNTDU
;;
*)
AMOUNT=$AMOUNTLOVE
;;
esac
G1cents=$(echo "$AMOUNTG1*100" | bc -l | awk '{print int($0)}')
log "__SUB:check_account: $PHONE: $AMOUNTG1 = $AMOUNT $UNIT ($G1cents) - $PUBKEY"
if [[ "$G1cents" != "" ]]; then
NN=$(cat "./wallets/PHONE/$PHONE/_n") || NN=0
((NN++))
echo "$NN" > "./wallets/PHONE/$PHONE/_n"
echo $G1cents > "./wallets/PHONE/$PHONE/_g1cents"
echo "$NANODATE" > "./wallets/PHONE/$PHONE/_nanodate"
# REFRESH NODE IPFS wallets & PUBLISH
I=$(ipfs_node_wallets_add)
# Register modification
echo "$I" > "./wallets/PHONE/$PHONE/_chain"
else
# BAN actual Duniter Node in case of silkaj timeout.
export NEWDUNITER=$(./shell/checknodes.sh 'BAN')
log "${c_red}__SUB:check_account: !!! SILKAJ IS TOO SLOW !!!$c_ => NEW DUNITER SERVER: $NEWDUNITER"
fi
declare -a walletvalues
walletvalues=( "$AMOUNTG1" "$AMOUNT" "$UNIT" )
log "__SUB:check_account: $(declare -p walletvalues)"
echo ${walletvalues[@]}
}
#################################################################################################################################
function make_accounting (){
# CONVERT $AMOUNT $UNIT to $VIR G1
case "$UNIT" in
G1)
VIR=$AMOUNT;
;;
DU)
VIR=$(bc -l <<< "scale=2; $AMOUNT * $DUFACTOR")
;;
LOVE)
VIR=$(bc -l <<< "scale=2; $AMOUNT * $DUFACTOR / 100")
;;
*)
VIR=$AMOUNT;
;;
esac
log "${c_yellow}__SUB:make_accounting:$c_ $VIR G1 CHECKING FOR $PHONE / PUBKEY = $PUBKEY"
###########################################################
# GET G1sms wallet AMOUNTG1 and CHECK for right balance
# Ask silkaj. If timeout, use last known $PHONE _g1cents value
AMOUNTG1=$(./shell/timeout.sh -t 20 ./silkaj/silkaj amount "$PUBKEY")
[[ ! $AMOUNTG1 ]] && AMOUNTG1=$(bc -l <<< "scale=2; $(cat ./wallets/PHONE/$PHONE/_g1cents) / 100")
[[ "$AMOUNTG1" == "" ]] && AMOUNTG1=0
# TAX AND MINIMUM WALLET ACCOUNT CALCULATION
PERCENT=0$(bc -l <<< "scale=2; $VIR / $SWARMCOMM")
MIN=$(bc -l <<< "$AMOUNTG1 - $PERCENT - $LIMIT")
CHARGE=$(bc -l <<< "scale=2; $VIR + $PERCENT + $LIMIT")
TESTMIN=$( echo "${VIR} < ${MIN}" | bc -l )
log "__SUB:make_accounting: TEST $AMOUNT $UNIT :: $VIR + $PERCENT + $LIMIT = $CHARGE < $AMOUNTG1 ? $TESTMIN"
declare -a myarray
myarray=( "$TESTMIN" "$VIR" "$PERCENT" "$CHARGE")
log "__SUB:make_accounting: $(declare -p myarray)"
echo ${myarray[@]}
}
#################################################################################################################################
function move_g1cents (){
# MODIFY $PHONE.g1cents value according to current silkaj
# TODO MAKE ALL SILKAJ TX CALL HERE. OR REMOVE???
# USE TASK COMMUNICATION BETWEEN NODES.
phonesrc=$1
pubkeydest=$2
zenvalue=$3
log "${c_yellow}__SUB:move_g1cents:$c_ $phonesrc ($zenvalue) -> $pubkeydest :: $G1COUNTFILE ::"
### CHANGE INPUT VALUE ####
curvalue=$(cat ./wallets/$phonesrc/$phonesrc.g1cents | cut -d '.' -f 1)
newvalue=$(bc -l <<< "$curvalue - $zenvalue")
echo $newvalue > ./wallets/$phonesrc/$phonesrc.g1cents
log "__SUB:move_g1cents: DEBIT: OK APPLY $curvalue - $zenvalue = $newvalue TO ./wallets/$phonesrc/$phonesrc.g1cents"
### CHANGE OUTPUT VALUE ####
# TEST IF $dest is a wallets_ G1sms PUBKEY?
winnerphone=$(grep -Rwl "$pubkeydest" ./wallets_swarm/*/*.pub | cut -d '.' -f 2 | cut -d '/' -f 3)
if [[ $winnerphone ]]; then
# GET INFORMATON ON MANAGER NODE
NODEID=$(cat ./wallets_swarm/$winnerphone/MASTERPHONE.ipfsid)
if [[ "$NODEID" == "$IPFSNODEID" ]]; then
# ACTUAL NODE IS WALLET MANAGING NODE ;)
curvalue=$(cat ./wallets/$winnerphone/$winnerphone.g1cents | cut -d '.' -f 1)
newvalue=$(bc -l <<< "$curvalue + $zenvalue")
echo $newvalue > ./wallets/$winnerphone/$winnerphone.g1cents
log "__SUB:move_g1cents: CREDIT: OK APPLY $curvalue + $zenvalue = $newvalue TO ./wallets/$winnerphone/$winnerphone.g1cents"
else
# MUST ASK MANAGER NODE TO CORRECT g1cents FOR $winnerphone WALLET
# WRITE TASK TO .$NODEID CHANNEL
mkdir -p ./wallets/.$NODEID/TASK/
# USE natools with NODEPUB crypt
echo "$zenvalue" > "/tmp/move_g1cents.$winnerphone"
# GET NODE G1sms Wallet PUBKEY
NODEPUB=$(cat ./wallets_swarm/.$NODEID/_pub)
./shell/natools.py encrypt -p $NODEPUB -i "/tmp/move_g1cents.$winnerphone" -o "./wallets/.$NODEID/TASK/$NANODATE.move_g1cents.$winnerphone.NODEPUB.crypt"
log "__SUB:move_g1cents: CREDIT: WRITE TASK TO ./wallets/.$NODEID/$NANODATE.move_g1cents.$winnerphone.NODEPUB.crypt "
rm -f /tmp/move_g1cents.$winnerphone
fi
else
log "${c_red}__SUB:move_g1cents: ERROR: NO $pubkeydest WALLET FOUND$c_"
fi
# UPDATE MY new ./wallet STATUS to SWARM
I=$(ipfs_node_wallets_add)
}
#################################################################################################################################
# Contact database management
function add_contact(){
log "${c_yellow}Add user contact$c_"
userDB="gammu"
pwdDB=$(cat /etc/gammu-smsdrc | grep "password =" | awk '{ print $3 }' || exit 1)
local sql="mysql -N -u$userDB -p$pwdDB gammu -e"
local PHONE=$1
local MEMBERUID=$2
[[ -z $MEMBERUID ]] && MEMBERUID=$PHONE
[[ -z $($sql "SELECT * FROM pbk_groups WHERE ID='1'") ]] && $sql "INSERT INTO pbk_groups (ID, Name, id_user, is_public) VALUES ('1', '$(grep "ADRESSE" $MY_PATH/../.profile | awk -F= '{ print $2 }' | tr -d '"')', '1', 'false')"
if [[ -z $($sql "SELECT * FROM pbk WHERE Number=$PHONE") ]]; then
$sql "INSERT INTO pbk (GroupID, Name, Number, id_user, is_public) VALUES ('1', '$MEMBERUID', '$PHONE', '1', 'false')" || exit 1
local id_user=$($sql "SELECT ID FROM pbk WHERE Number=$PHONE" || exit 1)
$sql "INSERT INTO user_group (id_group, id_pbk, id_pbk_groups, id_user) VALUES ('$id_user', '$id_user', '1', '1')" || exit 1
log "${c_green}Done$c_"
else
log "${red}Contact already exist$c_"
fi
}
function rm_contact(){
log "${c_yellow}Remove user contact$c_"
userDB="gammu"
pwdDB=$(cat /etc/gammu-smsdrc | grep "password =" | awk '{ print $3 }' || exit 1)
local sql="mysql -N -u$userDB -p$pwdDB gammu -e"
local PHONE=$1
local MEMBERUID=$2
[[ -z $MEMBERUID ]] && MEMBERUID=$PHONE
if [[ ! -z $($sql "SELECT * FROM pbk WHERE Number=$PHONE") ]]; then
local id_user=$($sql "SELECT ID FROM pbk WHERE Number=$PHONE" || exit 1)
$sql "DELETE FROM pbk WHERE Number=$PHONE" || exit 1
$sql "DELETE FROM user_group WHERE id_group='$id_user'" || exit 1
log "${c_green}Done$c_"
else
log "${red}Contact doesn't exist$c_"
fi
}