Skip to content

Commit

Permalink
test each address type with a dedicated regex
Browse files Browse the repository at this point in the history
  • Loading branch information
madoke committed May 27, 2024
1 parent 291d7d8 commit d87cb1c
Showing 1 changed file with 14 additions and 11 deletions.
25 changes: 14 additions & 11 deletions test/modules/finance.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,10 +325,15 @@ describe('finance', () => {

describe('bitcoinAddress()', () => {
// Utility for validating Bitcoin addresses (validator lib doesn't support taproot and testnets yet)
const bech32 = /^(bc1|tb1|bc1p|tb1p)[ac-hj-np-z02-9]{39,58}$/;
const base58 = /^(1|2|3|m)[A-HJ-NP-Za-km-z1-9]{25,39}$/;
const taproot = /^(bc1p|tb1p)[ac-hj-np-z02-9]{58,58}$/;
const bech32 = /^(bc1|tb1)[ac-hj-np-z02-9]{39,39}$/;
const segwit = /^(2|3)[A-HJ-NP-Za-km-z1-9]{25,39}$/;
const legacy = /^(1|m)[A-HJ-NP-Za-km-z1-9]{25,39}$/;
const isBtcAddress = (address: string) =>
bech32.test(address) || base58.test(address);
bech32.test(address) ||
taproot.test(address) ||
segwit.test(address) ||
legacy.test(address);

it('should return a valid bitcoin address', () => {
const bitcoinAddress = faker.finance.bitcoinAddress();
Expand All @@ -339,23 +344,21 @@ describe('finance', () => {
});

it.each([
[BitcoinAddressType.Legacy, '1'],
[BitcoinAddressType.Segwit, '3'],
[BitcoinAddressType.Bech32, 'bc1'],
[BitcoinAddressType.Taproot, 'bc1p'],
[BitcoinAddressType.Legacy, legacy],
[BitcoinAddressType.Segwit, segwit],
[BitcoinAddressType.Bech32, bech32],
[BitcoinAddressType.Taproot, taproot],
])(
'should handle the type = $type argument',
(type: BitcoinAddressType, expectedPrefix: string) => {
(type: BitcoinAddressType, regex: RegExp) => {
const bitcoinAddress = faker.finance.bitcoinAddress({
type,
});

expect(bitcoinAddress).toBeTruthy();
expect(bitcoinAddress).toBeTypeOf('string');
expect(bitcoinAddress).toSatisfy(isBtcAddress);
expect(bitcoinAddress).toSatisfy((v: string) =>
v.startsWith(expectedPrefix)
);
expect(bitcoinAddress).toSatisfy((v: string) => regex.test(v));
}
);

Expand Down

0 comments on commit d87cb1c

Please sign in to comment.