Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow registering new networks #287

Open
wants to merge 4 commits into
base: old-dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 77 additions & 1 deletion __tests__/models/network.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,80 @@ test('Get and set network', () => {
// Invalid network
const network2 = new Network('abc');
}).toThrowError();
})
});

test("register new network successfully", () => {
Network.registerNetwork({
name: 'jestnet',
alias: 'jestnet',
pubkeyhash: 0x70,
privatekey: 0x80,
scripthash: 0x93,
bech32prefix: 'tn',
xpubkey: 0x0488b21e,
xprivkey: 0x0434c8c4,
networkMagic: 0xf9beb4d9,
port: 8333,
dnsSeeds: []
});

// This shouldn't throw error
const network = new Network('jestnet');

expect(network.getVersionBytes()).toEqual({
'p2pkh': 0x70,
'p2sh': 0x93,
'xpub': 0x0488b21e,
'xpriv': 0x0434c8c4
})
});

const getNetworkConfig = (override) => {
return Object.assign({
name: 'jestnet',
alias: 'jestnet',
pubkeyhash: 0x70,
privatekey: 0x80,
scripthash: 0x93,
bech32prefix: 'tn',
xpubkey: 0x0488b21e,
xprivkey: 0x0434c8c4,
networkMagic: 0xf9beb4d9,
port: 8333,
dnsSeeds: []
}, override);
}

test("register invalid network config", () => {
Object.entries({
'name': undefined,
'alias': undefined,
'pubkeyhash': undefined,
'pubkeyhash': 'abc',
'pubkeyhash': 0x111,
'privatekey': undefined,
'privatekey': 'abc',
'privatekey': 0x111,
'scripthash': undefined,
'bech32prefix': undefined,
'xpubkey': undefined,
'xpubkey': 'abc',
'xprivkey': undefined,
'xprivkey': 'abc',
'networkMagic': undefined,
'networkMagic': 'abc',
'port': undefined,
'port': 'abc',
'dnsSeeds': undefined,
'dnsSeeds': 'abc',
'dnsSeeds': 123
}).forEach(([key, value]) => {
expect(() => {
Network.registerNetwork(
getNetworkConfig({
[key]: value,
})
);
}).toThrowError(`Validation errors in network definition: Error: ${key} is invalid.`)
})
});
98 changes: 93 additions & 5 deletions src/models/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,12 @@ const versionBytes = {
'xpriv': 0x0434c8c4, // tnpr
'xpub': 0x0488b21e, // xpub // 0x0434c85b -> tnpb
},
'privatenet': {
'p2pkh': 0x49,
'p2sh': 0x87,
'xpriv': 0x0434c8c4, // tnpr
'xpub': 0x0488b21e, // xpub // 0x0434c85b -> tnpb
},
}

/*Networks is an object of the bitcore-lib
Expand Down Expand Up @@ -86,16 +92,67 @@ const testnet = Networks.add({
dnsSeeds: []
});

const privatenet = Networks.add({
name: 'htr-privatenet',
alias: 'privatenet',
pubkeyhash: versionBytes['privatenet']['p2pkh'],
privatekey: 0x80,
scripthash: versionBytes['privatenet']['p2sh'],
bech32prefix: 'tn',
xpubkey: versionBytes['privatenet']['xpub'],
xprivkey: versionBytes['privatenet']['xpriv'],
networkMagic: 0xf9beb4d9,
port: 8333,
dnsSeeds: []
})

const networkOptions = {
testnet,
mainnet
mainnet,
privatenet
}

type versionBytesType = {
p2pkh: number,
p2sh: number,
}

// TODO I'm not sure if those are the best rules
const networkSchema = {
name: value => typeof value === 'string' && /^([a-z\-])+$/.test(value), // Only lower-case and dashes allowed
alias: value => typeof value === 'string' && /^([a-z\-])+$/.test(value), // Only lower-case and dashes allowed
pubkeyhash: value => typeof value === 'number' && value < 0x100,
privatekey: value => typeof value === 'number' && value < 0x100,
scripthash: value => typeof value === 'number' && value < 0x100,
bech32prefix: value => typeof value === 'string',
xpubkey: value => typeof value === 'number', // TODO How to validate valid xpubkey?
xprivkey: value => typeof value === 'number', // TODO How to validate valid xprivkey?,
networkMagic: value => typeof value === 'number', // TODO How to validate this?,
port: value => typeof value === 'number',
dnsSeeds: value => Array.isArray(value)
};

type networkConfigType = {
name: string,
alias: string,
pubkeyhash: number,
privatekey: number,
scripthash: number,
bech32prefix: string,
xpubkey: number,
xprivkey: number,
networkMagic: number,
port: number,
dnsSeeds: string[]
}

function validateNetworkConfig(networkConfig: networkConfigType) {
return Object
.keys(networkSchema)
.filter(key => !networkSchema[key](networkConfig[key]))
.map(key => new Error(`${key} is invalid.`));
}


class Network {
// Network name (currently supports only 'testnet' and 'mainnet')
Expand All @@ -105,7 +162,7 @@ class Network {
versionBytes: versionBytesType;

// bitcore-lib Networks object with all network options
bitcoreNetwork: Networks;
bitcoreNetwork: Networks.Network;

constructor(name: string) {
this.name = name;
Expand All @@ -114,19 +171,50 @@ class Network {
this.bitcoreNetwork = networkOptions[name];
}

/**
* Registers a new network configuration.
*
* We validate the configuration before registering.
*/
static registerNetwork(networkConfig: networkConfigType) {
const errors = validateNetworkConfig(networkConfig);

if (errors.length > 0) {
throw new Error(`Validation errors in network definition: ${errors}`);
}

const name: string = networkConfig['name'];

if (name in Object.keys(networkOptions)) {
throw new Error(`The network name ${name} is a reserved name.`);
} else if (name.startsWith('htr')) {
throw new Error(`You can't use the prefix 'htr' in network names`);
}

networkOptions[name] = Networks.add(networkConfig);
versionBytes[name] = {
'p2pkh': networkConfig['pubkeyhash'],
'p2sh': networkConfig['scripthash'],
'xpriv': networkConfig['xprivkey'],
'xpub': networkConfig['xpubkey']
}
}

/**
* Validate the network name is valid
*/
validateNetwork() {
if (this.name !== 'testnet' && this.name !== 'mainnet') {
throw Error('We currently support only mainnet and testnet as network.');
const possibleNetworks = Object.keys(networkOptions);

if (possibleNetworks.indexOf(this.name) < 0) {
throw new Error(`We currently support only [${possibleNetworks}] as network.`);
}
}

/**
* Method created to keep compatibility with old Network class
*/
getNetwork(): Networks {
getNetwork(): Networks.Network {
return this.bitcoreNetwork;
}

Expand Down