Crypt-HashCash

 view release on metacpan or  search on metacpan

bin/vault.pl  view on Meta::CPAN

#!/usr/bin/perl
# -*-cperl-*-
#
# vault.pl - Vault server for HashCash Digital Cash
# Copyright (c) 2017 Ashish Gulhati <crypt-hashcash at hash.neo.tc>
#
# $Id: bin/vault.pl v1.130 Sat Dec 22 18:42:26 PST 2018 $

use strict;
use warnings;

package Crypt::HashCash::Vault;

use vars qw(@ISA);
use Crypt::HashCash::Vault::Bitcoin;
use Crypt::HashCash::Coin::Blinded;
use Crypt::HashCash::CoinRequest;
use Crypt::HashCash::Coin;
use Crypt::HashCash qw (_dec _hex);
use Crypt::EECDH;
use Digest::MD5 qw(md5_hex);
use Net::Server::PreFork;
use File::HomeDir;
use Crypt::CBC;

my $HASHCASH = $ENV{HASHCASHDIR} || File::HomeDir->my_home . '/.hashcash';

unless (-d $HASHCASH) {
  die "Directory $HASHCASH doesn't exist and couldn't be created.\n" unless mkdir($HASHCASH, 0700);
}

unless (-d "$HASHCASH/vaults") {
  die "Directory $HASHCASH/.vaults doesn't exist and couldn't be created.\n" unless mkdir("$HASHCASH/vaults", 0700);
}

my $vault = new Crypt::HashCash::Vault::Bitcoin ( DB => "$HASHCASH/vault.db",
						  KeyDB => "$HASHCASH/vaults/vault.key" );

if (!-f "$HASHCASH/vaults/vault.key" or (defined $ARGV[0] and $ARGV[0] eq '--keygen')) {
  $|=1;
  print STDERR "Generating vault keys... ";
  $vault->keygen( Name   => 'localhost',
		  Server => 'localhost',
		  Port   => '20203',
		  Fees   => { mf => 50, mp => 0, vf => 50, vp => 0.001 } );
  print "done.\n";
}

$vault->mint->loadkeys();
my $sk = pack ('H*',$vault->mint->keydb->{vaultsec});

@ISA = qw(Net::Server::PreFork);

Crypt::HashCash::Vault->run();
exit;

sub process_request {
  my $self = shift;
  eval {
    local $SIG{ALRM} = sub { die "Timed Out!\n" };
    my $timeout = 60;                                    # Give client 60 seconds to send input
    alarm($timeout);
    while (<STDIN>) {
      /(\S+)/;                                           # Decrypt the message and get the key to encrypt reply with
      my $enchex = _hex($1);
      my $eecdh = new Crypt::EECDH;
      my ($request, $pubkey) = $eecdh->decrypt (Key => $sk, Ciphertext => pack ('H*', $enchex));
      diag("REQ: $request\n");
      alarm(0);
      my ($ret) = $vault->process_request($request);     # Process the request
      diag("RET: $ret\n");
      if ( defined $ret) {                               # Encrypt and return response
	my ($encrypted) = $eecdh->encrypt (PublicKey => $pubkey, Message => $ret);
	my $response = _dec(unpack 'H*', $encrypted);
	diag("RES: $response\n");
	print "$response\n";
      }
      alarm($timeout);
    }
  };
  if( $@=~/timed out/i ){
    print STDERR "Timed out\n";
    return;
  }



( run in 0.489 second using v1.01-cache-2.11-cpan-e1769b4cff6 )