#!/usr/bin/perl -w
use strict;
use diagnostics;
#use encoding 'cp1251';


 use JSON::RPC::Legacy::Client;
  use Data::Dumper;
 
  my $client = new JSON::RPC::Legacy::Client;
 
  $client->ua->credentials(
     'localhost:9357', 'jsonrpc', 'user' => 'pass'  # REPLACE WITH YOUR bitcoin.conf rpcuser/rpcpassword
      );
  my $count=0;
  my $uri = 'http://localhost:9357/';
  my $i = 0;
  #my $j = 0;
  print STDERR "дерьмо \n";
  for ($i = 1; $i<=40000; $i++)
  {
  #sleep (10) unless ($i%500);
  #$j = $i;
  #for ($j; $j<=$i+100; $j++)
  #{
  my $obj = {
      method  => 'getblockhash',
      params  => [$i],
   };
   
  my $res = $client->call( $uri, $obj );
     
  if ($res){
      if ($res->is_error) { print STDERR "Error : ", $res->error_message," \n" ;sleep (30); }
      else {
			my $bh = $res->result; 
			$obj = {
				method  => 'getblock',
				params  => [$bh],
			};
			$res = $client->call( $uri, $obj );
			unless (defined $res) {print STDERR "$i \n"; $i--; sleep (30); next;}
			#my $bc = $res->result;
			my $tidha = $res->result->{'tx'};
			#my %tid = %bc{'tx'};
			#$obj = {
			#	method  => 'getblock',
			#	params  => [$tid],
			#};
			while (defined( my $tid = pop @$tidha)){
					$obj = {
						method  => 'getrawtransaction',
						params  => [$tid],
					};
					$res = $client->call( $uri, $obj );
					unless (defined $res) {print STDERR "$i \n"; $i--; sleep (30); next;}
							$obj = {
								method  => 'decoderawtransaction',
								params  => [$res->result],
							};
					$res = $client->call( $uri, $obj );
					unless (defined $res) {print STDERR "$i \n"; $i--; sleep (30); next;}
					
					
					my $voita = $res->result->{'vout'};
					#print Dumper($voita);
					while (defined( my $wta = pop @$voita)){
						my $awa = $wta->{'scriptPubKey'}->{'addresses'};
						while (defined(my $aw = pop @$awa)){
							#print $aw, "\n";
							print $tid, "\n" if ($aw eq 'Sg2NdZywasiNUADzm5dxt6G1WWKyKkj9Mc');
						}
						$count++;
						#print Dumper($awa);
						;
						#while (defined( my $aw = pop @$voita)){
						#}
					}
					#print @$voita, "\n";
					#$count = $res->result;
					#print $count, "\n";
			}
			#my $tid = pop @$tidh;
			#print $tid;
			
			#print Dumper($tid);
			#print Dumper($tidh);
			#print Dumper($res->result); 
			}
  } else {print STDERR $client->status_line, " \n"; sleep (30);}
  
  #}
  #$i = $j;
  #print $count," $j", "\n";
  #sleep (1);
  }
  #my $obj = {
				#method  => 'decoderawtransaction',
				#params  => [$count],
			#};
  #my $res = $client->call( $uri, $obj );
  #print Dumper($res->result);
  
  print $count, "\n";