/packages/hw-app-btc/src/getWalletPublicKey.ts

https://github.com/LedgerHQ/ledger-node-js-api · TypeScript · 62 lines · 56 code · 3 blank · 3 comment · 8 complexity · 7363d57d7af9ddfa11900008d64e8af5 MD5 · raw file

  1. import type Transport from "@ledgerhq/hw-transport";
  2. import { bip32asBuffer } from "./bip32";
  3. /**
  4. * address format is one of legacy | p2sh | bech32 | cashaddr
  5. */
  6. export type AddressFormat =
  7. | "legacy"
  8. | "p2sh"
  9. | "bech32"
  10. | "bech32m"
  11. | "cashaddr";
  12. const addressFormatMap = {
  13. legacy: 0,
  14. p2sh: 1,
  15. bech32: 2,
  16. cashaddr: 3,
  17. };
  18. export async function getWalletPublicKey(
  19. transport: Transport,
  20. options: {
  21. path: string;
  22. verify?: boolean;
  23. format?: AddressFormat;
  24. }
  25. ): Promise<{
  26. publicKey: string;
  27. bitcoinAddress: string;
  28. chainCode: string;
  29. }> {
  30. const { path, verify, format } = {
  31. verify: false,
  32. format: "legacy",
  33. ...options,
  34. };
  35. if (!(format in addressFormatMap)) {
  36. throw new Error("btc.getWalletPublicKey invalid format=" + format);
  37. }
  38. const buffer = bip32asBuffer(path);
  39. const p1 = verify ? 1 : 0;
  40. const p2 = addressFormatMap[format];
  41. const response = await transport.send(0xe0, 0x40, p1, p2, buffer);
  42. const publicKeyLength = response[0];
  43. const addressLength = response[1 + publicKeyLength];
  44. const publicKey = response.slice(1, 1 + publicKeyLength).toString("hex");
  45. const bitcoinAddress = response
  46. .slice(1 + publicKeyLength + 1, 1 + publicKeyLength + 1 + addressLength)
  47. .toString("ascii");
  48. const chainCode = response
  49. .slice(
  50. 1 + publicKeyLength + 1 + addressLength,
  51. 1 + publicKeyLength + 1 + addressLength + 32
  52. )
  53. .toString("hex");
  54. return {
  55. publicKey,
  56. bitcoinAddress,
  57. chainCode,
  58. };
  59. }