## These are commands to be run on a Linux machine (Debian or Ubuntu).
## The main workhorse for the discrete logarithm computations is CADO-NFS,
## and we use GP-Pari as a 'pocket calculator' for modular arithmetic.

# install some packages
sudo apt install pari-gp jq
sudo apt install libgmp3-dev gcc g++ cmake libhwloc-dev
alias gpnoc="gp -q --default colors=\"no\""

# download and compile cado-nfs
cd /tmp
git clone https://scm.gforge.inria.fr/anonscm/git/cado-nfs/cado-nfs.git
cd cado-nfs
# A previous version of this script was using version fdae0f9f382 of
# CADO-NFS, but this was not robust.
git checkout 6b3746a2ec27  # version of 16/08
make cmake
make -j 4

# download blockchain-voting and extract public keys
cd /tmp
git clone https://github.com/moscow-technologies/blockchain-voting.git
cd blockchain-voting
git checkout d70986b2c4da  # most recent version at the time of writing
cd /tmp

# loop on the 3 public keys; could be done in parallel on 3 machines.
for i in {0,1,2}; do

  start=`date +%s`
  # extract the public key information
  p=`jq .modulos[$i] /tmp/blockchain-voting/encryption-keys/keys/public-key.json | tr -d \"`
  g=`jq .generators[$i] /tmp/blockchain-voting/encryption-keys/keys/public-key.json | tr -d \"`
  h=`jq .publicKeys[$i] /tmp/blockchain-voting/encryption-keys/keys/public-key.json | tr -d \"`
  ell=`echo "($p-1)/2" | gpnoc`

  # run cado-nfs to get log of h (takes a few minutes)
  wdir=`mktemp -d /tmp/cadorunXXXXXX`
  log_h=`/tmp/cado-nfs/cado-nfs.py -dlp -ell $ell workdir=$wdir target=$h $p`

  # run again to get log of generator (faster, since it reuses precomputed data)
  log_g=`/tmp/cado-nfs/cado-nfs.py $wdir/p75.parameters_snapshot.0 target=$g`

  # deduce private key
  x=`gpnoc <<EOF
xell=lift(Mod($log_h,$ell)/Mod($log_g,$ell)); half=lift(1/Mod(2,$ell));
x0=lift(Mod(2*half*xell, 2*$ell)); h0=lift(Mod($g,$p)^x0);
if (h0 != $h, x0=lift(Mod(2*half*xell+$ell, 2*$ell)));
x0
EOF`

  stop=`date +%s`
  echo "Private key number $((i+1)) is $x, computed in $((stop-start)) seconds."
done
