Skip to content

Instantly share code, notes, and snippets.

@mwgamera
Created August 23, 2013 10:51
Show Gist options
  • Save mwgamera/6317999 to your computer and use it in GitHub Desktop.
Save mwgamera/6317999 to your computer and use it in GitHub Desktop.
Validate pubkey hash address for main Bitcoin network in Perl
#!/usr/bin/env perl
# check if string looks like a valid pubkey hash address for main Bitcoin network
# klg, Aug 2013
package Base58Check;
use strict;
use bytes;
use Carp;
use Digest::SHA 'sha256';
use Math::BigInt;
use constant BASE58 =>
'123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
sub decode(;$) {
$_ = shift // $_ // ''; s/\s//g;
my $z = length((m/^(1*+)/)[0]);
my ($x, @x) = Math::BigInt->bzero;
$x->bmul(58)->badd(index BASE58, $_) for split //;
unshift @x, ($x->bdiv(256))[1] while $x;
$_ = "\0" x $z . pack 'C*', @x;
croak 'Base58Check invalid' unless substr($_, (length)-4) eq
substr(sha256(sha256 substr $_, 0, (length)-4), 0, 4);
$_ = substr $_, 0, (length) - 4;
}
sub valid($) {
$_ = shift // $_;
eval {
Base58Check::decode;
length == 21 and ord == 0;
};
}
package test;
print "ok\n" if Base58Check::valid '13gdq5b3uq1T6Hdq8137wxJHz7jXHSDPXa';
# $_ eq "0" . ripemd160(sha256(pubkey))
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment