Since Keypair.generate()
doesn't even exist anymore, and the class itself has been moved into solders.py, here's an up-to-date(solana.py v0.32, solders v0.20) solution:
I tried all of this and a lot more, and noticed that Keypair.secret()
doesn't look right. Because I assumed Keypair.secret()
is the key. But it's only 32 bytes, and the key is 64 bytes.
As seen in the auto-tests here, solders.keypair.Keypair
can actually be type-cast to bytes: bytes(Keypair())
https://github.com/kevinheavey/solders/blob/16656d9e508c5ed9bd237fd94a1c7bfa45eef9be/tests/test_keypair.py#L26
Doing so gives you the full 64 bytes of the private key.
# typecast whole Keypair object, not just Keypair.secret(). Very obvious, I know.
rawPK = bytes(solders.keypair.Keypair())
pk = base58.b58encode(rawPK).decode()
To then restore a keypair from this private key:
keypair = solders.keypair.Keypair.from_base58_string(pk)
Here's a complete example of how to export and import back a keypair:
import base58
import solders
keypair = solders.keypair.Keypair() # generates new keypair
generatedAddr = keypair.pubkey()
rawPK = bytes(keypair)
pk = base58.b58encode(rawPK).decode()
restoredKeypair = solders.keypair.Keypair.from_base58_string(pk)
restoredAddr = restoredKeypair.pubkey()
restoredCorrectly = (restoredAddr == generatedAddr)
print(restoredCorrectly)
@Henry Tirla also already faced the same issue and got the right idea in his answer, but of course this is Solana SO, so I have 0 rep here and can't do anything. Awesome idea to add so much separation to blockchain sub-Stacks.