#!/usr/bin/env python3
"""Independent reference for Permaweb Standard Seeds v1.0 (docs/seed-wallet-derivation.md):
a seed phrase to a numbered sequence of RSA-4096 Arweave wallets.

This deliberately shares no code, language, big-integer library, hash library or primality-test
structure with core/api/wallet. It regenerates vectors.json, which the unit tests compare against
the TypeScript implementation. Standard library only; takes a few minutes.

    python3 tests/fixtures/seed-wallets/reference.py > tests/fixtures/seed-wallets/vectors.json
    python3 tests/fixtures/seed-wallets/reference.py --legacy > tests/fixtures/seed-wallets/legacy-vectors.json
    npx prettier --write tests/fixtures/seed-wallets/vectors.json tests/fixtures/seed-wallets/legacy-vectors.json

Every phrase is public test data.

It also derives one wallet again from a phrase. The phrase is read from the first line of standard
input and a passphrase from the second, if there is one; the keyfile is written to standard output:

    python3 reference.py --keyfile 0 > wallet-1.json

(Wallet number 0 is the first wallet. Add --legacy for the legacy form.)

The scheme, for wallet number N with 0 <= N <= 2^31 - 1 (section numbers are the specification's):

    4  S    = BIP-39 seed of the normalized phrase and passphrase (64 bytes)
    5  M    = kL of the BIP32-Ed25519 node m/44'/472'/N'/0'/0' of S (32 bytes)
    6  s_j  = int(SHA-256(0x01 || j || M || 0x00) || ... || SHA-256(0x01 || j || M || 0x07)) | 3 * 2^2046
    7  o    = s_j if s_j is odd, else s_j + 1; prime(s_j) = the smallest prime greater than o
    8  p = prime(s_0), q = prime(s_1), n = p*q, e = 65537, d = e^-1 mod lcm(p-1, q-1),
       dp = d mod (p-1), dq = d mod (q-1), qi = q^-1 mod p

The legacy form, which the Ledger Arweave application derives, differs in section 6 only: its label
byte is 0x00 and it forces the top bit alone (| 2^2047). It is kept here for one reason: sections 4,
5, 7 and 8 are the same code for both forms, and the legacy form has a published answer from a real
device. The first set is the phrase of the Ledger Arweave application's emulator test
(LedgerHQ/app-arweave, tests_zemu/tests/address.test.ts); this script must reproduce that test's
published address for wallet 0 in the legacy form before it writes anything in either form.
"""

import base64
import hashlib
import hmac
import json
import math
import sys
import unicodedata

E = 65537
HARDENED = 0x80000000
HIGHEST_NUMBER = 2**31 - 1

LEDGER_PUBLISHED_ADDRESS = "ruH8xdwP4Y0rK3YpQOSO8pfmtao9sGi4HriXrg-5ZLg"
LEDGER_TEST_PHRASE = "equip will roof matter pink blind book anxiety banner elbow sun young"
# Wallet 0 of the same phrase in Permaweb Standard Seeds v1.0, as this script, the two engines of
# PermawebOS and its cross-check all derive it (vectors.json, the first wallet of ledgerTest).
STANDARD_REFERENCE_ADDRESS = "Xna4zn09aSvah-sWJ2h5NVE1CNzFyno0q_TqqEQA3ZM"


class Form:
    """A form of the scheme: section 6's label byte and the bits it forces on each starting point."""

    def __init__(self, name, label, forced, strict):
        self.name = name
        self.label = label
        self.forced = forced
        # Whether section 8 also refuses primes too close together and a short private exponent.
        self.strict = strict


STANDARD_V1 = Form("Permaweb Standard Seeds v1.0", 0x01, 3 << 2046, True)
LEGACY = Form("legacy", 0x00, 1 << 2047, False)

# The primes must differ by more than this, and the private exponent must exceed 2^2048 (section 8).
CLOSEST_PRIMES = 2**1948
SHORTEST_PRIVATE_EXPONENT = 2**2048

ABANDON_ART = " ".join(["abandon"] * 23 + ["art"])

# name: (phrase, passphrase, wallet numbers)
SETS = {
    "ledgerTest": (LEDGER_TEST_PHRASE, "", [0, 1, 2, HIGHEST_NUMBER]),
    "twelveWords": ("test test test test test test test test test test test junk", "", [0, 1, 2, 3, 20]),
    "fifteenWords": (" ".join(["abandon"] * 14 + ["address"]), "", [0]),
    "eighteenWords": (" ".join(["abandon"] * 17 + ["agent"]), "", [0]),
    "twentyOneWords": (" ".join(["abandon"] * 20 + ["admit"]), "", [0]),
    "twentyFourWords": (ABANDON_ART, "", list(range(10)) + [100, 1000, HIGHEST_NUMBER]),
    "passphrase": (ABANDON_ART, "TREZOR", [0, 1]),
    # find_cases.py found the phrases and numbers below: the first of its numbered test phrases, and
    # the first wallet numbers of the phrase above, with each property. The first two are the cases
    # in which other readings of "next prime" would give a different wallet.
    "evenStartBeforePrime": ("apple spend melt screen crumble off nephew timber deer ethics leopard pony", "", [0]),
    "primeStart": ("diary deputy aunt funny borrow usage skate swift hedgehog text modify autumn", "", [0]),
    # Wallet numbers with no key: the first prime of 76967 and the second prime of 180413 are 1
    # modulo the public exponent. They are the first number of each kind for this phrase.
    "invalidWallets": (ABANDON_ART, "", [76967, 180413]),
    # A phrase whose wallet 0 has no key.
    "invalidFirstWallet": ("pride reopen labor timber palm nest kangaroo near poet survey mind taste", "", [0]),
}

# The same sets in the legacy form, as they were published with it.
LEGACY_SETS = {
    "ledgerTest": (
        "equip will roof matter pink blind book anxiety banner elbow sun young",
        "",
        [0, 1, 2, HIGHEST_NUMBER],
    ),
    "twelveWords": ("test test test test test test test test test test test junk", "", [0, 1, 2, 3, 20]),
    "fifteenWords": (" ".join(["abandon"] * 14 + ["address"]), "", [0]),
    "eighteenWords": (" ".join(["abandon"] * 17 + ["agent"]), "", [0]),
    "twentyOneWords": (" ".join(["abandon"] * 20 + ["admit"]), "", [0]),
    "twentyFourWords": (
        " ".join(["abandon"] * 23 + ["art"]),
        "",
        list(range(10)) + [100, 1000, HIGHEST_NUMBER],
    ),
    "passphrase": (" ".join(["abandon"] * 23 + ["art"]), "TREZOR", [0, 1]),
    # docs/research/master-seed-wallets/ledger_emulator_check.py found these two phrases. They are
    # the cases in which other readings of "next prime" would give a different wallet.
    "evenStartBeforePrime": (
        "envelope zebra smooth glimpse skull slight joy fortune afraid clown buddy sphere",
        "",
        [0],
    ),
    "primeStart": (
        "rotate blue loyal volcano pause scatter deal extra believe beauty calm arrive",
        "",
        [0],
    ),
    # Wallet numbers with no key: the first prime of 18144 and the second prime of 93575 are
    # 1 modulo the public exponent. Found by testing every wallet number of this phrase up to 150000.
    "invalidWallets": (" ".join(["abandon"] * 23 + ["art"]), "", [18144, 93575]),
    # A phrase whose wallet 0 has no key. Its entropy is the first 16 bytes of
    # SHA-256("PermawebOS seed wallet test phrase 80861"), the first such counter found from 0.
    "invalidFirstWallet": (
        "lunch title sweet amazing air bright welcome liquid zone broccoli adapt claim",
        "",
        [0],
    ),
}

# Cases that section 9 of the specification requires the vectors to include, and an invalid wallet.
REQUIRED_CASES = {
    "highest wallet number",
    "even starting point",
    "even starting point followed by a prime",
    "odd starting point that is prime",
    "invalid wallet",
}
LEGACY_REQUIRED_CASES = REQUIRED_CASES | {"ledger published address", "4095-bit modulus"}


class InvalidWallet(Exception):
    pass


# The BIP-39 English word list: joined by newlines it is, byte for byte, the list of the BIP repository.
WORDS = """
abandon ability able about above absent absorb abstract absurd abuse access accident account
accuse achieve acid acoustic acquire across act action actor actress actual adapt add addict
address adjust admit adult advance advice aerobic affair afford afraid again age agent agree
ahead aim air airport aisle alarm album alcohol alert alien all alley allow almost alone alpha
already also alter always amateur amazing among amount amused analyst anchor ancient anger angle
angry animal ankle announce annual another answer antenna antique anxiety any apart apology
appear apple approve april arch arctic area arena argue arm armed armor army around arrange
arrest arrive arrow art artefact artist artwork ask aspect assault asset assist assume asthma
athlete atom attack attend attitude attract auction audit august aunt author auto autumn average
avocado avoid awake aware away awesome awful awkward axis baby bachelor bacon badge bag balance
balcony ball bamboo banana banner bar barely bargain barrel base basic basket battle beach bean
beauty because become beef before begin behave behind believe below belt bench benefit best
betray better between beyond bicycle bid bike bind biology bird birth bitter black blade blame
blanket blast bleak bless blind blood blossom blouse blue blur blush board boat body boil bomb
bone bonus book boost border boring borrow boss bottom bounce box boy bracket brain brand brass
brave bread breeze brick bridge brief bright bring brisk broccoli broken bronze broom brother
brown brush bubble buddy budget buffalo build bulb bulk bullet bundle bunker burden burger burst
bus business busy butter buyer buzz cabbage cabin cable cactus cage cake call calm camera camp
can canal cancel candy cannon canoe canvas canyon capable capital captain car carbon card cargo
carpet carry cart case cash casino castle casual cat catalog catch category cattle caught cause
caution cave ceiling celery cement census century cereal certain chair chalk champion change
chaos chapter charge chase chat cheap check cheese chef cherry chest chicken chief child chimney
choice choose chronic chuckle chunk churn cigar cinnamon circle citizen city civil claim clap
clarify claw clay clean clerk clever click client cliff climb clinic clip clock clog close cloth
cloud clown club clump cluster clutch coach coast coconut code coffee coil coin collect color
column combine come comfort comic common company concert conduct confirm congress connect
consider control convince cook cool copper copy coral core corn correct cost cotton couch
country couple course cousin cover coyote crack cradle craft cram crane crash crater crawl crazy
cream credit creek crew cricket crime crisp critic crop cross crouch crowd crucial cruel cruise
crumble crunch crush cry crystal cube culture cup cupboard curious current curtain curve cushion
custom cute cycle dad damage damp dance danger daring dash daughter dawn day deal debate debris
decade december decide decline decorate decrease deer defense define defy degree delay deliver
demand demise denial dentist deny depart depend deposit depth deputy derive describe desert
design desk despair destroy detail detect develop device devote diagram dial diamond diary dice
diesel diet differ digital dignity dilemma dinner dinosaur direct dirt disagree discover disease
dish dismiss disorder display distance divert divide divorce dizzy doctor document dog doll
dolphin domain donate donkey donor door dose double dove draft dragon drama drastic draw dream
dress drift drill drink drip drive drop drum dry duck dumb dune during dust dutch duty dwarf
dynamic eager eagle early earn earth easily east easy echo ecology economy edge edit educate
effort egg eight either elbow elder electric elegant element elephant elevator elite else embark
embody embrace emerge emotion employ empower empty enable enact end endless endorse enemy energy
enforce engage engine enhance enjoy enlist enough enrich enroll ensure enter entire entry
envelope episode equal equip era erase erode erosion error erupt escape essay essence estate
eternal ethics evidence evil evoke evolve exact example excess exchange excite exclude excuse
execute exercise exhaust exhibit exile exist exit exotic expand expect expire explain expose
express extend extra eye eyebrow fabric face faculty fade faint faith fall false fame family
famous fan fancy fantasy farm fashion fat fatal father fatigue fault favorite feature february
federal fee feed feel female fence festival fetch fever few fiber fiction field figure file film
filter final find fine finger finish fire firm first fiscal fish fit fitness fix flag flame
flash flat flavor flee flight flip float flock floor flower fluid flush fly foam focus fog foil
fold follow food foot force forest forget fork fortune forum forward fossil foster found fox
fragile frame frequent fresh friend fringe frog front frost frown frozen fruit fuel fun funny
furnace fury future gadget gain galaxy gallery game gap garage garbage garden garlic garment gas
gasp gate gather gauge gaze general genius genre gentle genuine gesture ghost giant gift giggle
ginger giraffe girl give glad glance glare glass glide glimpse globe gloom glory glove glow glue
goat goddess gold good goose gorilla gospel gossip govern gown grab grace grain grant grape
grass gravity great green grid grief grit grocery group grow grunt guard guess guide guilt
guitar gun gym habit hair half hammer hamster hand happy harbor hard harsh harvest hat have hawk
hazard head health heart heavy hedgehog height hello helmet help hen hero hidden high hill hint
hip hire history hobby hockey hold hole holiday hollow home honey hood hope horn horror horse
hospital host hotel hour hover hub huge human humble humor hundred hungry hunt hurdle hurry hurt
husband hybrid ice icon idea identify idle ignore ill illegal illness image imitate immense
immune impact impose improve impulse inch include income increase index indicate indoor industry
infant inflict inform inhale inherit initial inject injury inmate inner innocent input inquiry
insane insect inside inspire install intact interest into invest invite involve iron island
isolate issue item ivory jacket jaguar jar jazz jealous jeans jelly jewel job join joke journey
joy judge juice jump jungle junior junk just kangaroo keen keep ketchup key kick kid kidney kind
kingdom kiss kit kitchen kite kitten kiwi knee knife knock know lab label labor ladder lady lake
lamp language laptop large later latin laugh laundry lava law lawn lawsuit layer lazy leader
leaf learn leave lecture left leg legal legend leisure lemon lend length lens leopard lesson
letter level liar liberty library license life lift light like limb limit link lion liquid list
little live lizard load loan lobster local lock logic lonely long loop lottery loud lounge love
loyal lucky luggage lumber lunar lunch luxury lyrics machine mad magic magnet maid mail main
major make mammal man manage mandate mango mansion manual maple marble march margin marine
market marriage mask mass master match material math matrix matter maximum maze meadow mean
measure meat mechanic medal media melody melt member memory mention menu mercy merge merit merry
mesh message metal method middle midnight milk million mimic mind minimum minor minute miracle
mirror misery miss mistake mix mixed mixture mobile model modify mom moment monitor monkey
monster month moon moral more morning mosquito mother motion motor mountain mouse move movie
much muffin mule multiply muscle museum mushroom music must mutual myself mystery myth naive
name napkin narrow nasty nation nature near neck need negative neglect neither nephew nerve nest
net network neutral never news next nice night noble noise nominee noodle normal north nose
notable note nothing notice novel now nuclear number nurse nut oak obey object oblige obscure
observe obtain obvious occur ocean october odor off offer office often oil okay old olive
olympic omit once one onion online only open opera opinion oppose option orange orbit orchard
order ordinary organ orient original orphan ostrich other outdoor outer output outside oval oven
over own owner oxygen oyster ozone pact paddle page pair palace palm panda panel panic panther
paper parade parent park parrot party pass patch path patient patrol pattern pause pave payment
peace peanut pear peasant pelican pen penalty pencil people pepper perfect permit person pet
phone photo phrase physical piano picnic picture piece pig pigeon pill pilot pink pioneer pipe
pistol pitch pizza place planet plastic plate play please pledge pluck plug plunge poem poet
point polar pole police pond pony pool popular portion position possible post potato pottery
poverty powder power practice praise predict prefer prepare present pretty prevent price pride
primary print priority prison private prize problem process produce profit program project
promote proof property prosper protect proud provide public pudding pull pulp pulse pumpkin
punch pupil puppy purchase purity purpose purse push put puzzle pyramid quality quantum quarter
question quick quit quiz quote rabbit raccoon race rack radar radio rail rain raise rally ramp
ranch random range rapid rare rate rather raven raw razor ready real reason rebel rebuild recall
receive recipe record recycle reduce reflect reform refuse region regret regular reject relax
release relief rely remain remember remind remove render renew rent reopen repair repeat replace
report require rescue resemble resist resource response result retire retreat return reunion
reveal review reward rhythm rib ribbon rice rich ride ridge rifle right rigid ring riot ripple
risk ritual rival river road roast robot robust rocket romance roof rookie room rose rotate
rough round route royal rubber rude rug rule run runway rural sad saddle sadness safe sail salad
salmon salon salt salute same sample sand satisfy satoshi sauce sausage save say scale scan
scare scatter scene scheme school science scissors scorpion scout scrap screen script scrub sea
search season seat second secret section security seed seek segment select sell seminar senior
sense sentence series service session settle setup seven shadow shaft shallow share shed shell
sheriff shield shift shine ship shiver shock shoe shoot shop short shoulder shove shrimp shrug
shuffle shy sibling sick side siege sight sign silent silk silly silver similar simple since
sing siren sister situate six size skate sketch ski skill skin skirt skull slab slam sleep
slender slice slide slight slim slogan slot slow slush small smart smile smoke smooth snack
snake snap sniff snow soap soccer social sock soda soft solar soldier solid solution solve
someone song soon sorry sort soul sound soup source south space spare spatial spawn speak
special speed spell spend sphere spice spider spike spin spirit split spoil sponsor spoon sport
spot spray spread spring spy square squeeze squirrel stable stadium staff stage stairs stamp
stand start state stay steak steel stem step stereo stick still sting stock stomach stone stool
story stove strategy street strike strong struggle student stuff stumble style subject submit
subway success such sudden suffer sugar suggest suit summer sun sunny sunset super supply
supreme sure surface surge surprise surround survey suspect sustain swallow swamp swap swarm
swear sweet swift swim swing switch sword symbol symptom syrup system table tackle tag tail
talent talk tank tape target task taste tattoo taxi teach team tell ten tenant tennis tent term
test text thank that theme then theory there they thing this thought three thrive throw thumb
thunder ticket tide tiger tilt timber time tiny tip tired tissue title toast tobacco today
toddler toe together toilet token tomato tomorrow tone tongue tonight tool tooth top topic
topple torch tornado tortoise toss total tourist toward tower town toy track trade traffic
tragic train transfer trap trash travel tray treat tree trend trial tribe trick trigger trim
trip trophy trouble truck true truly trumpet trust truth try tube tuition tumble tuna tunnel
turkey turn turtle twelve twenty twice twin twist two type typical ugly umbrella unable unaware
uncle uncover under undo unfair unfold unhappy uniform unique unit universe unknown unlock until
unusual unveil update upgrade uphold upon upper upset urban urge usage use used useful useless
usual utility vacant vacuum vague valid valley valve van vanish vapor various vast vault vehicle
velvet vendor venture venue verb verify version very vessel veteran viable vibrant vicious
victory video view village vintage violin virtual virus visa visit visual vital vivid vocal
voice void volcano volume vote voyage wage wagon wait walk wall walnut want warfare warm warrior
wash wasp waste water wave way wealth weapon wear weasel weather web wedding weekend weird
welcome west wet whale what wheat wheel when where whip whisper wide width wife wild will win
window wine wing wink winner winter wire wisdom wise wish witness wolf woman wonder wood wool
word work world worry worth wrap wreck wrestle wrist write wrong yard year yellow you young
youth zebra zero zone zoo
""".split()
assert hashlib.sha256(("\n".join(WORDS) + "\n").encode()).hexdigest() == (
    "2f5eed53a4727b4bf8880d8f3f199efc90e58503646d9ff8eff3a2ed3b24dbda"
)


def valid_phrase(phrase):
    """Section 4.1: 12, 15, 18, 21 or 24 words of the list, with the checksum BIP-39 gives them."""
    words = phrase.split(" ")
    if len(words) not in (12, 15, 18, 21, 24) or any(word not in WORDS for word in words):
        return False
    bits = 0
    for word in words:
        bits = (bits << 11) | WORDS.index(word)
    # Every three words carry 32 bits of entropy and one bit of checksum.
    checksum_bits = len(words) // 3
    entropy = (bits >> checksum_bits).to_bytes(4 * checksum_bits, "big")
    return hashlib.sha256(entropy).digest()[0] >> (8 - checksum_bits) == bits & ((1 << checksum_bits) - 1)


def normalize(phrase):
    return " ".join(unicodedata.normalize("NFKD", phrase).lower().split())


def bip39_seed(phrase, passphrase):
    salt = unicodedata.normalize("NFKD", "mnemonic" + passphrase).encode()
    return hashlib.pbkdf2_hmac("sha512", normalize(phrase).encode(), salt, 2048)


def root_node(seed):
    key = b"ed25519 seed"
    chain = hmac.new(key, b"\x01" + seed, hashlib.sha256).digest()
    block = hmac.new(key, seed, hashlib.sha512).digest()
    while block[31] & 0x20:
        block = hmac.new(key, block, hashlib.sha512).digest()
    block = bytearray(block)
    block[0] &= 0xF8
    block[31] = (block[31] & 0x7F) | 0x40
    return bytes(block[:32]), bytes(block[32:]), chain


def hardened_child(k_left, k_right, chain, index):
    assert index >= HARDENED
    tail = k_left + k_right + index.to_bytes(4, "little")
    z = hmac.new(chain, b"\x00" + tail, hashlib.sha512).digest()
    left = (8 * int.from_bytes(z[:28], "little") + int.from_bytes(k_left, "little")) % 2**256
    right = (int.from_bytes(z[32:], "little") + int.from_bytes(k_right, "little")) % 2**256
    child_chain = hmac.new(chain, b"\x01" + tail, hashlib.sha512).digest()[32:]
    return left.to_bytes(32, "little"), right.to_bytes(32, "little"), child_chain


def wallet_secret(seed, number):
    assert 0 <= number <= HIGHEST_NUMBER
    node = root_node(seed)
    for index in (HARDENED + 44, HARDENED + 472, HARDENED + number, HARDENED, HARDENED):
        node = hardened_child(*node, index)
    return node[0]


def starting_point(secret, prime_index, form=STANDARD_V1):
    block = b"".join(
        hashlib.sha256(bytes([form.label, prime_index]) + secret + bytes([counter])).digest()
        for counter in range(8)
    )
    assert len(block) == 256
    return int.from_bytes(block, "big") | form.forced


def small_primes(limit):
    flags = bytearray([1]) * limit
    flags[0:2] = b"\x00\x00"
    for value in range(2, int(limit**0.5) + 1):
        if flags[value]:
            flags[value * value :: value] = bytearray(len(flags[value * value :: value]))
    return [value for value in range(limit) if flags[value]]


PRIMORIAL = math.prod(small_primes(2000))


def is_prime(candidate):
    """Miller-Rabin with base 2 and 24 bases drawn from a hash of the candidate."""
    if math.gcd(candidate, PRIMORIAL) != 1:
        return False
    odd, twos = candidate - 1, 0
    while odd % 2 == 0:
        odd //= 2
        twos += 1
    width = (candidate.bit_length() + 7) // 8
    bases = [2]
    for counter in range(24):
        digest = hashlib.shake_256(candidate.to_bytes(width, "big") + bytes([counter])).digest(width)
        bases.append(2 + int.from_bytes(digest, "big") % (candidate - 3))
    for base in bases:
        value = pow(base, odd, candidate)
        if value in (1, candidate - 1):
            continue
        for _ in range(twos - 1):
            value = value * value % candidate
            if value == candidate - 1:
                break
        else:
            return False
    return True


def next_prime(start):
    candidate = (start if start % 2 else start + 1) + 2
    while not is_prime(candidate):
        candidate += 2
    if candidate >= 2**2048:
        raise InvalidWallet("a prime search left the 2048-bit range")
    return candidate


def b64url(raw):
    return base64.urlsafe_b64encode(raw).rstrip(b"=").decode()


def b64url_int(value):
    return b64url(value.to_bytes((value.bit_length() + 7) // 8, "big"))


def keyfile(p, q, form=STANDARD_V1):
    if p == q:
        raise InvalidWallet("both prime searches found the same prime")
    if (p - 1) % E == 0 or (q - 1) % E == 0:
        raise InvalidWallet("a prime's predecessor shares a factor with the public exponent")
    if form.strict and abs(p - q) <= CLOSEST_PRIMES:
        raise InvalidWallet("the primes are too close together")
    n = p * q
    assert n.bit_length() == 4096 if form.strict else n.bit_length() in (4095, 4096)
    d = pow(E, -1, (p - 1) * (q - 1) // math.gcd(p - 1, q - 1))
    if form.strict and d <= SHORTEST_PRIVATE_EXPONENT:
        raise InvalidWallet("the private exponent is too short")
    return {
        "kty": "RSA",
        "n": b64url_int(n),
        "e": "AQAB",
        "d": b64url_int(d),
        "p": b64url_int(p),
        "q": b64url_int(q),
        "dp": b64url_int(d % (p - 1)),
        "dq": b64url_int(d % (q - 1)),
        "qi": b64url_int(pow(q, -1, p)),
    }


def vector(seed, number, form=STANDARD_V1):
    secret = wallet_secret(seed, number)
    starts = [starting_point(secret, prime_index, form) for prime_index in (0, 1)]
    cases = []
    if number == HIGHEST_NUMBER:
        cases.append("highest wallet number")
    if any(start % 2 == 0 for start in starts):
        cases.append("even starting point")
    if any(start % 2 == 0 and is_prime(start + 1) for start in starts):
        cases.append("even starting point followed by a prime")
    if any(start % 2 == 1 and is_prime(start) for start in starts):
        cases.append("odd starting point that is prime")
    entry = {
        "number": number,
        "walletSecret": secret.hex(),
        "startingPoints": [start.to_bytes(256, "big").hex() for start in starts],
    }
    try:
        key = keyfile(*(next_prime(start) for start in starts), form)
    except InvalidWallet as reason:
        return {**entry, "cases": cases + ["invalid wallet"], "invalid": str(reason)}
    modulus = int.from_bytes(base64.urlsafe_b64decode(key["n"] + "=" * (-len(key["n"]) % 4)), "big")
    owner = modulus.to_bytes(512, "big")
    if modulus.bit_length() == 4095:
        cases.append("4095-bit modulus")
    return {
        **entry,
        "cases": cases,
        "owner": b64url(owner),
        "address": b64url(hashlib.sha256(owner).digest()),
        # SHA-256 of the keyfile serialized as compact JSON with the fields in the order above.
        "keyfileSha256": hashlib.sha256(json.dumps(key, separators=(",", ":")).encode()).hexdigest(),
        "keyfile": key,
    }


def ledger_anchor():
    """Wallet 0 of the Ledger test phrase in the legacy form: the address a real device published."""
    wallet = vector(bip39_seed(LEDGER_TEST_PHRASE, ""), 0, LEGACY)
    if wallet["address"] != LEDGER_PUBLISHED_ADDRESS:
        sys.exit(f"wallet 0 of the Ledger test phrase is {wallet['address']}, not {LEDGER_PUBLISHED_ADDRESS}")


def derive_keyfile(number, form):
    """One wallet of the phrase on standard input, as the keyfile's JSON text."""
    # Lines end at a line feed, with or without a carriage return before it, and nowhere else.
    lines = [line.rstrip("\r") for line in sys.stdin.read().split("\n")]
    phrase = normalize(lines[0])
    if not valid_phrase(phrase):
        sys.exit("the first line of standard input is not a valid seed phrase: check each word and their order")
    if not 0 <= number <= HIGHEST_NUMBER:
        sys.exit("the wallet number is from 0 to 2^31 - 1")
    secret = wallet_secret(bip39_seed(phrase, lines[1] if len(lines) > 1 else ""), number)
    try:
        key = keyfile(*(next_prime(starting_point(secret, index, form)) for index in (0, 1)), form)
    except InvalidWallet as reason:
        sys.exit(f"wallet number {number} has no key: {reason}")
    sys.stdout.write(json.dumps(key, separators=(",", ":")) + "\n")


def main():
    legacy = "--legacy" in sys.argv[1:]
    form = LEGACY if legacy else STANDARD_V1
    if "--keyfile" in sys.argv[1:]:
        # Sections 4, 5, 7 and 8 must give the device's answer, and section 6 of the new form its
        # published wallet, before this script is trusted with a phrase.
        ledger_anchor()
        standard = vector(bip39_seed(LEDGER_TEST_PHRASE, ""), 0, STANDARD_V1)
        if standard["address"] != STANDARD_REFERENCE_ADDRESS:
            sys.exit(f"the built-in wallet of the new form is {standard['address']}, not {STANDARD_REFERENCE_ADDRESS}")
        derive_keyfile(int(sys.argv[sys.argv.index("--keyfile") + 1]), form)
        return
    # Sections 4, 5, 7 and 8 are the same code in both forms: they must give the device's answer first.
    ledger_anchor()
    print("the legacy form reproduces the Ledger's published address", file=sys.stderr, flush=True)

    output = {}
    for name, (phrase, passphrase, numbers) in (LEGACY_SETS if legacy else SETS).items():
        assert valid_phrase(normalize(phrase)), name
        seed = bip39_seed(phrase, passphrase)
        wallets = []
        for number in numbers:
            wallets.append(vector(seed, number, form))
            cases = ", ".join(wallets[-1]["cases"]) or "no special case"
            print(f"{name} {number}: {cases}", file=sys.stderr, flush=True)
        output[name] = {"seedPhrase": phrase, "passphrase": passphrase, "wallets": wallets}

    if legacy:
        output["ledgerTest"]["wallets"][0]["cases"].insert(0, "ledger published address")
    required = LEGACY_REQUIRED_CASES if legacy else REQUIRED_CASES
    covered = {case for entry in output.values() for wallet in entry["wallets"] for case in wallet["cases"]}
    if required - covered:
        sys.exit(f"no vector covers: {', '.join(sorted(required - covered))}")
    if not legacy:
        clashes = [wallet["invalid"] for wallet in output["invalidWallets"]["wallets"]]
        assert len(clashes) == 2 and all("public exponent" in reason for reason in clashes), clashes

    json.dump(output, sys.stdout, indent="\t")
    sys.stdout.write("\n")


if __name__ == "__main__":
    main()
