Cannot decode! Invalid Base58 Character(s)!

Viewed 3811

I am trying to run base58perl.pl in my terminal using the following command:

perl base58perl.pl

but I get the following error:

Cannot decode! Invalid Base58 Character(s)!

Here's the code:

my $fileSrc = 'base58.txt';
open my $fhSrc, $fileSrc or die "Could not open $fileSrc: $!";

my $fileDest = 'hex.txt';
open( my $fhDest, '>>', $fileDest) or die "Could not open file $fileDest: $!";

while ( my $base58_encoded_address = <$fhSrc >)  {   
    my $binary_address = decodebase58tohex($base58_encoded_address);
    say $fhDest $binary_address;
}

close $fhSrc;
close $fhDest;

The content of base58.txt is a list of BTC address in base58 form.

I also have tried

chmod a+x base58perl.pl
perl base58perl.pl

base58.txt contents:

1E5PBfSaFawBy1RjBHkS6FDtCwXkYSsVTo
1DCgptTS2uY2occbVdW1qcVT72T75RXbyg
1CUNEBjYrCn2y1SdiUMohaKUi4wpP326Lb 

I still get the same error.

4 Answers

That error message comes from the unbase58 function in the code you have linked.

die "Cannot Decode! Invalid Base58 Character(s)!\n" unless $bitcoin_address =~ /^[1-9A-HJ-NP-Za-km-z]*$/;

That line checks if the input contains only characters of the character group [1-9A-HJ-NP-Za-km-z]. Since your input does, it must dislike something else.

My guess is that it disliked the newline characters at the end of your lines. You need to chomp them off before passing the value to decodebase58tohex.

while( my $base58_encoded_address = <$fhSrc>)  {   
    chomp $base58_encoded_address;
    my $binary_address = decodebase58tohex($base58_encoded_address);
    say $fhDest $binary_address;
}

You probably need to remove whitespace. You appear to be passing only chunks of the string to the decode function at a time, which could also be a problem. Read the whole file into a var, remove any whitespace, then decode.

my $base58_encoded_address = do { local $/; <$fhSrc> };
$base58_encoded_address =~ s/\s+//g;
my $binary_address = decodebase58tohex($base58_encoded_address);
say $fhDest $binary_address;

The script is now working properly, the problem was the base58.txt the file was created using notepad. I created a new file using a different text editor.

my $fileSrc = 'base58.txt';
open my $fhSrc, $fileSrc or die "Could not open $fileSrc: $!";

my $fileDest = 'hex.txt';
open( my $fhDest, '>>', $fileDest) or die "Could not open file $fileDest: $!";

my @tmp = <$fhSrc>;
chomp @tmp;
for my $line (@tmp)  {   
    print "decoding '$line'\n";
    my $binary_address = decodebase58tohex($line);
    say $fhDest $binary_address;
}

close $fhSrc;
close $fhDest;

As someone else mentioned I think your dealing with whitespaces. chomp will take care of that for you.

The next thing to do is print the string you are trying to decode in quotes which will confirm your only decoding what you want to.

Related