#!/usr/bin/perl
use strict;
use warnings;
use Digest::SHA qw(sha256);
use FindBin qw($Bin);

print "Paste exactly 256 entropy bits, then press Return:\n";
my $bits = <STDIN> // '';
$bits =~ s/\s+//g;
die "Error: enter exactly 256 characters containing only 0 and 1.\n"
    unless length($bits) == 256 && $bits =~ /\A[01]+\z/;

open my $fh, '<', "$Bin/english.txt" or die "Cannot open english.txt: $!\n";
my @words = grep { length } map { chomp; $_ } <$fh>;
close $fh;
die "Error: english.txt must contain 2,048 words.\n" unless @words == 2048;

my $digest = sha256(pack('B*', $bits));
my $checksum = substr(unpack('B*', $digest), 0, 8);
my $combined = $bits . $checksum;

print "\nChecksum: $checksum\n\n24 BIP39 words:\n";
for my $i (0 .. 23) {
    my $group = substr($combined, $i * 11, 11);
    my $index = oct("0b$group");
    printf "%2d. %-10s  %s  (%d)\n", $i + 1, $words[$index], $group, $index;
}
