makesim.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  14. */
  15. var Fs = require('fs');
  16. var LINKEYNESS = 0.001;
  17. var makeNodes = function (keys) {
  18. var out = {};
  19. var ips = [];
  20. for (var i = 0; i < keys.length; i++) {
  21. var kip = keys[i].split(' ');
  22. ips.push(kip[1]);
  23. out[kip[1]] = {
  24. privateKey: kip[0],
  25. peers: []
  26. };
  27. }
  28. var links = 0;
  29. var linkedNodes = [1];
  30. while (linkedNodes.length < keys.length) {
  31. var linked = ((Math.random() * 1e9) | 0) % Object.keys(linkedNodes).length;
  32. var unlinked = ((Math.random() * 1e9) | 0) % keys.length;
  33. links++;
  34. if (linkedNodes.indexOf(unlinked) === -1) {
  35. linkedNodes.push(unlinked);
  36. } else if (Math.random() > LINKEYNESS) {
  37. continue;
  38. }
  39. if (Math.random() > 0.5) {
  40. var x = linked;
  41. linked = unlinked;
  42. unlinked = x;
  43. }
  44. out[ips[unlinked]].peers.push(ips[linked]);
  45. }
  46. console.log(JSON.stringify({nodes: out}, null, ' '));
  47. };
  48. if (process.argv[process.argv.length-1].split('/').pop() === __filename.split('/').pop()) {
  49. console.log("usage: " + process.argv[process.argv.length-1] + ' keys.txt');
  50. console.log("See makekeys.c to see how to generate keys.txt");
  51. return;
  52. }
  53. Fs.readFile(process.argv[process.argv.length-1], function (err, ret) {
  54. if (err) { throw err; }
  55. var keys = ret.toString('utf8').split('\n');
  56. for (var i = keys.length-1; i >= 0; i--) {
  57. if (!(/^[a-f0-9]{64} [a-f0-9:]{39}.*$/.test(keys[i]))) {
  58. keys.splice(i, 1);
  59. }
  60. }
  61. makeNodes(keys);
  62. });