Browse Source

Validate prefix charset

master
Luke Childs 6 years ago
parent
commit
143f7743dd
  1. 6
      src/charsets.js
  2. 7
      src/index.js
  3. 4
      src/p2pkh.js
  4. 4
      src/p2wpkh-p2sh.js
  5. 4
      src/p2wpkh.js
  6. 22
      test/unit.js

6
src/charsets.js

@ -0,0 +1,6 @@
const charsets = {
base58: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz',
bech32: 'qpzry9x8gf2tvdw0s3jn54khce6mua7l'
};
module.exports = charsets;

7
src/index.js

@ -12,6 +12,13 @@ class Vain extends Emitter {
constructor({addressFormat = 'p2pkh', prefix}) {
super();
this.addressFormat = addressFormats.get(addressFormat);
prefix.split('').forEach(char => {
if (!this.addressFormat.charset.includes(char)) {
throw new Error(`Invalid characters for address format "${addressFormat}"`);
}
});
this.prefix = `${this.addressFormat.prefix}${prefix}`;
}

4
src/p2pkh.js

@ -1,7 +1,9 @@
const bitcoin = require('bitcoinjs-lib');
const {base58} = require('./charsets');
const p2pkh = {
prefix: '1'
prefix: '1',
charset: base58
};
p2pkh.derive = () => {

4
src/p2wpkh-p2sh.js

@ -1,7 +1,9 @@
const bitcoin = require('bitcoinjs-lib');
const {base58} = require('./charsets');
const p2wpkhp2sh = {
prefix: '3'
prefix: '3',
charset: base58
};
p2wpkhp2sh.derive = () => {

4
src/p2wpkh.js

@ -1,7 +1,9 @@
const bitcoin = require('bitcoinjs-lib');
const {bech32} = require('./charsets');
const p2wpkh = {
prefix: 'bc1q'
prefix: 'bc1q',
charset: bech32
};
p2wpkh.derive = () => {

22
test/unit.js

@ -66,3 +66,25 @@ test('Vain defaults to p2pkh if no address format is set', async t => {
t.true(address.startsWith(`1${options.prefix}`));
t.is(address, wifAddress);
});
test('Vain throws on invalid charset', t => {
const optionsArray = [
{
addressFormat: 'p2pkh',
prefix: '0'
},
{
addressFormat: 'p2wpkh-p2sh',
prefix: '0'
},
{
addressFormat: 'p2wpkh',
prefix: '1'
}
];
optionsArray.forEach(options => {
const error = t.throws(() => new Vain(options));
t.true(error.message.includes('Invalid characters for address format'));
});
});

Loading…
Cancel
Save