'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.runStorageTests = runStorageTests;

var _tape = require('tape');

var _tape2 = _interopRequireDefault(_tape);

var _fetchMock = require('fetch-mock');

var _fetchMock2 = _interopRequireDefault(_fetchMock);

var _bitcoinjsLib = require('bitcoinjs-lib');

var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib);

var _hub = require('../../../lib/storage/hub');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function runStorageTests() {

  (0, _tape2.default)('uploadToGaiaHub', function (t) {
    t.plan(2);

    var config = { address: '19MoWG8u88L6t766j7Vne21Mg4wHsCQ7vk',
      url_prefix: 'gaia.testblockstack.org',
      token: '',
      server: 'hub.testblockstack.org' };

    _fetchMock2.default.post(config.server + '/store/' + config.address + '/foo.json', JSON.stringify({ publicURL: '${config.url_prefix}/${config.address}/foo.json' }));

    (0, _hub.uploadToGaiaHub)('foo.json', 'foo the bar', config).then(function (url) {
      t.ok(url, 'URL returned');
      t.equal(url, '${config.url_prefix}/${config.address}/foo.json');
    });
  });

  (0, _tape2.default)('getFullReadUrl', function (t) {
    t.plan(1);

    var config = { address: '19MoWG8u88L6t766j7Vne21Mg4wHsCQ7vk',
      url_prefix: 'gaia.testblockstack.org',
      token: '',
      server: 'hub.testblockstack.org' };

    var outUrl = (0, _hub.getFullReadUrl)('foo.json', config);
    t.equal('' + config.url_prefix + config.address + '/foo.json', outUrl);
  });

  (0, _tape2.default)('connectToGaiaHub', function (t) {
    t.plan(5);

    var hubServer = 'hub.testblockstack.org';

    var hubInfo = {
      read_url_prefix: 'gaia.testblockstack.org',
      challenge_text: 'please-sign'
    };

    var privateKey = 'a5c61c6ca7b3e7e55edee68566aeab22e4da26baa285c7bd10e8d2218aa3b229';
    var address = '1NZNxhoxobqwsNvTb16pdeiqvFvce3Yg8U';
    var publicKey = '027d28f9951ce46538951e3697c62588a87f1f1f295de4a14fdd4c780fc52cfe69';

    _fetchMock2.default.get(hubServer + '/hub_info', JSON.stringify(hubInfo));

    (0, _hub.connectToGaiaHub)(hubServer, privateKey).then(function (config) {
      t.ok(config, 'Config returned by connectToGaiaHub()');
      t.equal(hubInfo.read_url_prefix, config.url_prefix);
      t.equal(address, config.address);
      t.equal(hubServer, config.server);

      var verificationKey = _bitcoinjsLib2.default.ECPair.fromPublicKeyBuffer(Buffer.from(publicKey, 'hex'));

      var decoded = JSON.parse(Buffer.from(config.token, 'base64').toString());
      var signature = _bitcoinjsLib2.default.ECSignature.fromDER(Buffer.from(decoded.signature, 'hex'));

      t.ok(verificationKey.verify(_bitcoinjsLib2.default.crypto.sha256(hubInfo.challenge_text), signature), 'Verified token');
    });
  });
}