Skip to content
This repository has been archived by the owner on Aug 7, 2019. It is now read-only.

Commit

Permalink
Merge pull request #12 from keepkey/issue-#4/utility-for-bip32-to-add…
Browse files Browse the repository at this point in the history
…ressn

Utility for converting bip32 to addressN closes #4
  • Loading branch information
spiceboi authored Jan 21, 2019
2 parents a182ad3 + a06e43c commit 28ffddb
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
21 changes: 21 additions & 0 deletions src/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,4 +54,25 @@ describe('utils', () => {
expect(utils.fromHexString('!')).toEqual(new Uint8Array([0]))
})
})

describe('bip32ToAddressNList', () => {
test('formats return value correctly', () => {
expect(utils.bip32ToAddressNList(`m/44'/60'/0'/0/0`)).toEqual([ -2147483604, -2147483588, -2147483648, 0, 0 ])
})
test('will always return an array if the path looks valid', () => {
expect(utils.bip32ToAddressNList(`m/`)).toEqual([])
})
test('throws when given an incorrect bip32 path', () => {
expect(() => utils.bip32ToAddressNList(`/44'/60'/0'/0/0`)).toThrow()
})
})

describe('bip32Like', () => {
test('returns true if path is valid', () => {
expect(utils.bip32Like(`m/`)).toEqual(true)
})
test('returns false otherwise', () => {
expect(utils.bip32Like(`/44'/60'/0'/0/0`)).toEqual(false)
})
})
})
15 changes: 15 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,18 @@ export function arrayify (value: string): Uint8Array {
return new Uint8Array(result)
}
}

const harden = 0x80000000
export function bip32ToAddressNList (address: string): number[] {
if (!bip32Like(address)) throw new Error('Unrecognized bip32 path')
address = address.slice(1, address.length)
return address.split('/').filter(part => part.length).map(part => {
const insertHarden = part.indexOf(`'`) > -1
const num = parseFloat(part)
return insertHarden ? harden | num : num
})
}

export function bip32Like (address: string): boolean {
return address.slice(0, 2) === 'm/'
}

0 comments on commit 28ffddb

Please sign in to comment.