Hush/List.pm

filter: Statementstmt 90.4% 19 / 21 Branchbran n/a Conditioncond n/a MC/DCmcdc n/a Subroutinesub 100% 7 / 7 Podpod n/a totaltotal 92.8% 26 / 28 CC 1 SCAR 0.4
CC
1
Cov
90%
BEGIN
1.3
BEGIN
1.0
BEGIN
1.0
CRAP 1.0
« Hush/Contact.pm ↑ Summary Hush.pm »
1 package Hush::List;
2 1 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
3 1 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 1 ▶use Hush::RPC;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 1 ▶use Try::Tiny;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 1 ▶use File::Spec::Functions;
Subroutine BEGIN: called CC=1 SCAR=0.0
7 1 ▶use Hush::Util qw/barf is_valid_zaddr/;
Subroutine BEGIN: called CC=1 SCAR=0.0
8 0 ▶use File::Slurp;
Subroutine BEGIN: called CC=1 SCAR=2.6
9 use Hush::Memo;
10 use Hush::Logger qw/debug/;
11 use Hush::Contact;
12 use Data::Dumper;
13 use JSON;
14  
15 =head1 NAME
16  
17 Hush::List - HushList Protocol Reference Implementation
18  
19 =head1 DESCRIPTION
20  
21 HushList
22  
23 =head1 SYNOPSIS
24  
25 # API access
26 use Hush::List;
27  
28 # CLI
29 hushlist subscribe 'hushlist://SKxqPjNKvcfpmBpR8daQHNj4DoMfKmaPiVcT3A3YPynZNYXoDoaq?height=215683'
30  
31 =head1 AUTHOR
32  
33 Duke Leto <duke@leto.net>
34  
35 =head1 SUPPORT THIS WORK
36  
37 If you would like to support this work, because it helped you out
38 and your life is now amazing, feel free to send some donations to
39 the developer via the blockchain :
40  
41 HUSH: zcB3LvCwYPdvVmNmTvEFdFGwb4teocrPnVD8wvBgMn8ZKo5Vq9ypJLpAuqUM31hEbBnSHCjCpax5mjUi2HEM6NB8x7vfKrV
42  
43 ZEC: zcZLVdeNHvbw58ch56RWi92ws8hweLHyxhoT6jniFKd8kkBPXPR5E46YXzAqXhrfagtwRojAtumg4M3kmrHfZPU6m63Rj5z
44  
45  
46 Cryptocoins make the world go round and round.
47  
48 =head1 COPYRIGHT
49  
50 Copyright (c) 2017-2018 by Duke Leto <duke@leto.net>. All rights reserved.
51  
52 =head1 LICENSE AGREEMENT
53  
54 This package is free software; you can redistribute it and/or
55 modify it under the GNU Public License Version 3.
56  
57 =cut
58  
59 # as per z_sendmany rpc docs
60 my $MAX_RECIPIENTS = 54;
61 my $HUSH_CONFIG_DIR = $ENV{HUSH_CONFIG_DIR} || catdir($ENV{HOME},'.hush');
62 my $HUSHLIST_CONFIG_DIR = $ENV{HUSH_CONFIG_DIR} || catdir($HUSH_CONFIG_DIR, 'list');
63 our $VERSION = 20180215;
64 my $rpc = Hush::RPC->new;
65  
66 sub _sanity_checks {
67 if (!-e $HUSH_CONFIG_DIR ) {
68 barf "Hush config directory $HUSH_CONFIG_DIR not found! You can set the HUSH_CONFIG_DIR environment variable if it is not ~/.hush";
69 }
70  
71 my $list_conf = catfile($HUSHLIST_CONFIG_DIR, 'list.conf');
72  
73 if (!-e $HUSHLIST_CONFIG_DIR) {
74 print "No Hush List config directory found, creating one...\n";
75 if (mkdir $HUSHLIST_CONFIG_DIR) {
76 print "Created $HUSHLIST_CONFIG_DIR\n";
77 } else {
78 barf "Could not create $HUSHLIST_CONFIG_DIR, bailing out";
79 }
80 create_default_conf($rpc,$list_conf);
81  
82 if (mkdir catdir($HUSHLIST_CONFIG_DIR,'contacts')) {
83 print "Created $HUSHLIST_CONFIG_DIR/contacts\n";
84 } else {
85 barf "Could not create $HUSHLIST_CONFIG_DIR/contacts, bailing out";
86 }
87  
88 } else {
89 # directory exists, does the conf file?
90 if (-e $list_conf) {
91 # conf file already exists, DO NOTHING
92 debug("detected existing $list_conf");
93 } else {
94 # no config file found, generate one
95 create_default_conf($rpc,$list_conf);
96 }
97 }
98 }
99  
100 sub create_default_conf {
101 my ($rpc,$list_conf) = @_;
102  
103 # when we create a brand new conf, we create brand new funding+nym addrs
104 my $funding_zaddr = $rpc->z_getnewaddress;
105 barf "Unable to create funding zaddr" unless $funding_zaddr;
106  
107 my $pseudonym_taddr = $rpc->getnewaddress;
108 barf "Unable to create pseudonym taddr" unless $pseudonym_taddr;
109  
110 debug("setting funding_zaddr=$funding_zaddr, pseudonym_taddr=$pseudonym_taddr");
111  
112 my $time = time;
113 # this will overwrite an existing conf!!! should we back up last version?
114 open my $fh, ">", $list_conf or barf "Could not write file $list_conf ! : $!";
115 print $fh "# hushlist config v$Hush::List::VERSION\n";
116 print $fh "funding_zaddr=$funding_zaddr\n";
117 print $fh "pseudonym_taddr=$pseudonym_taddr\n";
118 print $fh "generated=$time\n";
119 close $fh;
120  
121 debug("created new config file $list_conf");
122 }
123  
124 sub new {
125 my ($rpc,$options) = @_;
126 my $hush_list = {};
127  
128 # we only need a single RPC connection
129 $hush_list->{rpc} = $rpc;
130 $hush_list->{lists} = {};
131  
132 _sanity_checks();
133  
134 return bless $hush_list, 'Hush::List';
135 }
136  
137 sub list_members {
138 }
139  
140 # show overview of current hushlists
141 sub global_status {
142 my ($self) = @_;
143 my @hushlists = map { -d $_ && $_ } glob catdir($HUSHLIST_CONFIG_DIR,'*');
144 print "Hushlists:\n";
145 for my $hushlist (@hushlists) {
146 my $members_file = catfile($hushlist,'members.txt');
147 if (-e $members_file) {
148 my @members = read_file($members_file);
149 print "\t- $hushlist: " . scalar(@members) . " members \n";
150 }
151 }
152  
153 print "Hushlist contacts:\n ";
154  
155 # other possibilties: KMD, ZEN, others?
156 my @chains = qw/hush tush zec taz/;
157  
158 for my $chain (@chains) {
159 my $contacts_file = catdir($HUSHLIST_CONFIG_DIR,"$chain-contacts.txt");
160 if (-e $contacts_file) {
161 my @contacts = read_file($contacts_file);
162 my $uchain = uc($chain);
163 print "\t- " . scalar(@contacts) . " $uchain contacts\n";
164 }
165 }
166 }
167  
168 sub _hushlist_exists {
169 my ($name) = @_;
170 my $list_dir = catdir($HUSHLIST_CONFIG_DIR,$name);
171 return (-e $list_dir) ? 1 : 0;
172 }
173  
174 sub exit_unless_hushlist_exists {
175 my ($name) = @_;
176 if (!_hushlist_exists($name)) {
177 print "Hushlist $name does not exist!\n";
178 exit(1);
179 };
180 }
181  
182 # show details about a particular (hushlist,addr) pair
183 # NOTE: We assume that we only use one addr per hushlist for
184 # maximim metadata privacy, that is what we do, but other/custom software
185 # could break that assumption. The user is encouraged to create 2 local
186 # hushlists, with the same contacts, but different sending address (perhaps one
187 # taddr and one zaddr) if they want to send from multiple addresses
188 sub show {
189 my ($self,$name) = @_;
190  
191 exit_unless_hushlist_exists($name);
192  
193 my $list_specific_conf = catfile($HUSHLIST_CONFIG_DIR,$name,'list.conf');
194 my %list_conf = read_file( $list_specific_conf ) =~ /^(\w+)=(.*)$/mg ;
195 #TODO: write out new keys zfrom/tfrom
196 my $sending_zaddr = $list_conf{zfrom} || $list_conf{tfrom} || $list_conf{sending_zaddr};
197  
198 # todo: validate
199 #barf "Invalid sending_zaddr: '$sending_zaddr' found for Hushlist $name!" unless is_valid_zaddr($sending_zaddr);
200  
201 print "Hushlist: $name\n";
202 print "Recents memos:\n";
203 # show the last 10 memos with env var over-ride
204 my $N = $ENV{HUSHLIST_NUM_MEMOS} || 10;
205  
206 # TODO: detect the last N memos to our zaddr for this list
207 # 1) look for xtns to zaddr via RPC
208 # 2) any xtns TO this zaddr are Hushlist memos
209 # 3) iterate over these and grab memo field (only available locally on the
210 # full node which has the xtn, unles txindex=1 on hush full node!)
211 #TODO: sometimes you can send from a taddr
212 my @memos = find_memos($name, $sending_zaddr);
213  
214 if (@memos) {
215 print "Found memos!\n";
216 } else {
217 print "No memos found!\n";
218 }
219 }
220  
221 sub find_memos {
222 my ($name,$zaddr) = @_;
223  
224 #warn "looking up xtns for $zaddr";
225 my @xtns = $rpc->z_listreceivedbyaddress($zaddr);
226  
227 if (@xtns) {
228 # TODO: need local shielded balance to get data => need (t,z) xtn
229  
230 my @memos = map { Hush::Memo->new($rpc, $_) } @xtns;
231  
232 # debugging
233 for my $xtn (map { $_->[0] } @xtns) {
234 #printf "txid=%s memo=%s\n", $xtn->{txid}, $xtn->{memo};
235 my $txid = $xtn->{txid};
236 my $memo = pack('h*', $xtn->{memo});
237 printf "=" x 80;
238 print "\n";
239 printf <<HEAD;
240 Hushlist '$name' Memo
241 txid=$txid
242 ---
243  
244 HEAD
245 printf "$memo\n";
246 printf "=" x 80;
247 print "\n";
248 }
249 return @memos;
250 } else {
251 debug("find_memos: No memos found for $name + $zaddr");
252 }
253 return;
254 }
255  
256  
257 # show details about a particular hushlist
258 sub status {
259 my ($self,$name) = @_;
260  
261 exit_unless_hushlist_exists($name);
262  
263 my $list_specific_conf = catfile($HUSHLIST_CONFIG_DIR,$name,'list.conf');
264 my %list_conf = read_file( $list_specific_conf ) =~ /^(\w+)=(.*)$/mg ;
265 my $member_list = catfile($HUSHLIST_CONFIG_DIR,$name,'members.txt');
266 my @members = read_file($member_list);
267 my @nicknames = map { m/^[^ ]+(.*)/ } @members;
268 my $num_members = @members;
269 print "Hushlist '$name' has $num_members members, generated at $list_conf{generated}\n";
270 #map { print "\t - $_\n" } @nicknames;
271 map { print "\t - $_" } @members;
272 }
273  
274 sub new_list {
275 my ($self,$name) = @_;
276 my $lists = $self->{lists};
277 # a list is simply a list of addresses, which can be looked up by name, and maybe some other metadata
278 $lists->{$name} = { recipients => {} };
279  
280 my $list_dir = catdir($HUSHLIST_CONFIG_DIR,$name);
281 if (!-e $list_dir) {
282 # create the config dir for the list for the first time
283 mkdir $list_dir;
284 if (!-e $list_dir) {
285 barf "Could not create directory $list_dir !";
286 }
287 } else {
288 barf "Hushlist $name already exists!";
289 }
290 my $list_specific_conf = catfile($HUSHLIST_CONFIG_DIR,$name,'list.conf');
291 my $member_list = catfile($HUSHLIST_CONFIG_DIR,$name,'members.txt');
292 my $time = time;
293 my $sending_zaddr = $rpc->z_getnewaddress;
294  
295 {
296 open my $fh, '>', $list_specific_conf or barf "Could not open $list_specific_conf for writing";
297 print $fh "# hushlist $name config v$Hush::List::VERSION\n";
298 # every list has a unique sending zaddr, so there is no metadata leaked
299 # across one user sending messages to multiple hushlists
300 print $fh "sending_zaddr=$sending_zaddr\n";
301 print $fh "generated=$time\n";
302 # default chain is hush for now
303 # changing the chain of an existing list means that the subset
304 # of members that have addresses in the local contact list for the
305 # new chain will receive message, or operation aborts if no valid
306 # contacts on new chain
307 print $fh "chain=hush\n";
308 close $fh;
309 }
310  
311 {
312 open my $fh, '>', $member_list or barf "Could not open $member_list for writing";
313 print $fh "";
314 close $fh;
315 }
316  
317 # We consider members.txt the oracle, so users can simply maintain a simple
318 # text file of one item per line, and other files serialized version
319 # ~/.hush/list/LIST_NAME/
320 # ~/.hush/list/LIST_NAME/list.conf - list-specific config items
321 # ~/.hush/list/LIST_NAME/members.txt - list member zaddrs, one per line
322 # ~/.hush/list/LIST_NAME/list.json - list data, in JSON
323 # ~/.hush/list/LIST_NAME/list.png - user-specified image for list
324 return $self;
325 }
326  
327 # make a local hushlist PUBLIC by publishing its PRIVKEY
328 # to the blockchain via OP_RETURN. This is a ONE WAY PROCESS!!!
329 # You can not make a public hushlist private again, it's privkey is in the wild,
330 # but we CAN make
331 sub public {
332 my ($self,$name) = @_;
333 }
334  
335 # hushlist://SKxqPjNKvcfpmBpR8daQHNj4DoMfKmaPiVcT3A3YPynZNYXoDoaq?height=215683
336 sub subscribe {
337 my ($self,@hushlist) = @_;
338 my ($chain, $net, $key, $height) = @hushlist;
339 #warn Dumper [ @hushlist ];
340  
341 my $rescan = "whenkeyisnew";
342 $rpc->z_importkey($key, $rescan, $height + 0);
343 print "Successfully subscribed to hushlist://$key !\n";
344 return $self;
345 }
346  
347 sub add_contact {
348 my ($self,$name,$contact) = @_;
349  
350 #TODO validate
351 $name ||= '';
352 barf "Invalid Hushlist list name!" unless $name;
353  
354 $contact||= '';
355 barf "Invalid Hushlist contact=$contact" unless $contact;
356  
357 #barf "Hush list $list does not exist" unless $list;
358  
359 # TODO: does contact exist already?
360 my $member_list = catfile($HUSHLIST_CONFIG_DIR,$name,'members.txt');
361 open my $fh, '>>', $member_list or barf "Could not open $member_list for writing";
362 print $fh $contact . "\n";
363 close $fh;
364  
365 return $self;
366 }
367  
368 sub remove_zaddr {
369 my ($self,$name,$zaddr) = @_;
370 barf "Invalid zaddr=$zaddr" unless $zaddr;
371  
372 my $lists = $self->{lists};
373 my $list = $lists->{$name};
374  
375 barf "Hush list $list does not exist" unless $list;
376  
377 delete $list->{recipients}->{$zaddr};
378  
379 return $self;
380 }
381  
382 # send a memo to a Hush List, weeeeee!
383 sub send_memo {
384 my ($self,$rpc,$name,$memo) = @_;
385  
386 # TODO: better validation
387 barf "Invalid Hush list name" unless $name =~ m/^([a-z0-9]+)$/i;
388 barf "Hush memo cannot be empty" unless $memo;
389  
390 my $MAX_MEMO = 512;
391 my $length = length($memo);
392  
393 barf("Hushlist memo too large! $length > $MAX_MEMO") if ($length > $MAX_MEMO);
394  
395 #my $debug = sub { debug("send_memo: @_") };
396 my $debug = sub { warn "send_memo: @_" };
397  
398 # each hush list has a sending_zaddr defined at time of creation
399 # which is used to send to this list
400 my $list_specific_conf = catfile($HUSHLIST_CONFIG_DIR,$name,'list.conf');
401 unless (-e $list_specific_conf) {
402 barf "Hushlist config for $name list not found!";
403 }
404  
405 my %list_conf = read_file( $list_specific_conf ) =~ /^(\w+)=(.*)$/mg ;
406 my $from = $list_conf{zfrom} || $list_conf{tfrom} || $list_conf{sending_zaddr};
407 # default should probably be TUSH, but meh...
408 my $chain = $list_conf{chain} || 'hush';
409  
410 #barf "Invalid Hushlist chain! $chain" unless $chain =~ m/$(tush|hush)$/i;
411 barf "Invalid Hush from address! $from" unless $from;
412  
413 my $list_members_file = catfile($HUSHLIST_CONFIG_DIR,$name,'members.txt');
414 unless (-e $list_members_file) {
415 barf "No members file found for Hushlist $name!";
416 }
417 my @list_members = read_file( $list_members_file );
418 # we sometimes get a trailing newline, sigh
419 chomp @list_members;
420 my %list_members = map { $_ => 1 } @list_members;
421 #$debug->("list_members=" . join(",",@list_members));
422 warn Dumper [ @list_members ];
423  
424 # Now that we have all the list member pseudonyms, look them
425 # up in the appropriate chain
426  
427 my $contacts_file = catdir($HUSHLIST_CONFIG_DIR,"$chain-contacts.txt");
428 unless (-e $contacts_file) {
429 barf "Could not find Hushlist contacts for chain $chain!";
430 }
431  
432 # grab all contacts
433 # TODO: serialize/make more effiecient/etc
434 my %contacts = read_file( $contacts_file ) =~ /^([a-z0-9]+) (.*)$/mgi ;
435 $debug->("contacts=" . join(",",keys %contacts));
436 # this is the subset of contacts that we are sending to on this hushlist
437 # with proper amount/memo keys to appease the z_sendmany gods
438 my $list_addrs = { };
439  
440 # This must be a string to make JSON elder gods happy
441 my $amount = "0.00"; # amount is hidden in (z,z) xtns, so it does not identify list messages via metadata
442  
443 # override default amount with the amount key in this lists config file
444 if ($list_conf{amount}) {
445 $amount = $list_conf{amount} . "";
446 }
447  
448 my $raw_memo = unpack("h*",$memo); # backend wants hex-encoded memo-field
449 $debug->("memo=$memo");
450 $debug->("raw_memo=$memo");
451  
452 while (my ($addr, $contact) = each %contacts) {
453 print "contact $contact has $addr\n";
454  
455 # if this contact exists on this list, add them to recipient list for z_sendmany
456 if ($list_members{$contact}) {
457 $debug->("adding $contact => $addr to recipients");
458 $list_addrs->{$contact} = {
459 address => $addr,
460 amount => $amount,
461 memo => $raw_memo,
462 };
463 }
464 }
465 warn Dumper [ $list_addrs ];
466  
467 barf "Max recipients of $MAX_RECIPIENTS exceeded" if (keys %contacts > $MAX_RECIPIENTS);
468  
469 $debug->("initiating z_sendmany");
470  
471 my $default_fee = 1e-4;
472 my $CURR = "HUSH";
473 my $fee = defined $ENV{HUSHLIST_FEE} ? sprintf "%.8f", $ENV{HUSHLIST_FEE} : $default_fee;
474 my $balance = $rpc->z_gettotalbalance;
475 my $zbalance = $balance->{private};
476 my $tbalance = $balance->{transparent};
477 my $recipients = (keys %$list_addrs);
478  
479 # this is the total cost to send the current Hush
480 # transaction to N recipients each with $fee
481 my $total_cost = $fee * $recipients;
482 $debug->("calculated total_cost=$total_cost $CURR for $recipients recipients");
483  
484 # decide on which balance to look at
485 my $available_balance = ($from =~ m/^zc/) ? $zbalance : $tbalance;
486  
487 if ($available_balance < $fee) {
488 $debug->("Insufficient balance to pay even one fee=$fee");
489 return;
490 }elsif ($available_balance < $total_cost) {
491 $debug->("Insufficient balance to pay full xtn fee=$total_cost to $recipients recipients with balance=$available_balance");
492 return;
493 }
494  
495 # z_sendmany
496 # Arguments:
497 # 1. "fromaddress" (string, required) The taddr or zaddr to send the funds from.
498 # 2. "amounts" (array, required) An array of json objects representing the amounts to send.
499 # [{
500 # "address":address (string, required) The address is a taddr or zaddr
501 # "amount":amount (numeric, required) The numeric amount in ZEC is the value
502 # "memo":memo (string, optional) If the address is a zaddr, raw data represented in hexadecimal string format
503 # }, ... ]
504 # 3. minconf (numeric, optional, default=1) Only use funds confirmed at least this many times.
505 # 4. fee (numeric, optional, default=0.0001) The fee amount to attach to this transaction.
506  
507 my $minconf = 1;
508 my $opid = $rpc->z_sendmany($from, [values %$list_addrs], $minconf, $fee);
509  
510 if (defined $opid) {
511 $debug->("z_sendmany opid=$opid from $from");
512 # omg we got an opid, lets see what is up
513 my @opids = ( $opid );
514 my $status = $rpc->z_getoperationstatus([@opids]);
515 if ($status) {
516 $debug->("$opid has status=$status");
517 } else {
518 $debug->("no status for opid=$opid");
519 }
520 } else {
521 $debug->("z_sendmany failed!");
522 }
523  
524 return $self;
525 }
526  
527 sub new_taddr {}
528 sub new_zaddr {}
529  
530 1;
« Hush/Contact.pm ↑ Summary Hush.pm »