'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var fromString = require('uint8arrays/from-string');
var cid = require('multiformats/cid');
var sha2 = require('multiformats/hashes/sha2');
var delay = require('delay');

function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }

var delay__default = /*#__PURE__*/_interopDefaultLegacy(delay);

async function fakeCid(data) {
  const bytes = data || fromString.fromString(`TEST${ Math.random() }`);
  const mh = await sha2.sha256.digest(bytes);
  return cid.CID.createV0(mh);
}
async function ensureReachable(nodeA, nodeB) {
  async function canFindOnDHT(source, target) {
    const {id} = await target.id();
    for await (const event of source.dht.query(id)) {
      if (event.name === 'PEER_RESPONSE' && event.from === id) {
        return;
      }
    }
    throw new Error(`Could not find ${ id } in DHT`);
  }
  const nodeBId = await nodeB.id();
  await nodeA.swarm.connect(nodeBId.addresses[0]);
  while (true) {
    try {
      await Promise.all([
        canFindOnDHT(nodeA, nodeB),
        canFindOnDHT(nodeB, nodeA)
      ]);
      break;
    } catch {
      await delay__default["default"](1000);
    }
  }
}

exports.ensureReachable = ensureReachable;
exports.fakeCid = fakeCid;
