bitpay / bitcore

A full stack for bitcoin and blockchain-based applications
https://bitcore.io/
MIT License
4.88k stars 2.09k forks source link

networks remove() issue #2400

Open randydu opened 5 years ago

randydu commented 5 years ago

src:

bitcore-lib/lib/networks.js

issue

uses function remove() to delete existing network ("testnet" for example), then add a new custom network with the same name ("testnet"), expecting the function get("testnet") will return the added custom network object, but actually we get a undefined object.

const lib = require('bitcore-lib');
const Networks = lib.Networks;

const my_testnet = {
    name: 'testnet',
    alias: 'regtest',
    pubkeyhash: 0x42,
    privatekey: 0xc2,
    scripthash: 0x7f,
    xpubkey: 0x043587cf,
    xprivkey: 0x04358394
  }

Networks.remove(Networks.testnet);
Networks.add(my_testnet);

Networks.get("testnet");// => undefined

root cause


function removeNetwork(network) {
  ...
  for (var key in networkMaps) {
    const index = networkMaps[key].indexOf(network);
    if (index >= 0) {
      delete networkMaps[key][index]; // it leaves an _undefined_ object in the array instead of removing it!
    }
  }
}

function get(arg, keys) {
 ...
  if(networkMaps[arg] && networkMaps[arg].length >= 1) {
    return networkMaps[arg][0]; // it returns the _undefined_ object without checking if it is a valid network.
  } else {
    return networkMaps[arg];
  }
}

bug fix

function removeNetwork(network) {
  ...
  for (var key in networkMaps) {
    const index = networkMaps[key].indexOf(network);
    if (index >= 0) {
      networkMaps[key].splice(index, 1); //remove it physically.
    }
  }
}
randydu commented 5 years ago

This bug occurs after bitcore-lib is upgraded from v0.16.0 to v8.7.1, it used to work properly.

r4mmer commented 3 years ago

This issue is still happening, i was going to create a PR but @randydu bug fix is perfect. Can i open this PR?