getWifForAddress.ts 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /* Import modules. */
  2. import BCHJS from '@psf/bch-js'
  3. import { mnemonicToSeed } from '@nexajs/hdnode'
  4. /* Initialize BCHJS. */
  5. const bchjs = new BCHJS()
  6. /* Initialize constants. */
  7. const HUSH_PROTOCOL_ID = 0x48555348
  8. /**
  9. * Get WIF For An Address
  10. *
  11. * Will return the wallet import format (WIF) for a specific address.
  12. */
  13. export default function (_address) {
  14. /* Initialize locals. */
  15. let accountIdx
  16. let addressIdx
  17. let changeIdx
  18. let childNode
  19. let mainAddress
  20. let wif
  21. /* Set main (wallet) address. */
  22. mainAddress = this.getBchAddress(0, 0, 0)
  23. if (mainAddress === _address) {
  24. /* Set account index. */
  25. accountIdx = 0 // NOTE: This is the Main chain
  26. /* Set address index. */
  27. addressIdx = 0
  28. } else {
  29. /* Set account index. */
  30. accountIdx = HUSH_PROTOCOL_ID // NOTE: This is the Hush chain
  31. /* Handle fusion addresses. */
  32. Object.keys(this.fusionAddrs).forEach(_addressIdx => {
  33. /* Set fusion address. */
  34. const fusionAddress = this.fusionAddrs[_addressIdx]
  35. /* Validate address. */
  36. if (_address === fusionAddress.address) {
  37. /* Set address index. */
  38. addressIdx = _addressIdx
  39. }
  40. })
  41. }
  42. // console.log('ACCOUNT IDX', accountIdx)
  43. // console.log('ADDRESS IDX', addressIdx)
  44. if (typeof addressIdx === 'undefined' || addressIdx === null) {
  45. throw new Error(`Oops! There is NO private key for [ ${_address} ]`)
  46. }
  47. /* Set change index. */
  48. changeIdx = 0
  49. /* Convert mnemonic to seed. */
  50. const seed = mnemonicToSeed(this.mnemonic)
  51. /* Conver to seed buffer. */
  52. // FIXME Migrate to TypedArrays.
  53. const seedBuffer = Buffer.from(seed, 'hex')
  54. /* Generate master node. */
  55. const masterNode = bchjs.HDNode.fromSeed(seedBuffer)
  56. /* Generate child node. */
  57. childNode = masterNode
  58. .derivePath(`m/44'/145'/${accountIdx}'/${changeIdx}/${addressIdx}`)
  59. /* Generate wallet import format (WIF). */
  60. wif = bchjs.HDNode.toWIF(childNode)
  61. // console.log('BCH WIF', i, wif)
  62. /* Return WIF. */
  63. return wif
  64. }