I will not repeat the mental model of how keys, addresses, and balances work on Bitcoin, let's assume you're familiar with this: https://bitcoin.stackexchange.com/a/115830/137501
One more thing to note about:
I still don't have the full answer, and the following is only for BTC (I'd prefer an answer that works across many blockchains)
The answer you get for Bitcoin can only apply to other Bitcoin-tech blockchains (like Litecoin, Bitcoin Cash, etc.). Other blockchains like Ethereum use totally different schemes, which I'm not familiar with at all.
Ok, so you know that in order to find your UTXOs you need to find some good libraries that implement these 3 BIPs:
Also, SatoshiLabs (Trezor wallet manufacturer) maintains a list of derivation paths for many blockchains:
On a higher level, you have to:
- Generate the master key from mnemonic
- Generate the master xpub. Note that generating the master key and the xpub should be done on an offline device, and then copied over to the online device to preserve security of "air-gapping". Maybe the Ledger device can export just the xpub? If that's possible then you can skip the risky business of doing it yourself.
- Use the derivation path to produce a list of some
- Scan the UTXO set against those addresses and tally the balance
- If you want the wallet history and not just the current balance, you need to scan the entire blockchain against the list of addresses
Note that wallets make a new address each time you receive payment, so the list will grow.
When you're restoring a wallet from seed they don't know the
N, so what they do is they scan for some number of addresses, like 100, and then find the last address that was actually used, and then scan for 100 more from that one, until they get to the 100 which was never used.
So, how to do the scanning in steps 4. and 5.?
I'm not fully familiar with that but I can tell you where to look:
- If you're running your own node, find the node's RPC documentation, and see if you can get most of the job done using the node's RPC
- Use Electrum APIs to get what you need, either from a public server of from running your own Electrum server alongside your node.
- Use Ledger APIs and talk to their servers the same way their wallet talks to them, but I'm not sure how well this is documented.
With 2., there are plenty of public servers you could query, and the data can be verified in a trustless manner, all you need are block headers.
However, the server may store your queries and IPs so there's a privacy loss trade-off.
If you don't want to use a server, you can run an Electrum server by yourself alongside your node, and the server will produce indexes from the blockchain data so an address history can be easily looked up.