| 1 | # PODNAME: Finance::Dogecoin::Utils::NodeRPC | ||
| 2 | # ABSTRACT: make authenticated RPC to a Dogecoin Core node | ||
| 3 | |||
| 4 | use Object::Pad; | ||
| 5 | |||
| 6 | use strict; | ||
| 7 | use warnings; | ||
| 8 | |||
| 9 | class Finance::Dogecoin::Utils::NodeRPC { | ||
| 10 | use Mojo::UserAgent; | ||
| 11 | use Mojo::JSON 'decode_json'; | ||
| 12 | |||
| 13 | field $ua :param; | ||
| 14 | field $auth :param; | ||
| 15 | |||
| 16 | sub BUILDARGS( $class, %args ) { | ||
| 17 | $args{ua} //= Mojo::UserAgent->new; | ||
| 18 | unless ($args{auth}) { | ||
| 19 | if ($args{user} && $args{password}) { | ||
| 20 | $args{auth} = "$args{user}:$args{password}"; | ||
| 21 | } elsif ($args{user} && $args{auth_file}) { | ||
| 22 | my $auth = decode_json( $args{auth_file}->slurp_utf8 ); | ||
| 23 | $args{password} = $auth->{$args{user}} if exists $auth->{$args{user}}; | ||
| 24 | } | ||
| 25 | } | ||
| 26 | |||
| 27 | $args{auth} = "$args{user}:$args{password}"; | ||
| 28 | |||
| 29 | return %args; | ||
| 30 | } | ||
| 31 | |||
| 32 | method call_method( $method, @params ) { | ||
| 33 | my $res = $ua->post( | ||
| 34 | Mojo::URL->new('http://localhost:22555')->userinfo( $auth ), | ||
| 35 | json => { jsonrpc => '1.0', id => 'Perl RPCAuth', method => $method, params => \@params } | ||
| 36 | )->res; | ||
| 37 | |||
| 38 | return $res->json if $res->is_success; | ||
| 39 | |||
| 40 | if (! defined $res->is_error) { | ||
| 41 | warn "RPC server not available\n"; | ||
| 42 | } elsif ($res->code == 403) { | ||
| 43 | warn "Auth to Dogecoin RPC failed\n"; | ||
| 44 | } else { | ||
| 45 | warn "Something went wrong with Dogecoin RPC: " . $res->code . "\n"; | ||
| 46 | } | ||
| 47 | |||
| 48 | return {}; | ||
| 49 | } | ||
| 50 | } | ||
| 51 | |||
| 52 | __END__ |