diff --git a/assets/dashboard/js/app.js b/assets/dashboard/js/app.js
index d15a63e..68e33ce 100644
--- a/assets/dashboard/js/app.js
+++ b/assets/dashboard/js/app.js
@@ -1,20 +1,14 @@
-window.Web3 = require('web3');
-window.privateKeyToAddress = require('ethereum-private-key-to-address');
-window.Buf = require('buffer').Buffer;
-var Common = require('ethereumjs-common')
-
-/* global location */
'use strict'
+const Web3 = require('web3');
+const privateKeyToAddress = require('ethereum-private-key-to-address');
+const Buf = require('buffer').Buffer;
+const Common = require('ethereumjs-common');
const fetch = require("node-fetch");
-const IPFS = require('ipfs')
-const {
- Buffer
-} = IPFS
const fs = require('fs');
-const Protector = require('libp2p-pnet')
const fileReaderPullStream = require('pull-file-reader')
const request = require('request');
+
// Node
const $ethomessage = document.querySelector('.etho-message')
const $nodeId = document.querySelector('.node-id')
@@ -35,8 +29,6 @@ const $allDisabledElements = document.querySelectorAll('.disabled')
let MainFileArray = [];
const FILES = []
-const workspace = location.hash
-var ChannelStringArray = new Array();
var usedStorageArray = new Array();
var availableStorageArray = new Array();
var nodeCountArray = new Array();
@@ -44,92 +36,675 @@ var PeersForChannel = new Array();
let uploadCount = 0;
let fileSize = 0
process.env.LIBP2P_FORCE_PNET = 1
-let node
-let info
let addr
let messageFlag = 0;
let messageString = "";
let healthMessage = "";
let averageAvailableStorageTotal = 0;
-const swarmKey = "/key/swarm/psk/1.0.0/\n/base16/\n38307a74b2176d0054ffa2864e31ee22d0fc6c3266dd856f6d41bddf14e2ad63";
-var swarmKeyBuffer = new Buffer(swarmKey);
-/* ===========================================================================
- Start the IPFS node
- =========================================================================== */
-function start() {
- if (!node) {
- const options = {
- libp2p: {
- modules: {
- connProtector: new Protector(swarmKeyBuffer)
- },
- config: {
- dht: {
- enabled: false
- }
- }
- },
- config: {
- Bootstrap: [
- '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W',
- '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst',
- '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu',
- '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ',
- '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw',
- '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ',
- '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX',
- '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu',
- '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W',
- '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ',
- '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ'
- ],
- Addresses: {
- Swarm: [
- '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W',
- '/dns4/wss1.ethofs.com/tcp/443/wss/ipfs/QmTcwcKqKcnt84wCecShm1zdz1KagfVtqopg1xKLiwVJst',
- '/dns4/wss.ethofs.com/tcp/443/wss/ipfs/QmPW8zExrEeno85Us3H1bk68rBo7N7WEhdpU9pC9wjQxgu',
- '/dns4/wss2.ethofs.com/tcp/443/wss/ipfs/QmUEy4ScCYCgP6GRfVgrLDqXfLXnUUh4eKaS1fDgaCoGQJ',
- '/dns4/wss3.ethofs.com/tcp/443/wss/ipfs/QmPT4bDvbAjwPTjf2yeugRT1pruHoH2DMLhpjR2NoczWgw',
- '/dns4/wss4.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ',
- '/dns4/wss5.ethofs.com/tcp/443/wss/ipfs/QmRwQ49Zknc2dQbywrhT8ArMDS9JdmnEyGGy4mZ1wDkgaX',
- '/dns4/wss6.ethofs.com/tcp/443/wss/ipfs/Qmf4oLLYAhkXv95ucVvUihnWPR66Knqzt9ee3CU6UoJKVu',
- '/dns4/wss0.ethofs.com/tcp/443/wss/ipfs/QmTJ81wQ6cQV9bh5nTthfLbjnrZPMeeCPfvRFiygSzWV1W',
- '/dns4/wss7.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ',
- '/dns4/wss8.ethofs.com/tcp/443/wss/ipfs/QmeG81bELkgLBZFYZc53ioxtvRS8iNVzPqxUBKSuah2rcQ'
- ]
- }
+
+/*SET CONTRACTS UP HERE*/
+var GlobalChannelString = "ethoFSPinningChannel_alpha11";
+var GlobalControllerContractAddress = "0xc38B47169950D8A28bC77a6Fa7467464f25ADAFc";
+var GlobalControllerABI = JSON.parse('[ { "constant": true, "inputs": [], "name": "last_completed_migration", "outputs": [ { "name": "", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [], "name": "owner", "outputs": [ { "name": "", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [ { "name": "completed", "type": "uint256" } ], "name": "setCompleted", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "new_address", "type": "address" } ], "name": "upgrade", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinToAdd", "type": "string" }, { "name": "pinSize", "type": "uint32" } ], "name": "PinAdd", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pin", "type": "string" } ], "name": "PinRemove", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "inputs": [], "payable": false, "stateMutability": "nonpayable", "type": "constructor" }, { "constant": false, "inputs": [], "name": "deleteContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "hostingCost", "type": "uint256" } ], "name": "SetHostingCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "pinStorageAddress", "type": "address" } ], "name": "SetPinStorageAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSDashboardAddress", "type": "address" } ], "name": "SetEthoFSDashboardAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "ethoFSHostingContractsAddress", "type": "address" } ], "name": "SetEthoFSHostingContractsAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountName", "type": "string" } ], "name": "AddNewUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUserOwner", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "RemoveUserPublic", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "pinSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddNewContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "MainContentHash", "type": "string" } ], "name": "RemoveHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubHostingContracts", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address", "value": "0x" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool", "value": false } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32", "value": "0" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": true, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string", "value": "" } ], "payable": false, "stateMutability": "view", "type": "function" }, { "constant": false, "inputs": [ { "name": "newOperator", "type": "address" } ], "name": "changeOperator", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "AccountName", "type": "string" } ], "name": "AddNewUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "RemoveUser", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "newContractAddress", "type": "address" }, { "name": "UserAddress", "type": "address" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" } ], "name": "AddHostingContract", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" } ], "name": "RemoveHostingContract1", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountActiveContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "GetUserAccountTotalContractCount", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" }, { "name": "ArrayKey", "type": "uint256" } ], "name": "GetHostingContractAddress", "outputs": [ { "name": "value", "type": "address" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "UserAddress", "type": "address" } ], "name": "CheckAccountExistence", "outputs": [ { "name": "", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [], "name": "ScrubContractList", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "set", "type": "uint256" } ], "name": "SetHostingContractCost", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" }, { "name": "HostingContractExtensionDuration", "type": "uint32" } ], "name": "ExtendHostingContract", "outputs": [], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetMainContentHash", "outputs": [ { "name": "MainContentHash", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentHashString", "outputs": [ { "name": "ContentHashString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetContentPathString", "outputs": [ { "name": "ContentPathString", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractDeployedBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractExpirationBlockHeight", "outputs": [ { "name": "value", "type": "uint256" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractStorageUsed", "outputs": [ { "name": "value", "type": "uint32" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "HostingContractAddress", "type": "address" } ], "name": "GetHostingContractName", "outputs": [ { "name": "value", "type": "string" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "MainContentHash", "type": "string" }, { "name": "HostingContractName", "type": "string" }, { "name": "HostingContractDuration", "type": "uint32" }, { "name": "TotalContractSize", "type": "uint32" }, { "name": "ContentHashString", "type": "string" }, { "name": "ContentPathString", "type": "string" } ], "name": "AddHostingContract", "outputs": [ { "name": "value", "type": "address" } ], "payable": true, "stateMutability": "payable", "type": "function" }, { "constant": false, "inputs": [ { "name": "CustomerAddress", "type": "address" }, { "name": "HostingContractAddress", "type": "address" }, { "name": "AccountCollectionAddress", "type": "address" } ], "name": "RemoveHostingContract2", "outputs": [ { "name": "value", "type": "bool" } ], "payable": false, "stateMutability": "nonpayable", "type": "function" }, { "constant": false, "inputs": [ { "name": "AccountCollectionAddress", "type": "address" } ], "name": "SetAccountCollectionAddress", "outputs": [], "payable": false, "stateMutability": "nonpayable", "type": "function" } ]');
+/*END OF CONTRACT SETUP*/
+const $miningMessage = document.querySelector('.mining-message')
+
+/*START OF MISC GLOBAL VARIABLES*/
+var privateKeyLogin = false;
+var GlobalPrivateKey;
+var minimumContractCost = 10000000000000000;
+
+var GlobalUploadName = "";
+var GlobalUserAddress = "";
+var GlobalHostingCost = 1.0;
+var GlobalHostingCostWei = GlobalHostingCost * 1000000000000000000;
+var GlobalUploadSize = 0;
+var GlobalHashArray = new Array();
+var GlobalSizeArray = new Array();
+var GlobalPathArray = new Array();
+var GlobalMainHashArray = new Array();
+var GlobalMainPathArray = new Array();
+var GlobalMainContentHash = "";
+var GlobalUploadHash = "";
+var GlobalUploadPath = "";
+var GlobalContractDuration = "";
+var GlobalHostingContractArray = new Array();
+var GlobalTotalContractCount = 0;
+var GlobalHostingContractDetailArray = new Array();
+var GlobalExtensionDuration;
+/*END OF MISC GLOBAL VARIABLES*/
+
+
+fetch('https://api.coinmarketcap.com/v2/ticker/3452/').then(response => {
+ return response.json();
+}).then(data => {
+ var ethoPriceUSD = data.data.quotes.USD.price;
+ document.getElementById("ethoprice").textContent = round(ethoPriceUSD, 4);
+}).catch(err => {});
+
+if (typeof web3 == 'undefined') {
+ var web3 = new Web3()
+ web3.setProvider(new Web3.providers.HttpProvider('https://rpc.ether1.org'))
+ $('#ethofsLoginModal').modal('show');
+} else {
+ ethofsLogin("");
+}
+
+function ethofsLogin(privateKey) {
+ $('#ethofsLoginModal').modal('hide');
+ $('#ethofsRegistrationModal').modal('hide');
+ //CREATE ETHER-1 CHAIN CONNECTION AND LOOK FOR EXISTING USER ACCOUNT
+ if (privateKey != "") {
+ GlobalPrivateKey = privateKey;
+ privateKeyLogin = true;
+ web3.eth.net.isListening()
+ .then(function() {
+ console.log('ethoFS is connected')
+ let account = web3.eth.accounts.privateKeyToAccount('0x' + privateKey);
+ console.log(account);
+ web3.eth.accounts.wallet.add(account)
+ web3.eth.defaultAccount = account.address;
+ startEthofs()
+ })
+ } else {
+ privateKeyLogin = false;
+ web3 = new Web3(web3.currentProvider);
+ web3.eth.getAccounts(function(err, accounts) {
+ if (err != null) {
+ console.error("An error occurred: " + err);
+ outputNoAddressContractTable();
+ } else if (accounts.length == 0) {
+ $('#ethofsLoginModal').modal('show');
+ console.log("User is not logged in");
+ document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension";
+ document.getElementById("accountaddress").textContent = "Address Not Found";
+ outputNoAddressContractTable();
+ } else {
+ console.log("User is logged in");
+ web3.eth.defaultAccount = accounts[0];
+ startEthofs();
}
- }
- node = new IPFS(options)
- node.once('start', () => {
- node.id()
- .then((id) => {
- info = id
- subscribeToHealthChannel()
- updateView('ready', node)
- onSuccess('Node is ready.')
- setInterval(refreshPeerList, 10000)
- setInterval(sendFileList, 10000)
- })
- .catch((error) => onError(error))
- })
+ });
}
}
-function SwarmPeers() {
- node.swarm.peers(function(err, peerInfos) {
- if (err) {
- throw err
+function startEthofs() {
+ console.log("Starting ethoFS");
+ GlobalUserAddress = web3.eth.defaultAccount;
+ var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
+ ethoFSAccounts.methods.CheckAccountExistence(GlobalUserAddress).call(function(error, result) {
+ if (!error) {
+ if (result) {
+ document.getElementById("accountaddress").textContent = web3.eth.defaultAccount;
+ ethoFSAccounts.methods.GetUserAccountName(GlobalUserAddress).call(function(error, result) {
+ if (!error) {
+ if (result) {
+ getBlockHeight(web3);
+ getBalance(web3);
+ document.getElementById("welcome-name").textContent = "Welcome Back " + result;
+ updateContractTable();
+ startApplication();
+ }
+ } else {
+ console.log("Error getting user account name");
+ }
+ });
+ } else {
+ document.getElementById("welcome-name").textContent = "User Not Found";
+ document.getElementById("accountaddress").textContent = "Address Not Found";
+ console.log("User Not Found");
+ $('#ethofsRegistrationModal').modal('show');
+ }
+ } else {
+ document.getElementById("welcome-name").textContent = "Access to Ether-1 Blockchain Not Found - Make Sure You Are Using Metamask or The Ether-1 Browser Extension";
+ document.getElementById("accountaddress").textContent = "Address Not Found";
+ console.log("Blockchain Access Error");
}
- console.log(peerInfos)
- })
+ });
}
+
+/*************************************************************************************************************/
+function AddNewUser(userName) {
+ console.log("Initiating New User Addition... " + userName);
+ var controller = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
+
+ if (privateKeyLogin == true) {
+ const tx = {
+ to: GlobalControllerContractAddress,
+ from: GlobalUserAddress,
+ gas: 4000000,
+ data: controller.methods.AddNewUserPublic(userName).encodeABI()
+ };
+ var privateKey = '0x' + GlobalPrivateKey;
+ web3.eth.accounts.signTransaction(tx, privateKey)
+ .then(function(signedTransactionData) {
+ web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) {
+ if (!error) {
+ if (result) {
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ ethofsLogin(GlobalPrivateKey);
+ });
+ } else {
+ console.log("There was a problem adding new contract");
+ }
+ } else {
+ console.error(error);
+ }
+ });
+ });
+ } else {
+ controller.methods.AddNewUserPublic(userName).send(function(error, result) {
+ if (!error) {
+ if (result) {
+ document.getElementById("wait").innerHTML = 'Waiting For Add User Confirmation.';
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ ethofsLogin("");
+ });
+ } else {
+ console.log("There was a problem adding new user");
+ $('#ethofsLoginModal').modal('show');
+ }
+ } else {
+ console.error(error);
+ $('#ethofsLoginModal').modal('show');
+ }
+ });
+ }
+}
+/*************************************************************************************************************/
+function getBlockHeight(web3) {
+ console.log("Starting Block Height Detection..");
+ web3.eth.getBlockNumber(function(err, data) {
+ document.getElementById("blocknumber").textContent = data;
+ console.log("ETHO Block Number: " + data);
+ });
+}
+/*************************************************************************************************************/
+function getBalance(web3) {
+ console.log("Starting Balance Detection..");
+ web3.eth.getBalance(web3.eth.defaultAccount, function(err, data) {
+ var balance = "ETHO Balance: " + Number(web3.utils.fromWei(data, "ether")).toFixed(2);
+ document.getElementById("ethobalance").textContent = balance;
+ console.log("ETHO Balance: " + data);
+ });
+}
+/*************************************************************************************************************/
+//CALCULATE AMOUNT TO BE SENT
+function calculateCost(contractSize, contractDuration, hostingCost) {
+ var cost = ((((contractSize / 1048576) * hostingCost) * (contractDuration / 46522)));
+ if (cost < minimumContractCost) {
+ cost = minimumContractCost;
+ }
+ return cost;
+}
+/*************************************************************************************************************/
+//CHECK FOR TX - BLOCK TO BE MINED
+function waitForReceipt(hash, cb) {
+ web3.eth.getTransactionReceipt(hash, function(err, receipt) {
+ document.getElementById("mining-status-message").textContent = "In Progress";
+ $miningMessage.innerText = "Waiting For Transaction Confirmation";
+ web3.eth.getBlock('latest', function(e, res) {
+ if (!e) {
+ document.getElementById("block-height").textContent = res.number;
+ }
+ });
+ if (err) {
+ error(err);
+ $miningMessage.innerText = "Error Conneting To Ether-1 Network";
+ }
+ if (receipt !== null) {
+ $miningMessage.innerText = "Transaction Confirmed";
+ document.getElementById("mining-status-message").textContent = "Complete";
+ if (cb) {
+ cb(receipt);
+ }
+ } else {
+ setTimeout(function() {
+ waitForReceipt(hash, cb);
+ }, 10000);
+ }
+ });
+}
+/*************************************************************************************************************/
+//CREATE ETHER-1 CHAIN CONNECTION AND REMOVE CONTRACT
+function RemoveContract(hostingAddress, contentHash) {
+ var pinRemoving = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
+ if (privateKeyLogin == true) {
+ const tx = {
+ to: GlobalControllerContractAddress,
+ from: GlobalUserAddress,
+ gas: 4000000,
+ data: pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).encodeABI()
+ };
+ var privateKey = '0x' + GlobalPrivateKey;
+ console.log("Private Key: " + privateKey);
+ web3.eth.accounts.signTransaction(tx, privateKey)
+ .then(function(signedTransactionData) {
+ console.log("Signed TX Data: " + signedTransactionData.rawTransaction);
+ web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) {
+ if (!error) {
+ if (result) {
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ updateContractTable();
+ });
+ } else {
+ console.log("There was a problem adding new contract");
+ }
+ } else {
+ console.error(error);
+ }
+ });
+ });
+ } else {
+ const tx = {
+ to: GlobalControllerContractAddress,
+ from: GlobalUserAddress,
+ };
+ pinRemoving.methods.RemoveHostingContract(hostingAddress, contentHash).send(tx, function(error, result) {
+ if (!error) {
+ if (result) {
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ updateContractTable();
+ });
+ } else {
+ console.log("There was a problem removing contract");
+ }
+ } else {
+ console.error(error);
+ }
+ });
+ }
+}
+
+function updateContractTable() {
+ /*************************************************************************************************************/
+ //CREATE ETHER-1 CHAIN CONNECTION AND GET USER ACCOUNT & CONTRACTS
+ var ethoFSHostingContracts = new Array();
+ var hostingContracts = "";
+ var TotalContractCount = 0;
+ var blockHeight = 0;
+ web3.eth.getBlockNumber(function(error, result) {
+ if (!error) {
+ blockHeight = result;
+ } else
+ console.error(error);
+ });
+ var ethoFSAccounts = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
+ ethoFSAccounts.methods.GetUserAccountTotalContractCount(web3.eth.defaultAccount).call(function(error, result) {
+ TotalContractCount = result;
+ GlobalTotalContractCount = result;
+ const getContractData = async (ethoFSAccounts, account, TotalContractCount) => {
+ if (TotalContractCount == 0) {
+ outputNoAddressContractTableWithButton();
+ }
+ for (var i = 0; i < TotalContractCount; i++) {
+ const promisify = (inner) =>
+ new Promise((resolve, reject) =>
+ inner((err, res) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(res);
+ }
+ })
+ );
+ var counter = i;
+ GlobalHostingContractArray[counter] = new Array();
+ var ethoFSHostingContractAddress = promisify(cb => ethoFSAccounts.methods.GetHostingContractAddress(account, counter).call(cb));
+ await Promise.all([getAdditionalContractData(await ethoFSHostingContractAddress, counter, ethoFSAccounts)]);
+
+ async function getAdditionalContractData(ethoFSHostingContractAddress, counter, ethoFSAccounts) {
+ const promisify = (inner) =>
+ new Promise((resolve, reject) =>
+ inner((err, res) => {
+ if (err) {
+ reject(err);
+ } else {
+ resolve(res);
+ }
+ })
+ );
+ var ethoFSHostingContractCost = counter;
+ var ethoFSHostingContractName = promisify(cb => ethoFSAccounts.methods.GetHostingContractName(ethoFSHostingContractAddress).call(cb));
+ var ethoFSHostingContractMainHash = promisify(cb => ethoFSAccounts.methods.GetMainContentHash(ethoFSHostingContractAddress).call(cb));
+ var ethoFSHostingContractHashString = promisify(cb => ethoFSAccounts.methods.GetContentHashString(ethoFSHostingContractAddress).call(cb));
+ var ethoFSHostingContractPathString = promisify(cb => ethoFSAccounts.methods.GetContentPathString(ethoFSHostingContractAddress).call(cb));
+
+ var ethoFSHostingContractStorage = promisify(cb => ethoFSAccounts.methods.GetHostingContractStorageUsed(ethoFSHostingContractAddress).call(cb));
+ var ethoFSHostingContractStartBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractDeployedBlockHeight(ethoFSHostingContractAddress).call(cb));
+ var ethoFSHostingContractEndBlock = promisify(cb => ethoFSAccounts.methods.GetHostingContractExpirationBlockHeight(ethoFSHostingContractAddress).call(cb));
+
+ GlobalHostingContractArray[counter]['address'] = await ethoFSHostingContractAddress;
+ GlobalHostingContractArray[counter]['name'] = await ethoFSHostingContractName;
+ GlobalHostingContractArray[counter]['mainhash'] = await ethoFSHostingContractMainHash;
+ GlobalHostingContractArray[counter]['hashstring'] = await ethoFSHostingContractHashString;
+ GlobalHostingContractArray[counter]['pathstring'] = await ethoFSHostingContractPathString;
+ GlobalHostingContractArray[counter]['storage'] = await ethoFSHostingContractStorage;
+ GlobalHostingContractArray[counter]['startblock'] = await ethoFSHostingContractStartBlock;
+ GlobalHostingContractArray[counter]['endblock'] = await ethoFSHostingContractEndBlock;
+
+ GlobalHostingContractArray[counter]['hash'] = new Array();
+ GlobalHostingContractArray[counter]['path'] = new Array();
+
+ var ContractHashArray = new Array();
+ var ContractPathArray = new Array();
+ var splitHashArray = await Promise.all([splitString(await ethoFSHostingContractHashString, ":")]);
+ var splitPathArray = await Promise.all([splitString(await ethoFSHostingContractPathString, ":")]);
+
+ function splitString(stringToSplit, splitDelimeter) {
+ return stringToSplit.split(splitDelimeter);
+ }
+ await Promise.all([loopSplitStrings(await splitHashArray[0], await splitPathArray[0], counter)]);
+
+ function loopSplitStrings(splitHashArray, splitPathArray, counter) {
+ for (var j = 1; j < splitHashArray.length; j++) {
+ GlobalHostingContractArray[counter]['hash'][j] = splitHashArray[j];
+ GlobalHostingContractArray[counter]['path'][j] = splitPathArray[j];
+ }
+ }
+
+ await Promise.all([addNewTableEntry(await ethoFSHostingContractAddress, await ethoFSHostingContractMainHash, await ethoFSHostingContractName, await ethoFSHostingContractAddress, await ethoFSHostingContractStorage, await ethoFSHostingContractStartBlock, await ethoFSHostingContractEndBlock, await ethoFSHostingContractCost, await counter, await blockHeight)]);
+ }
+ }
+ //END GET ADDITIONAL CONTACT DATA
+ };
+ getContractData(ethoFSAccounts, web3.eth.defaultAccount, TotalContractCount);
+
+ function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractMainHash, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractCost, counter, blockHeight) {
+ if (blockHeight > ethoFSHostingContractEndBlock) {
+ var ethoFSHostingContractStatus = "Expired";
+ hostingContracts += '
| ' + ethoFSHostingContractName + ' | ' + ethoFSHostingContractHash + ' | ' + ethoFSHostingContractStartBlock + ' | ' + ethoFSHostingContractEndBlock + ' | ' + ethoFSHostingContractStatus + ' | |
';
+ } else {
+ var ethoFSHostingContractStatus = "Active";
+ hostingContracts += '| ' + ethoFSHostingContractName + ' | ' + ethoFSHostingContractHash + ' | ' + ethoFSHostingContractStartBlock + ' | ' + ethoFSHostingContractEndBlock + ' | ' + ethoFSHostingContractStatus + ' | |
';
+ }
+ GlobalHostingContractArray[counter]['status'] = ethoFSHostingContractStatus;
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+ }
+ });
+}
+/*************************************************************************************************************/
+//UPDATE CONTRACT DURATION AND CONTRACT COST
+function contractDurationChange(selectObj) {
+ var duration = document.getElementById('contract-duration').value;
+ GlobalContractDuration = duration;
+ var ContractCost = (((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522));
+ document.getElementById("contract-cost").innerHTML = round(ContractCost, 2);
+ return false;
+}
+/*************************************************************************************************************/
+//MISC ROUNDING FUNCTION
+function round(value, decimals) {
+ return Number(Math.round(value + 'e' + decimals) + 'e-' + decimals);
+}
+/*************************************************************************************************************/
+function finishUploadModal() {
+ $('#uploadTrackerModal').modal('hide');
+ stopApplication();
+ resetUploadSystem();
+ updateContractTable();
+ return false;
+}
+
+function resetUploadModal() {
+ stopApplication();
+ resetUploadSystem();
+ updateContractTable();
+ return false;
+}
+/*************************************************************************************************************/
+//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT
+function checkForUploadedContentAvailability(HostingContractName) {
+ document.getElementById("upload-check-button").style.visibility = "hidden";
+ $('#uploadTrackerModal').modal('show');
+ document.getElementById("upload-hash").innerHTML = HostingContractName;
+ return false;
+}
+/*************************************************************************************************************/
+/*************************************************************************************************************/
+function resetUploadSystem() {
+ GlobalMainHashArray = new Array();
+ GlobalMainPathArray = new Array();
+ GlobalHashArray = new Array();
+ GlobalPathArray = new Array();
+ GlobalUploadHash = "";
+ GlobalUploadPath = "";
+ GlobalUploadSize = 0;
+ var TableBody = document.getElementById("file-history-body");
+ TableBody.innerHTML = '| There are no files awaiting upload |
';
+ var duration = document.getElementById('contract-duration').value;
+ GlobalContractDuration = duration;
+ var ContractCost = ((GlobalUploadSize / 1048576) * GlobalHostingCost) * (duration / 46522);
+ document.getElementById("contract-cost").innerHTML = round(ContractCost, 2);
+ document.getElementById("upload-hash").innerHTML = "";
+ document.getElementById("upload-size").innerHTML = 0;
+ return false;
+}
+/*************************************************************************************************************/
+/*************************************************************************************************************/
+//CHECK FOR PROPAGATED & AVAILABLE DATA ON NETWORK - FINAL VERIFICATION FOR UPLOADED CONTENT
+function sortContractTable() {
+ var hostingContracts = "";
+ var i;
+ var localContractArray = GlobalHostingContractArray;
+ var tableSortDirection = "";
+ var sortSelection = document.getElementById('sort-contracts');
+ var tableSorter = sortSelection.value;
+ var filterSelection = document.getElementById('filter-contracts');
+ var tableFilterer = filterSelection.value;
+
+ if (tableSorter == "Ascending") {
+ tableSortDirection = "asc";
+ } else {
+ tableSortDirection = "desc";
+ }
+ localContractArray = multiSort(localContractArray, {
+ startblock: tableSortDirection
+ });
+ var filterCounter = 0;
+ for (var i = 0; i < GlobalTotalContractCount; i++) {
+ if ((localContractArray[i]['status'] != "Expired" && tableFilterer == "Active Contracts") || (localContractArray[i]['status'] != "Active" && tableFilterer == "Expired Contracts") || tableFilterer == "All Contracts") {
+ addNewTableEntry(localContractArray[i]['address'], localContractArray[i]['name'], localContractArray[i]['hash'], localContractArray[i]['storage'], localContractArray[i]['startblock'], localContractArray[i]['endblock'], localContractArray[i]['status'], localContractArray[i]['cost'], i);
+ filterCounter++;
+ } else {
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+ }
+ }
+ if (GlobalTotalContractCount == 0 || filterCounter == 0) {
+ hostingContracts = '| No Hosting Contracts Found | | | | | |
';
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+
+ }
+
+ function addNewTableEntry(ethoFSHostingContractAddress, ethoFSHostingContractName, ethoFSHostingContractHash, ethoFSHostingContractStorage, ethoFSHostingContractStartBlock, ethoFSHostingContractEndBlock, ethoFSHostingContractStatus, ethoFSHostingContractCost, counter) {
+ if (ethoFSHostingContractStatus == "Active") {
+ hostingContracts += '| ' + ethoFSHostingContractName + ' | ' + ethoFSHostingContractHash + ' | ' + ethoFSHostingContractStartBlock + ' | ' + ethoFSHostingContractEndBlock + ' | ' + ethoFSHostingContractStatus + ' | |
';
+ } else {
+ hostingContracts += '| ' + ethoFSHostingContractName + ' | ' + ethoFSHostingContractHash + ' | ' + ethoFSHostingContractStartBlock + ' | ' + ethoFSHostingContractEndBlock + ' | ' + ethoFSHostingContractStatus + ' | |
';
+ }
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+ }
+
+ function multiSort(array, sortObject = {}) {
+ const sortKeys = Object.keys(sortObject);
+ // Return array if no sort object is supplied.
+ if (!sortKeys.length) {
+ return array;
+ }
+ // Change the values of the sortObject keys to -1, 0, or 1.
+ for (let key in sortObject) {
+ sortObject[key] = sortObject[key] === 'desc' || sortObject[key] === -1 ? -1 :
+ (sortObject[key] === 'skip' || sortObject[key] === 0 ? 0 : 1);
+ }
+ const keySort = (a, b, direction) => {
+ direction = direction !== null ? direction : 1;
+ if (a === b) { // If the values are the same, do not switch positions.
+ return 0;
+ }
+ // If b > a, multiply by -1 to get the reverse direction.
+ return a > b ? direction : -1 * direction;
+ };
+ return array.sort((a, b) => {
+ let sorted = 0;
+ let index = 0;
+ // Loop until sorted (-1 or 1) or until the sort keys have been processed.
+ while (sorted === 0 && index < sortKeys.length) {
+ const key = sortKeys[index];
+ if (key) {
+ const direction = sortObject[key];
+ sorted = keySort(a[key], b[key], direction);
+ index++;
+ }
+ }
+ return sorted;
+ });
+ }
+}
+/*************************************************************************************************************/
+//SHOW MODAL WITH HOSTING CONTRACT DETAILS
+function showHostingContractDetails(counter) {
+ resetContractExtensionChange();
+
+ GlobalHostingContractDetailArray = GlobalHostingContractArray[counter];
+ $('#contractDetailModal').modal('show');
+ document.getElementById("contract-detail-name").innerHTML = GlobalHostingContractDetailArray['name'];
+ var hashOutputString = "";
+ var hostingContractEntry = "";
+ for (var i = 1; GlobalHostingContractDetailArray['hash'].length > i; i++) {
+ addNewTableEntry(GlobalHostingContractDetailArray['hash'][i], GlobalHostingContractDetailArray['path'][i], i);
+ }
+ document.getElementById("contract-detail-startblock").innerHTML = GlobalHostingContractDetailArray['startblock'];
+ document.getElementById("contract-detail-endblock").innerHTML = GlobalHostingContractDetailArray['endblock'];
+ document.getElementById("contract-detail-status").innerHTML = GlobalHostingContractDetailArray['status'];
+ document.getElementById("contract-detail-size").innerHTML = (GlobalHostingContractDetailArray['storage'] / 1048576);
+
+ function addNewTableEntry(ethoFSHostingContractHash, ethoFSHostingContractPath, count) {
+ var table = document.getElementById("contract-detail-table");
+ var row = table.insertRow(count + 10);
+ var cell1 = row.insertCell(0);
+ //var cell2 = row.insertCell(1);
+ //cell1.innerHTML = ethoFSHostingContractPath;
+ cell1.innerHTML = '' + ethoFSHostingContractHash + '';
+ }
+
+}
+
+function resetContractDetailTableRows() {
+ var x = document.getElementById("contract-detail-table").rows.length;
+ for (var y = (x - 1); y > 10; y--) {
+ document.getElementById("contract-detail-table").deleteRow(y);
+ }
+}
+/*************************************************************************************************************/
+//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT
+function outputNoAddressContractTable() {
+ hostingContracts = '| No Hosting Contracts Found | | | | | |
';
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+}
+//LOCK CONTRACT TABLE DOWN - NO USER ACCOUNT
+function outputNoAddressContractTableWithButton() {
+ hostingContracts = '| No Hosting Contracts Found | | | | | |
';
+ document.getElementById("hostingcontractstablebody").innerHTML = hostingContracts;
+}
+/*************************************************************************************************************/
+function resetContractExtensionChange() {
+ GlobalExtensionDuration = 0;
+ document.getElementById("contract-extension-cost").innerHTML = 0;
+ document.getElementById("extend-contract").selectedIndex = "0";
+}
+/*************************************************************************************************************/
+//CONTRACT EXTENSION VALUE CHANGE
+function contractExtensionChange(selectObj) {
+ var index = selectObj.selectedIndex;
+ var extensionDuration = selectObj.options[index].value;
+ GlobalExtensionDuration = extensionDuration;
+ document.getElementById("contract-extension-button").style.visibility = "visible";
+ var extensionCost = ((GlobalHostingContractDetailArray['storage'] / 1048576) * GlobalHostingCost) * (extensionDuration / 46522);
+ document.getElementById("contract-extension-cost").innerHTML = round(extensionCost, 2);
+}
+/*************************************************************************************************************/
+//CONTRACT EXTENSION CONFIRM
+function contractExtensionConfirmation() {
+ if (GlobalExtensionDuration > 0) {
+ var extensionDuration = GlobalExtensionDuration;
+ var ethoFSController = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
+
+ var extensionCost = calculateCost(GlobalHostingContractDetailArray['storage'], extensionDuration, GlobalHostingCostWei);
+ const transactionObject = {
+ from: GlobalUserAddress,
+ value: extensionCost
+ };
+ if (privateKeyLogin == true) {
+ const tx = {
+ to: GlobalControllerContractAddress,
+ from: GlobalUserAddress,
+ value: extensionCost,
+ gas: 4000000,
+ data: ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).encodeABI()
+ };
+ var privateKey = '0x' + GlobalPrivateKey;
+ console.log("Private Key: " + privateKey);
+ web3.eth.accounts.signTransaction(tx, privateKey)
+ .then(function(signedTransactionData) {
+ console.log("Signed TX Data: " + signedTransactionData.rawTransaction);
+ web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) {
+ if (!error) {
+ if (result) {
+ $('#contractDetailModal').modal('hide');
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ updateContractTable();
+ });
+ } else {
+ console.log("There was a problem adding new contract");
+ }
+ } else {
+ console.error(error);
+ }
+ });
+ });
+ } else {
+
+ ethoFSController.methods.ExtendContract(GlobalHostingContractDetailArray['address'], extensionDuration).send(transactionObject, function(error, result) {
+ if (!error) {
+ if (result) {
+ $('#contractDetailModal').modal('hide');
+ $('#minedBlockTrackerModal').modal('show');
+ waitForReceipt(result, function(receipt) {
+ console.log("Transaction Has Been Mined: " + receipt);
+ $('#minedBlockTrackerModal').modal('hide');
+ updateContractTable();
+ });
+ }
+ } else {
+ console.log(error);
+ }
+ });
+ }
+ }
+}
+/*************************************************************************************************************/
+
/* ===========================================================================
Pubsub
=========================================================================== */
const subscribeToHealthChannel = () => {
- node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler)
+ window.node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler)
.catch(() => onError('An error occurred when subscribing to the health check workspace.'))
}
const healthMessageHandler = (message) => {
@@ -202,19 +777,16 @@ const receiveExitMsg = (msg) => console.log("Content Upload Successful")
const exitMessageHandler = (message) => {
const cancelMessageString = message.data.toString()
}
-window.CheckForUploadedContentVerification = function(){
-
-}
const subscribeToMessaging = () => {
for(var i = 4; i < PeersForChannel.length; i++){
- node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler)
+ window.node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler)
.catch(() => onError('An error occurred when subscribing to the workspace.'))
}
}
const unsubscribeToMessaging = () => {
for(var i = 4; i < PeersForChannel.length; i++){
- node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler)
+ window.node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler)
.catch(() => onError('An error occurred when unsubscribing to the workspace.'))
}
}
@@ -222,7 +794,7 @@ const publishImmediatePin = (hash) => {
const data = Buffer.from(hash)
for (var i = 0; i < PeersForChannel.length; i++) {
var channel = PeersForChannel[i] + "ImmediatePinningChannel_alpha11";
- node.pubsub.publish(channel, data)
+ window.node.pubsub.publish(channel, data)
.catch(() => onError('An error occurred when publishing the message.'))
}
}
@@ -230,18 +802,15 @@ const publishImmediatePin = (hash) => {
/* ===========================================================================
Files handling
=========================================================================== */
-
-const isFileInList = (hash) => FILES.indexOf(hash) !== -1
-
const sendFileList = () => FILES.forEach((hash) => publishHash(hash))
-const updateProgress = (bytesLoaded) => {
+/*const updateProgress = (bytesLoaded) => {
let percent = 100 - ((bytesLoaded / fileSize) * 100)
if (percent <= 5) {
document.getElementById("upload-confirm-button").style.visibility = "visible";
}
$progressBar.style.transform = `translateX(${-percent}%)`
-}
+}*/
const resetProgress = () => {
$progressBar.style.transform = 'translateX(-100%)'
@@ -289,13 +858,16 @@ function resetFileTable() {
const onDragEnter = (event) => $dragContainer.classList.add('dragging')
const onDragLeave = () => $dragContainer.classList.remove('dragging')
-window.startUploadProcess = function() {
+function startUploadProcess() {
+ console.log("Starting Upload Process..");
$('#preparingUploadModal').modal('show');
var streamFinishCount = 0;
for (var i = 0; i < MainFileArray.length; i++) {
const streamFiles = (files) => {
const stream = node.addReadableStream()
stream.on('data', function(data) {
+ console.log("Data...");
+ console.log(data);
GlobalHashArray.push(`${data.hash}`);
GlobalSizeArray.push(`${data.size}`);
GlobalPathArray.push(`${data.path}`);
@@ -306,7 +878,7 @@ window.startUploadProcess = function() {
streamFinishCount++;
GlobalMainHashArray.push(`${data.hash}`);
GlobalMainPathArray.push(`${data.path}`);
- if (streamFinishCount == MainFileArray.length) {
+ if(streamFinishCount == MainFileArray.length) {
createMainHash();
}
}
@@ -385,7 +957,7 @@ window.startUploadProcess = function() {
for (i = 0; i < GlobalMainHashArray.length; i++) {
contentHashString += ":" + GlobalMainHashArray[i];
}
- node.add(Buffer.from(contentHashString), (err, res) => {
+ window.node.add(Buffer.from(contentHashString), (err, res) => {
if (err || !res) {
return console.error('ipfs add error', err, res)
}
@@ -493,46 +1065,66 @@ function updateAnalyzeProgress(width) {
}
function onFileUpload(event) {
+ event.preventDefault()
document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA";
document.getElementById("upload-confirm-button").style.visibility = "hidden";
MainFileArray.push([]);
- let filesUploaded = event.target.files;
- var streamCompareCount = filesUploaded.length;
- for (let i = 0; filesUploaded.length > i; i++) {
- handleFile(filesUploaded[i]);
- }
+ let dirSelected = event.target.files;
+ let dirPath = dirSelected[0].path;
+ var streamCompareCount = 0;
+ var totalUploadItems = 0;
+ readDirectoryContents(dirPath);
- function readFileContents(file) {
- return new Promise((resolve) => {
- const reader = new window.FileReader()
- reader.onload = (event) => resolve(event.target.result)
- reader.readAsArrayBuffer(file)
- })
- }
-
- function handleFile(file) {
- readFileContents(file).then((buffer) => {
- var filePath = file.webkitRelativePath;
- var filetowrite = {
- path: filePath,
- content: Buffer.from(buffer)
- };
- MainFileArray[MainFileArray.length - 1].push(filetowrite);
- GlobalUploadSize += Number(file.size);
- fileSize += Number(file.size);
- var totalUploadSizeMB = GlobalUploadSize / 1000000;
- appendFile(filePath, file.name, file.size, null);
- console.log("Path: " + filePath + " Size: " + file.size + " Total Size: " + GlobalUploadSize);
- document.getElementById("upload-size").textContent = totalUploadSizeMB;
- contractDurationChange(document.getElementById('contract-duration').value);
- streamCompareCount--;
- updateAnalyzeProgress(((filesUploaded.length - streamCompareCount) / filesUploaded.length));
- if (streamCompareCount == 0) {
- document.getElementById("upload-hash").textContent = "READY FOR UPLOAD";
- document.getElementById("upload-confirm-button").style.visibility = "visible";
+ function readDirectoryContents(directory) {
+ console.log("Directory Path: " + directory);
+ fs.readdir(directory, function(err, filesUploaded) {
+ if(!err) {
+ for (let i = 0; filesUploaded.length > i; i++) {
+ handleItem(filesUploaded[i], directory);
+ }
+ } else {
+ console.log("File Upload Error: " + err);
}
});
}
+
+ function handleItem(filename, relativePath) {
+ var filepath = relativePath.concat('\\', filename);
+ fs.stat(filepath, function(err, stats) {
+ if(!err) {
+ if(stats.isDirectory()) {
+ readDirectoryContents(filepath)
+ } else {
+ streamCompareCount ++;
+ totalUploadItems ++;
+ console.log("File Path: " + filepath);
+ fs.readFile(filepath, function(err, file) {
+ var filetowrite = {
+ path: filepath,
+ content: file
+ };
+ var filename = filepath;
+ MainFileArray[MainFileArray.length - 1].push(filetowrite);
+ GlobalUploadSize += Number(stats.size);
+ fileSize += Number(stats.size);
+ var totalUploadSizeMB = GlobalUploadSize / 1000000;
+ appendFile(filepath, filename, stats.size, null);
+ console.log("Path: " + filepath + " Size: " + stats.size + " Total Size: " + GlobalUploadSize);
+ document.getElementById("upload-size").textContent = totalUploadSizeMB;
+ contractDurationChange(document.getElementById('contract-duration').value);
+ streamCompareCount--;
+ updateAnalyzeProgress(((totalUploadItems - streamCompareCount) / totalUploadItems));
+ if (streamCompareCount == 0) {
+ document.getElementById("upload-hash").textContent = "READY FOR UPLOAD";
+ document.getElementById("upload-confirm-button").style.visibility = "visible";
+ }
+ });
+ }
+ } else {
+ console.log("File Stats Error: " + err);
+ }
+ });
+ }
}
function onDrop(event) {
@@ -626,7 +1218,7 @@ function connectToPeer(event) {
return onError('No multiaddr was inserted.')
}
- node.swarm.connect(multiaddr)
+ window.node.swarm.connect(multiaddr)
.then(() => {
onSuccess(`Successfully connected to peer.`)
$multiaddrInput.value = ''
@@ -653,7 +1245,7 @@ function updatePeerProgress(width, peercount) {
function refreshPeerList() {
var updatedPeerCount = 0;
- node.swarm.peers()
+ window.node.swarm.peers()
.then((peers) => {
const peersAsHtml = peers.reverse()
.map((peer) => {
@@ -712,10 +1304,10 @@ window.onerror = onError
const states = {
ready: () => {
- const addressesHtml = info.addresses.map((address) => {
+ const addressesHtml = window.info.addresses.map((address) => {
return `${address}`
}).join('')
- $nodeId.innerText = info.id
+ $nodeId.innerText = window.info.id
$allDisabledButtons.forEach(b => {
b.disabled = false
})
@@ -738,21 +1330,22 @@ function updateView(state, ipfs) {
/* ===========================================================================
Boot the app
=========================================================================== */
-window.startApplication = function() {
+function startApplication() {
// Setup event listeners
$dragContainer.addEventListener('dragenter', onDragEnter)
$dragContainer.addEventListener('dragover', onDragEnter)
$dragContainer.addEventListener('drop', onDrop)
$dragContainer.addEventListener('dragleave', onDragLeave)
document.getElementById("fileUploadButton").addEventListener("change", onFileUpload)
- start()
+ //start()
+ window.startNode()
extendedStartApplication()
}
function extendedStartApplication() {
$ethomessage.innerText = GlobalUserAddress;
}
-window.stopApplication = function() {
+function stopApplication() {
resetUploadProcess();
resetFileTable();
}
diff --git a/assets/dashboard/js/bundle.js b/assets/dashboard/js/bundle.js
index ec3b59f..2169965 100644
--- a/assets/dashboard/js/bundle.js
+++ b/assets/dashboard/js/bundle.js
@@ -1,65 +1,23 @@
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i {
- node.id()
+ console.log("Launching ethoFS Node...");
+ window.node = new IPFS(options)
+ console.log("Waiting For ethoFS Node Launch Confirmation...");
+ window.node.once('start', () => {
+ console.log("ethoFS Node Startup Confirmed...");
+ window.node.id()
.then((id) => {
- info = id
+
+ window.info = id
+ console.log("Getting ethoFS Node ID...");
subscribeToHealthChannel()
- updateView('ready', node)
+ updateView('ready', window.node)
onSuccess('Node is ready.')
setInterval(refreshPeerList, 10000)
setInterval(sendFileList, 10000)
@@ -117,650 +80,11 @@ function start() {
})
}
}
-
-function SwarmPeers() {
- node.swarm.peers(function(err, peerInfos) {
- if (err) {
- throw err
- }
- console.log(peerInfos)
- })
-}
-/* ===========================================================================
- Pubsub
- =========================================================================== */
-
-const subscribeToHealthChannel = () => {
- node.pubsub.subscribe(info.id + "_alpha11", healthMessageHandler)
- .catch(() => onError('An error occurred when subscribing to the health check workspace.'))
-}
-const healthMessageHandler = (message) => {
- healthMessage = message.data.toString();
- UpdateHealthCheckInfo(healthMessage);
-}
-function UpdateHealthCheckInfo(healthMessage) {
- var mainMessage = healthMessage.split(";")[1];
- var splitMessage = mainMessage.split(",");
- var usedStorageTotal = 0;
- var availableStorageTotal = 0;
- var activeHistory = 0;
- var nodeCounter = 0;
- splitMessage.forEach(function(nodeMessage, index) {
- var nodeSplitMessage = nodeMessage.split(":");
- activeHistory = Number(nodeSplitMessage[5]);
- if(activeHistory >= 5){
- nodeCounter++;
- usedStorageTotal += Number(nodeSplitMessage[8]);
- availableStorageTotal += Number(nodeSplitMessage[7]);
- }
- if(index == (splitMessage.length - 1)){
- updateStorageArrays(usedStorageTotal, availableStorageTotal, nodeCounter);
- }
- });
- function updateStorageArrays(usedStorageTotal, availableStorageTotal, nodecount){
-
- if(availableStorageArray.length >= 50){
- if(availableStorageTotal > 0.75 * averageAvailableStorageTotal && availableStorageTotal < 1.25 * averageAvailableStorageTotal){
- availableStorageArray.push(availableStorageTotal);
- availableStorageArray.shift();
- }
- }else{
- availableStorageArray.push(availableStorageTotal);
- }
- if(nodeCountArray.length >= 50){
- nodeCountArray.push(nodecount);
- nodeCountArray.shift();
- }else{
- nodeCountArray.push(nodecount);
- }
- calculateStorageAverages(usedStorageArray, availableStorageArray, nodeCountArray);
- }
- function calculateStorageAverages(usedStorageArray, availableStorageArray, nodeCountArray){
-
- var sumAvailableStorage = 0;
- availableStorageArray.forEach(function(value, index) {
- sumAvailableStorage += value;
- if(index == (availableStorageArray.length - 1)){
- averageAvailableStorageTotal = (sumAvailableStorage/availableStorageArray.length);
- document.getElementById("nodestorage").textContent=(round(2+((averageAvailableStorageTotal)/1000000), 1)) + "TB";
- }
- });
- var sumNodeCount = 0;
- nodeCountArray.forEach(function(value, index) {
- sumNodeCount += value;
- if(index == (nodeCountArray.length - 1)){
- var averageNodeCount = (sumNodeCount/nodeCountArray.length) + 19;
- document.getElementById("nodecount").textContent=(round(averageNodeCount, 0));
- }
- });
- }
-}
-
-
-const messageHandler = (message) => {
- messageString = message.data.toString();
-}
-const receiveExitMsg = (msg) => console.log("Content Upload Successful")
-const exitMessageHandler = (message) => {
- const cancelMessageString = message.data.toString()
-}
-window.CheckForUploadedContentVerification = function(){
-
-}
-
-const subscribeToMessaging = () => {
- for(var i = 4; i < PeersForChannel.length; i++){
- node.pubsub.subscribe(PeersForChannel[i] + "PinningChannel_alpha11", messageHandler)
- .catch(() => onError('An error occurred when subscribing to the workspace.'))
- }
-}
-const unsubscribeToMessaging = () => {
- for(var i = 4; i < PeersForChannel.length; i++){
- node.pubsub.unsubscribe(PeersForChannel[i] + "PinningChannel_alpha11", exitMessageHandler)
- .catch(() => onError('An error occurred when unsubscribing to the workspace.'))
- }
-}
-const publishImmediatePin = (hash) => {
- const data = Buffer.from(hash)
- for (var i = 0; i < PeersForChannel.length; i++) {
- var channel = PeersForChannel[i] + "ImmediatePinningChannel_alpha11";
- node.pubsub.publish(channel, data)
- .catch(() => onError('An error occurred when publishing the message.'))
- }
-}
-
-/* ===========================================================================
- Files handling
- =========================================================================== */
-
-const isFileInList = (hash) => FILES.indexOf(hash) !== -1
-
-const sendFileList = () => FILES.forEach((hash) => publishHash(hash))
-
-const updateProgress = (bytesLoaded) => {
- let percent = 100 - ((bytesLoaded / fileSize) * 100)
- if (percent <= 5) {
- document.getElementById("upload-confirm-button").style.visibility = "visible";
- }
- $progressBar.style.transform = `translateX(${-percent}%)`
-}
-
-const resetProgress = () => {
- $progressBar.style.transform = 'translateX(-100%)'
-}
-
-function appendFile(name, hash, size, data) {
- const file = new window.Blob([data], {
- type: 'application/octet-binary'
- })
- const url = window.URL.createObjectURL(file)
- const row = document.createElement('tr')
-
- const nameCell = document.createElement('td')
- nameCell.innerHTML = name
-
- const hashCell = document.createElement('td')
- hashCell.innerHTML = hash
-
- const sizeCell = document.createElement('td')
- sizeCell.innerText = size
-
- const downloadCell = document.createElement('td')
- const link = document.createElement('a')
- link.setAttribute('href', url)
- link.setAttribute('download', name)
- link.innerHTML = '
'
- downloadCell.appendChild(link)
-
- row.appendChild(nameCell)
- row.appendChild(hashCell)
- row.appendChild(sizeCell)
- row.appendChild(downloadCell)
-
- $fileHistory.insertBefore(row, $fileHistory.firstChild)
-}
-
-function resetFileTable() {
- while ($fileHistory.hasChildNodes()) {
- $fileHistory.removeChild($fileHistory.firstChild);
- }
-}
-/* Drag & Drop
- =========================================================================== */
-
-const onDragEnter = (event) => $dragContainer.classList.add('dragging')
-const onDragLeave = () => $dragContainer.classList.remove('dragging')
-
-window.startUploadProcess = function() {
- $('#preparingUploadModal').modal('show');
- var streamFinishCount = 0;
- for (var i = 0; i < MainFileArray.length; i++) {
- const streamFiles = (files) => {
- const stream = node.addReadableStream()
- stream.on('data', function(data) {
- GlobalHashArray.push(`${data.hash}`);
- GlobalSizeArray.push(`${data.size}`);
- GlobalPathArray.push(`${data.path}`);
- GlobalUploadHash = `${data.hash}`;
- GlobalUploadPath = `${data.path}`;
- var splitString = GlobalUploadPath.split("/")
- if (splitString.length == 1 || splitString[0] == "") {
- streamFinishCount++;
- GlobalMainHashArray.push(`${data.hash}`);
- GlobalMainPathArray.push(`${data.path}`);
- if (streamFinishCount == MainFileArray.length) {
- createMainHash();
- }
- }
- });
- files.forEach(file => stream.write(file))
- stream.end()
- }
- var filesForStream = MainFileArray[i];
- streamFiles(filesForStream);
- }
-
- const streamFilesExternally = (filesArray, MainHashArray) => {
-
- var confirmationServers = ["https://ipfsapi.ethofs.com/ipfs/", "https://ipfsapi1.ethofs.com/ipfs/", "https://ipfsapi2.ethofs.com/ipfs/", "https://ipfsapi5.ethofs.com/ipfs/", "https://ipfsapi6.ethofs.com/ipfs/", "https://ipfsapi7.ethofs.com/ipfs/"];
- let hashVerificationArray = [...GlobalHashArray, ...GlobalMainHashArray];
- hashVerificationArray.push(GlobalMainContentHash);
- var hashConfirmationCount = 0;
-
-
- for (var i = 0; i < MainHashArray.length; i++) {
- console.log("Sending Immediate Pin Request: " + MainHashArray[i]);
- publishImmediatePin(MainHashArray[i]);
- }
- setTimeout(function() {
- hashVerificationArray.forEach(function(hash) {
- verifyDataUpload(hash);
- });
- }, 5000);
-
- const verifyDataUpload = async hash => {
- var confirmationServer = confirmationServers[Math.floor(Math.random() * confirmationServers.length)];
- var url = confirmationServer + hash;
- try {
- const response = await fetch(url);
- console.log("Data Confirmation Status: " + response.status + " Hash: " + hash);
- if (response.status == 200) {
- hashConfirmationCount++;
- var confirmationPercentage = Math.ceil((hashConfirmationCount / hashVerificationArray.length) * 100);
- updateUploadProgress(confirmationPercentage);
- console.log("Data Upload Confirmation Received: " + hashConfirmationCount + "/" + hashVerificationArray.length);
- $uploadMessage.innerText = "Upload Confirmation Received: " + hashConfirmationCount + "/" + hashVerificationArray.length;
- if (confirmationPercentage >= 99) {
- $uploadMessage.innerText = "Upload Complete";
- document.getElementById("upload-status-message").textContent = "Complete";
- finishUploadModal();
- }
- } else {
- setTimeout(function() {
- verifyDataUpload(hash)
- }, 2000);
- }
- } catch (error) {
- console.log(error);
- console.log("Data Confirmation Error: " + error.status);
- setTimeout(function() {
- verifyDataUpload(hash)
- }, 2000);
- }
- };
- }
-
- function updateUploadProgress(width) {
- var elem = document.getElementById("myBar");
- width = round(width, 2);
- if (width >= 100) {
- width = 100;
- elem.style.width = width + '%';
- elem.innerHTML = width * 1 + '%';
- }
- elem.style.width = width + '%';
- elem.innerHTML = width * 1 + '%';
- }
-
- function createMainHash() {
- var contentHashString = GlobalChannelString;
- for (i = 0; i < GlobalMainHashArray.length; i++) {
- contentHashString += ":" + GlobalMainHashArray[i];
- }
- node.add(Buffer.from(contentHashString), (err, res) => {
- if (err || !res) {
- return console.error('ipfs add error', err, res)
- }
- res.forEach((file) => {
- if (file && file.hash) {
- GlobalMainContentHash = file.hash;
- AddNewPin(GlobalUploadHash, GlobalUploadSize, document.getElementById('newcontractname').value, GlobalContractDuration);
- }
- });
- });
- }
-
- /*****************************************************************************/
- function AddNewPin(pinToAdd, pinSize, HostingContractName, HostingContractDuration) {
- var contentHashString = GlobalChannelString;
- var contentPathString = GlobalChannelString;
- for (i = 0; i < GlobalMainHashArray.length; i++) {
- contentHashString += ":" + GlobalMainHashArray[i];
- contentPathString += ":" + GlobalMainPathArray[i];
- }
- var MainHashArray = GlobalMainHashArray;
- GlobalUploadName = HostingContractName;
- var contractCost = calculateCost(pinSize, HostingContractDuration, GlobalHostingCostWei);
- var pinAdding = new web3.eth.Contract(GlobalControllerABI, GlobalControllerContractAddress);
- const transactionObject = {
- from: GlobalUserAddress,
- value: contractCost
- };
- $('#preparingUploadModal').modal('hide');
- console.log("Contract Address: " + GlobalControllerContractAddress + " Value: " + contractCost);
- if (privateKeyLogin == true) {
- const tx = {
- to: GlobalControllerContractAddress,
- from: GlobalUserAddress,
- value: contractCost,
- gas: 4000000,
- data: pinAdding.methods.AddNewContract(GlobalMainContentHash, HostingContractName, HostingContractDuration, pinSize, pinSize, contentHashString, contentPathString).encodeABI()
- };
- var privateKey = '0x' + GlobalPrivateKey;
- console.log("Private Key: " + privateKey);
- web3.eth.accounts.signTransaction(tx, privateKey)
- .then(function(signedTransactionData) {
- console.log("Signed TX Data: " + signedTransactionData.rawTransaction);
- web3.eth.sendSignedTransaction(signedTransactionData.rawTransaction, function(error, result) {
- if (!error) {
- if (result) {
- console.log("Result: " + result);
- $('#minedBlockTrackerModal').modal('show');
- waitForReceipt(result, function(receipt) {
- console.log("Transaction Has Been Mined: " + receipt);
- $('#minedBlockTrackerModal').modal('hide');
- $('#nodeModal').modal('hide');
- var filesForStream = MainFileArray;
- streamFilesExternally(filesForStream, MainHashArray);
- checkForUploadedContentAvailability(HostingContractName);
- });
- } else {
- console.log("There was a problem adding new contract");
- }
- } else {
- console.error(error);
- }
- });
- });
- } else {
- pinAdding.methods.AddNewContract(GlobalMainContentHash, HostingContractName, HostingContractDuration, pinSize, pinSize, contentHashString, contentPathString).send(transactionObject, function(error, result) {
- if (!error) {
- if (result) {
- $('#minedBlockTrackerModal').modal('show');
- waitForReceipt(result, function(receipt) {
- console.log("Transaction Has Been Mined: " + receipt);
- $('#minedBlockTrackerModal').modal('hide');
- $('#nodeModal').modal('hide');
- var filesForStream = MainFileArray;
- streamFilesExternally(filesForStream, MainHashArray);
- checkForUploadedContentAvailability(HostingContractName);
- });
- } else {
- console.log("There was a problem adding new contract");
- }
- } else {
- console.error(error);
- }
- });
- }
- }
- /*****************************************************************************/
-}
-
-function resetUploadProcess() {
- MainFileArray = new Array();
- GlobalUploadSize = 0;
-}
-
-function updateAnalyzeProgress(width) {
- var elem = document.getElementById("myAnalyzeBar");
- width = round(width, 2);
- if (width >= 100) {
- width = 100;
- elem.style.width = width + '%';
- elem.innerHTML = width * 1 + '%';
- }
- elem.style.width = width + '%';
- elem.innerHTML = width * 1 + '%';
-}
-
-function onFileUpload(event) {
- document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA";
- document.getElementById("upload-confirm-button").style.visibility = "hidden";
- MainFileArray.push([]);
- let filesUploaded = event.target.files;
- var streamCompareCount = filesUploaded.length;
- for (let i = 0; filesUploaded.length > i; i++) {
- handleFile(filesUploaded[i]);
- }
-
- function readFileContents(file) {
- return new Promise((resolve) => {
- const reader = new window.FileReader()
- reader.onload = (event) => resolve(event.target.result)
- reader.readAsArrayBuffer(file)
- })
- }
-
- function handleFile(file) {
- readFileContents(file).then((buffer) => {
- var filePath = file.webkitRelativePath;
- var filetowrite = {
- path: filePath,
- content: Buffer.from(buffer)
- };
- MainFileArray[MainFileArray.length - 1].push(filetowrite);
- GlobalUploadSize += Number(file.size);
- fileSize += Number(file.size);
- var totalUploadSizeMB = GlobalUploadSize / 1000000;
- appendFile(filePath, file.name, file.size, null);
- console.log("Path: " + filePath + " Size: " + file.size + " Total Size: " + GlobalUploadSize);
- document.getElementById("upload-size").textContent = totalUploadSizeMB;
- contractDurationChange(document.getElementById('contract-duration').value);
- streamCompareCount--;
- updateAnalyzeProgress(((filesUploaded.length - streamCompareCount) / filesUploaded.length));
- if (streamCompareCount == 0) {
- document.getElementById("upload-hash").textContent = "READY FOR UPLOAD";
- document.getElementById("upload-confirm-button").style.visibility = "visible";
- }
- });
- }
-}
-
-function onDrop(event) {
- MainFileArray.push([]);
- document.getElementById("upload-hash").textContent = "ANALYZING UPLOAD DATA";
- document.getElementById("upload-confirm-button").style.visibility = "hidden";
- fileSize = 0;
- resetProgress();
- onDragLeave()
- event.preventDefault()
- if (GlobalUploadHash != "" && GlobalUploadPath != "") {
- GlobalMainHashArray.push(GlobalUploadHash);
- GlobalMainPathArray.push(GlobalUploadPath);
- }
- const dt = event.dataTransfer
- const filesDropped = dt.files
- const itemsDropped = dt.items
-
- function readFileContents(file) {
- return new Promise((resolve) => {
- const reader = new window.FileReader()
- reader.onload = (event) => resolve(event.target.result)
- reader.readAsArrayBuffer(file)
- })
- }
- var totalItemCount = 0;
- var streamCompareCount = 0;
-
- function initialHandleItems(items) {
- const files = [];
- totalItemCount = items.length;
- streamCompareCount = items.length;
- for (var item of items) {
- var awaitHandleEntry = handleEntry(item.webkitGetAsEntry());
- }
-
- function handleEntry(entry) {
- if (entry.isFile) {
- getFile(entry);
-
- function getFile(entry) {
- entry.file(function(file) {
- readFileContents(file)
- .then((buffer) => {
- var filePath = entry.fullPath;
- var filetowrite = {
- path: entry.fullPath,
- content: Buffer.from(buffer)
- };
- MainFileArray[MainFileArray.length - 1].push(filetowrite);
- GlobalUploadSize += Number(file.size);
- fileSize += Number(file.size);
- var totalUploadSizeMB = GlobalUploadSize / 1000000;
- appendFile(entry.fullPath, entry.name, file.size, null);
- document.getElementById("upload-size").textContent = totalUploadSizeMB;
- contractDurationChange(document.getElementById('contract-duration').value);
- streamCompareCount--;
- updateAnalyzeProgress(((totalItemCount - streamCompareCount) / totalItemCount));
- if (streamCompareCount == 0) {
- document.getElementById("upload-hash").textContent = "READY FOR UPLOAD";
- document.getElementById("upload-confirm-button").style.visibility = "visible";
- }
- });
- });
- }
-
- } else if (entry.isDirectory) {
- let directoryReader = entry.createReader();
- directoryReader.readEntries(function(entries) {
- streamCompareCount += entries.length - 1;
- totalItemCount += entries.length - 1;
- entries.forEach(function(newEntry) {
- handleEntry(newEntry);
- });
- });
- }
- }
-
- }
- initialHandleItems(event.dataTransfer.items);
-}
-
-/* ===========================================================================
- Peers handling
- =========================================================================== */
-
-function connectToPeer(event) {
- const multiaddr = $multiaddrInput.value
-
- if (!multiaddr) {
- return onError('No multiaddr was inserted.')
- }
-
- node.swarm.connect(multiaddr)
- .then(() => {
- onSuccess(`Successfully connected to peer.`)
- $multiaddrInput.value = ''
- })
- .catch(() => onError('An error occurred when connecting to the peer.'))
-}
-
-function updatePeerProgress(width, peercount) {
- var backgroundcolor = "";
- var elem = document.getElementById("myPeerBar");
- width = round(width, 2);
- if (width >= 100) {
- width = 100;
- }
- if (width >= 80) {
- backgroundcolor = '"#3CB371"';
- } else if (width >= 40 && width < 80) {
- backgroundcolor = '"#FFFF00"';
- } else {
- backgroundcolor = '"#FF0000"';
- }
- elem.style.width = width + '%';
-}
-
-function refreshPeerList() {
- var updatedPeerCount = 0;
- node.swarm.peers()
- .then((peers) => {
- const peersAsHtml = peers.reverse()
- .map((peer) => {
- if (peer.addr) {
- const addr = peer.addr.toString()
- if (addr.indexOf('ipfs') >= 0) {
- return addr
- } else {
- return addr + peer.peer.id.toB58String()
- }
- }
- })
- .map((addr) => {
- var splitString = addr.split("/");
- addr = splitString[splitString.length - 1];
- updatedPeerCount++;
- if (!PeersForChannel.includes(addr)) {
- PeersForChannel.push(addr);
- }
- return `| ${addr} |
`
- }).join('')
-
- }).then(() => {
- updatePeerProgress(((updatedPeerCount / 7) * 100), updatedPeerCount)
- })
- .catch((error) => onError(error))
-}
-
-/* ===========================================================================
- Error handling
- =========================================================================== */
-
-function onSuccess(msg) {
- $logs.classList.add('success')
- $logs.innerHTML = msg
-}
-
-function onError(err) {
- let msg = 'An error occured, check the dev console'
-
- if (err.stack !== undefined) {
- msg = err.stack
- } else if (typeof err === 'string') {
- msg = err
- }
-
- $logs.classList.remove('success')
- $logs.innerHTML = msg
-}
-
-window.onerror = onError
-
-/* ===========================================================================
- App states
- =========================================================================== */
-
-const states = {
- ready: () => {
- const addressesHtml = info.addresses.map((address) => {
- return `${address}`
- }).join('')
- $nodeId.innerText = info.id
- $allDisabledButtons.forEach(b => {
- b.disabled = false
- })
- $allDisabledInputs.forEach(b => {
- b.disabled = false
- })
- $allDisabledElements.forEach(el => {
- el.classList.remove('disabled')
- })
- }
-}
-
-function updateView(state, ipfs) {
- if (states[state] !== undefined) {
- states[state]()
- } else {
- throw new Error('Could not find state "' + state + '"')
- }
-}
-/* ===========================================================================
- Boot the app
- =========================================================================== */
-window.startApplication = function() {
- // Setup event listeners
- $dragContainer.addEventListener('dragenter', onDragEnter)
- $dragContainer.addEventListener('dragover', onDragEnter)
- $dragContainer.addEventListener('drop', onDrop)
- $dragContainer.addEventListener('dragleave', onDragLeave)
- document.getElementById("fileUploadButton").addEventListener("change", onFileUpload)
+window.startNode = function() {
start()
- extendedStartApplication()
}
-
-function extendedStartApplication() {
- $ethomessage.innerText = GlobalUserAddress;
-}
-window.stopApplication = function() {
- resetUploadProcess();
- resetFileTable();
-}
-
-}).call(this,require('_process'))
-},{"_process":1438,"buffer":217,"ethereum-private-key-to-address":336,"ethereumjs-common":355,"fs":212,"ipfs":692,"libp2p-pnet":1094,"node-fetch":1359,"pull-file-reader":1471,"request":1572,"web3":1839}],2:[function(require,module,exports){
+}).call(this,require('_process'),require("buffer").Buffer)
+},{"_process":1258,"buffer":181,"ipfs":538,"libp2p-pnet":931}],2:[function(require,module,exports){
/*globals self, window */
"use strict"
@@ -934,7 +258,7 @@ AbstractIterator.prototype._end = function (callback) {
module.exports = AbstractIterator
}).call(this,require('_process'))
-},{"_process":1438}],5:[function(require,module,exports){
+},{"_process":1258}],5:[function(require,module,exports){
(function (Buffer,process){
var xtend = require('xtend')
var supports = require('level-supports')
@@ -1253,12 +577,33 @@ AbstractLevelDOWN.prototype._checkValue = function (value) {
module.exports = AbstractLevelDOWN
}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
-},{"../is-buffer/index.js":766,"./abstract-chained-batch":3,"./abstract-iterator":4,"_process":1438,"level-supports":869,"xtend":1860}],6:[function(require,module,exports){
+},{"../is-buffer/index.js":608,"./abstract-chained-batch":3,"./abstract-iterator":4,"_process":1258,"level-supports":708,"xtend":7}],6:[function(require,module,exports){
exports.AbstractLevelDOWN = require('./abstract-leveldown')
exports.AbstractIterator = require('./abstract-iterator')
exports.AbstractChainedBatch = require('./abstract-chained-batch')
},{"./abstract-chained-batch":3,"./abstract-iterator":4,"./abstract-leveldown":5}],7:[function(require,module,exports){
+module.exports = extend
+
+var hasOwnProperty = Object.prototype.hasOwnProperty;
+
+function extend() {
+ var target = {}
+
+ for (var i = 0; i < arguments.length; i++) {
+ var source = arguments[i]
+
+ for (var key in source) {
+ if (hasOwnProperty.call(source, key)) {
+ target[key] = source[key]
+ }
+ }
+ }
+
+ return target
+}
+
+},{}],8:[function(require,module,exports){
module.exports = after
function after(count, callback, err_cb) {
@@ -1288,5836 +633,7 @@ function after(count, callback, err_cb) {
function noop() {}
-},{}],8:[function(require,module,exports){
-'use strict';
-
-var compileSchema = require('./compile')
- , resolve = require('./compile/resolve')
- , Cache = require('./cache')
- , SchemaObject = require('./compile/schema_obj')
- , stableStringify = require('fast-json-stable-stringify')
- , formats = require('./compile/formats')
- , rules = require('./compile/rules')
- , $dataMetaSchema = require('./data')
- , util = require('./compile/util');
-
-module.exports = Ajv;
-
-Ajv.prototype.validate = validate;
-Ajv.prototype.compile = compile;
-Ajv.prototype.addSchema = addSchema;
-Ajv.prototype.addMetaSchema = addMetaSchema;
-Ajv.prototype.validateSchema = validateSchema;
-Ajv.prototype.getSchema = getSchema;
-Ajv.prototype.removeSchema = removeSchema;
-Ajv.prototype.addFormat = addFormat;
-Ajv.prototype.errorsText = errorsText;
-
-Ajv.prototype._addSchema = _addSchema;
-Ajv.prototype._compile = _compile;
-
-Ajv.prototype.compileAsync = require('./compile/async');
-var customKeyword = require('./keyword');
-Ajv.prototype.addKeyword = customKeyword.add;
-Ajv.prototype.getKeyword = customKeyword.get;
-Ajv.prototype.removeKeyword = customKeyword.remove;
-Ajv.prototype.validateKeyword = customKeyword.validate;
-
-var errorClasses = require('./compile/error_classes');
-Ajv.ValidationError = errorClasses.Validation;
-Ajv.MissingRefError = errorClasses.MissingRef;
-Ajv.$dataMetaSchema = $dataMetaSchema;
-
-var META_SCHEMA_ID = 'http://json-schema.org/draft-07/schema';
-
-var META_IGNORE_OPTIONS = [ 'removeAdditional', 'useDefaults', 'coerceTypes', 'strictDefaults' ];
-var META_SUPPORT_DATA = ['/properties'];
-
-/**
- * Creates validator instance.
- * Usage: `Ajv(opts)`
- * @param {Object} opts optional options
- * @return {Object} ajv instance
- */
-function Ajv(opts) {
- if (!(this instanceof Ajv)) return new Ajv(opts);
- opts = this._opts = util.copy(opts) || {};
- setLogger(this);
- this._schemas = {};
- this._refs = {};
- this._fragments = {};
- this._formats = formats(opts.format);
-
- this._cache = opts.cache || new Cache;
- this._loadingSchemas = {};
- this._compilations = [];
- this.RULES = rules();
- this._getId = chooseGetId(opts);
-
- opts.loopRequired = opts.loopRequired || Infinity;
- if (opts.errorDataPath == 'property') opts._errorDataPathProperty = true;
- if (opts.serialize === undefined) opts.serialize = stableStringify;
- this._metaOpts = getMetaSchemaOptions(this);
-
- if (opts.formats) addInitialFormats(this);
- addDefaultMetaSchema(this);
- if (typeof opts.meta == 'object') this.addMetaSchema(opts.meta);
- if (opts.nullable) this.addKeyword('nullable', {metaSchema: {type: 'boolean'}});
- addInitialSchemas(this);
-}
-
-
-
-/**
- * Validate data using schema
- * Schema will be compiled and cached (using serialized JSON as key. [fast-json-stable-stringify](https://github.com/epoberezkin/fast-json-stable-stringify) is used to serialize.
- * @this Ajv
- * @param {String|Object} schemaKeyRef key, ref or schema object
- * @param {Any} data to be validated
- * @return {Boolean} validation result. Errors from the last validation will be available in `ajv.errors` (and also in compiled schema: `schema.errors`).
- */
-function validate(schemaKeyRef, data) {
- var v;
- if (typeof schemaKeyRef == 'string') {
- v = this.getSchema(schemaKeyRef);
- if (!v) throw new Error('no schema with key or ref "' + schemaKeyRef + '"');
- } else {
- var schemaObj = this._addSchema(schemaKeyRef);
- v = schemaObj.validate || this._compile(schemaObj);
- }
-
- var valid = v(data);
- if (v.$async !== true) this.errors = v.errors;
- return valid;
-}
-
-
-/**
- * Create validating function for passed schema.
- * @this Ajv
- * @param {Object} schema schema object
- * @param {Boolean} _meta true if schema is a meta-schema. Used internally to compile meta schemas of custom keywords.
- * @return {Function} validating function
- */
-function compile(schema, _meta) {
- var schemaObj = this._addSchema(schema, undefined, _meta);
- return schemaObj.validate || this._compile(schemaObj);
-}
-
-
-/**
- * Adds schema to the instance.
- * @this Ajv
- * @param {Object|Array} schema schema or array of schemas. If array is passed, `key` and other parameters will be ignored.
- * @param {String} key Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`.
- * @param {Boolean} _skipValidation true to skip schema validation. Used internally, option validateSchema should be used instead.
- * @param {Boolean} _meta true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
- * @return {Ajv} this for method chaining
- */
-function addSchema(schema, key, _skipValidation, _meta) {
- if (Array.isArray(schema)){
- for (var i=0; i} errors optional array of validation errors, if not passed errors from the instance are used.
- * @param {Object} options optional options with properties `separator` and `dataVar`.
- * @return {String} human readable string with all errors descriptions
- */
-function errorsText(errors, options) {
- errors = errors || this.errors;
- if (!errors) return 'No errors';
- options = options || {};
- var separator = options.separator === undefined ? ', ' : options.separator;
- var dataVar = options.dataVar === undefined ? 'data' : options.dataVar;
-
- var text = '';
- for (var i=0; i%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i;
-// For the source: https://gist.github.com/dperini/729294
-// For test cases: https://mathiasbynens.be/demo/url-regex
-// @todo Delete current URL in favour of the commented out URL rule when this issue is fixed https://github.com/eslint/eslint/issues/7983.
-// var URL = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu;
-var URL = /^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-?)*(?:[0-9KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[KSa-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i;
-var UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i;
-var JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/;
-var JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i;
-var RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;
-
-
-module.exports = formats;
-
-function formats(mode) {
- mode = mode == 'full' ? 'full' : 'fast';
- return util.copy(formats[mode]);
-}
-
-
-formats.fast = {
- // date: http://tools.ietf.org/html/rfc3339#section-5.6
- date: /^\d\d\d\d-[0-1]\d-[0-3]\d$/,
- // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
- time: /^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)?$/i,
- 'date-time': /^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d:\d\d)$/i,
- // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
- uri: /^(?:[a-z][a-z0-9+-.]*:)(?:\/?\/)?[^\s]*$/i,
- 'uri-reference': /^(?:(?:[a-z][a-z0-9+-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
- 'uri-template': URITEMPLATE,
- url: URL,
- // email (sources from jsen validator):
- // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
- // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'willful violation')
- email: /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i,
- hostname: HOSTNAME,
- // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
- ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
- // optimized http://stackoverflow.com/questions/53497/regular-expression-that-matches-valid-ipv6-addresses
- ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
- regex: regex,
- // uuid: http://tools.ietf.org/html/rfc4122
- uuid: UUID,
- // JSON-pointer: https://tools.ietf.org/html/rfc6901
- // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
- 'json-pointer': JSON_POINTER,
- 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
- // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
- 'relative-json-pointer': RELATIVE_JSON_POINTER
-};
-
-
-formats.full = {
- date: date,
- time: time,
- 'date-time': date_time,
- uri: uri,
- 'uri-reference': URIREF,
- 'uri-template': URITEMPLATE,
- url: URL,
- email: /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,
- hostname: hostname,
- ipv4: /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,
- ipv6: /^\s*(?:(?:(?:[0-9a-f]{1,4}:){7}(?:[0-9a-f]{1,4}|:))|(?:(?:[0-9a-f]{1,4}:){6}(?::[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){5}(?:(?:(?::[0-9a-f]{1,4}){1,2})|:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(?:(?:[0-9a-f]{1,4}:){4}(?:(?:(?::[0-9a-f]{1,4}){1,3})|(?:(?::[0-9a-f]{1,4})?:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){3}(?:(?:(?::[0-9a-f]{1,4}){1,4})|(?:(?::[0-9a-f]{1,4}){0,2}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){2}(?:(?:(?::[0-9a-f]{1,4}){1,5})|(?:(?::[0-9a-f]{1,4}){0,3}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?:(?:[0-9a-f]{1,4}:){1}(?:(?:(?::[0-9a-f]{1,4}){1,6})|(?:(?::[0-9a-f]{1,4}){0,4}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(?::(?:(?:(?::[0-9a-f]{1,4}){1,7})|(?:(?::[0-9a-f]{1,4}){0,5}:(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(?:%.+)?\s*$/i,
- regex: regex,
- uuid: UUID,
- 'json-pointer': JSON_POINTER,
- 'json-pointer-uri-fragment': JSON_POINTER_URI_FRAGMENT,
- 'relative-json-pointer': RELATIVE_JSON_POINTER
-};
-
-
-function isLeapYear(year) {
- // https://tools.ietf.org/html/rfc3339#appendix-C
- return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
-}
-
-
-function date(str) {
- // full-date from http://tools.ietf.org/html/rfc3339#section-5.6
- var matches = str.match(DATE);
- if (!matches) return false;
-
- var year = +matches[1];
- var month = +matches[2];
- var day = +matches[3];
-
- return month >= 1 && month <= 12 && day >= 1 &&
- day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month]);
-}
-
-
-function time(str, full) {
- var matches = str.match(TIME);
- if (!matches) return false;
-
- var hour = matches[1];
- var minute = matches[2];
- var second = matches[3];
- var timeZone = matches[5];
- return ((hour <= 23 && minute <= 59 && second <= 59) ||
- (hour == 23 && minute == 59 && second == 60)) &&
- (!full || timeZone);
-}
-
-
-var DATE_TIME_SEPARATOR = /t|\s/i;
-function date_time(str) {
- // http://tools.ietf.org/html/rfc3339#section-5.6
- var dateTime = str.split(DATE_TIME_SEPARATOR);
- return dateTime.length == 2 && date(dateTime[0]) && time(dateTime[1], true);
-}
-
-
-function hostname(str) {
- // https://tools.ietf.org/html/rfc1034#section-3.5
- // https://tools.ietf.org/html/rfc1123#section-2
- return str.length <= 255 && HOSTNAME.test(str);
-}
-
-
-var NOT_URI_FRAGMENT = /\/|:/;
-function uri(str) {
- // http://jmrware.com/articles/2009/uri_regexp/URI_regex.html + optional protocol + required "."
- return NOT_URI_FRAGMENT.test(str) && URI.test(str);
-}
-
-
-var Z_ANCHOR = /[^\\]\\Z/;
-function regex(str) {
- if (Z_ANCHOR.test(str)) return false;
- try {
- new RegExp(str);
- return true;
- } catch(e) {
- return false;
- }
-}
-
-},{"./util":18}],13:[function(require,module,exports){
-'use strict';
-
-var resolve = require('./resolve')
- , util = require('./util')
- , errorClasses = require('./error_classes')
- , stableStringify = require('fast-json-stable-stringify');
-
-var validateGenerator = require('../dotjs/validate');
-
-/**
- * Functions below are used inside compiled validations function
- */
-
-var ucs2length = util.ucs2length;
-var equal = require('fast-deep-equal');
-
-// this error is thrown by async schemas to return validation errors via exception
-var ValidationError = errorClasses.Validation;
-
-module.exports = compile;
-
-
-/**
- * Compiles schema to validation function
- * @this Ajv
- * @param {Object} schema schema object
- * @param {Object} root object with information about the root schema for this schema
- * @param {Object} localRefs the hash of local references inside the schema (created by resolve.id), used for inline resolution
- * @param {String} baseId base ID for IDs in the schema
- * @return {Function} validation function
- */
-function compile(schema, root, localRefs, baseId) {
- /* jshint validthis: true, evil: true */
- /* eslint no-shadow: 0 */
- var self = this
- , opts = this._opts
- , refVal = [ undefined ]
- , refs = {}
- , patterns = []
- , patternsHash = {}
- , defaults = []
- , defaultsHash = {}
- , customRules = [];
-
- root = root || { schema: schema, refVal: refVal, refs: refs };
-
- var c = checkCompiling.call(this, schema, root, baseId);
- var compilation = this._compilations[c.index];
- if (c.compiling) return (compilation.callValidate = callValidate);
-
- var formats = this._formats;
- var RULES = this.RULES;
-
- try {
- var v = localCompile(schema, root, localRefs, baseId);
- compilation.validate = v;
- var cv = compilation.callValidate;
- if (cv) {
- cv.schema = v.schema;
- cv.errors = null;
- cv.refs = v.refs;
- cv.refVal = v.refVal;
- cv.root = v.root;
- cv.$async = v.$async;
- if (opts.sourceCode) cv.source = v.source;
- }
- return v;
- } finally {
- endCompiling.call(this, schema, root, baseId);
- }
-
- /* @this {*} - custom context, see passContext option */
- function callValidate() {
- /* jshint validthis: true */
- var validate = compilation.validate;
- var result = validate.apply(this, arguments);
- callValidate.errors = validate.errors;
- return result;
- }
-
- function localCompile(_schema, _root, localRefs, baseId) {
- var isRoot = !_root || (_root && _root.schema == _schema);
- if (_root.schema != root.schema)
- return compile.call(self, _schema, _root, localRefs, baseId);
-
- var $async = _schema.$async === true;
-
- var sourceCode = validateGenerator({
- isTop: true,
- schema: _schema,
- isRoot: isRoot,
- baseId: baseId,
- root: _root,
- schemaPath: '',
- errSchemaPath: '#',
- errorPath: '""',
- MissingRefError: errorClasses.MissingRef,
- RULES: RULES,
- validate: validateGenerator,
- util: util,
- resolve: resolve,
- resolveRef: resolveRef,
- usePattern: usePattern,
- useDefault: useDefault,
- useCustomRule: useCustomRule,
- opts: opts,
- formats: formats,
- logger: self.logger,
- self: self
- });
-
- sourceCode = vars(refVal, refValCode) + vars(patterns, patternCode)
- + vars(defaults, defaultCode) + vars(customRules, customRuleCode)
- + sourceCode;
-
- if (opts.processCode) sourceCode = opts.processCode(sourceCode);
- // console.log('\n\n\n *** \n', JSON.stringify(sourceCode));
- var validate;
- try {
- var makeValidate = new Function(
- 'self',
- 'RULES',
- 'formats',
- 'root',
- 'refVal',
- 'defaults',
- 'customRules',
- 'equal',
- 'ucs2length',
- 'ValidationError',
- sourceCode
- );
-
- validate = makeValidate(
- self,
- RULES,
- formats,
- root,
- refVal,
- defaults,
- customRules,
- equal,
- ucs2length,
- ValidationError
- );
-
- refVal[0] = validate;
- } catch(e) {
- self.logger.error('Error compiling schema, function code:', sourceCode);
- throw e;
- }
-
- validate.schema = _schema;
- validate.errors = null;
- validate.refs = refs;
- validate.refVal = refVal;
- validate.root = isRoot ? validate : _root;
- if ($async) validate.$async = true;
- if (opts.sourceCode === true) {
- validate.source = {
- code: sourceCode,
- patterns: patterns,
- defaults: defaults
- };
- }
-
- return validate;
- }
-
- function resolveRef(baseId, ref, isRoot) {
- ref = resolve.url(baseId, ref);
- var refIndex = refs[ref];
- var _refVal, refCode;
- if (refIndex !== undefined) {
- _refVal = refVal[refIndex];
- refCode = 'refVal[' + refIndex + ']';
- return resolvedRef(_refVal, refCode);
- }
- if (!isRoot && root.refs) {
- var rootRefId = root.refs[ref];
- if (rootRefId !== undefined) {
- _refVal = root.refVal[rootRefId];
- refCode = addLocalRef(ref, _refVal);
- return resolvedRef(_refVal, refCode);
- }
- }
-
- refCode = addLocalRef(ref);
- var v = resolve.call(self, localCompile, root, ref);
- if (v === undefined) {
- var localSchema = localRefs && localRefs[ref];
- if (localSchema) {
- v = resolve.inlineRef(localSchema, opts.inlineRefs)
- ? localSchema
- : compile.call(self, localSchema, root, localRefs, baseId);
- }
- }
-
- if (v === undefined) {
- removeLocalRef(ref);
- } else {
- replaceLocalRef(ref, v);
- return resolvedRef(v, refCode);
- }
- }
-
- function addLocalRef(ref, v) {
- var refId = refVal.length;
- refVal[refId] = v;
- refs[ref] = refId;
- return 'refVal' + refId;
- }
-
- function removeLocalRef(ref) {
- delete refs[ref];
- }
-
- function replaceLocalRef(ref, v) {
- var refId = refs[ref];
- refVal[refId] = v;
- }
-
- function resolvedRef(refVal, code) {
- return typeof refVal == 'object' || typeof refVal == 'boolean'
- ? { code: code, schema: refVal, inline: true }
- : { code: code, $async: refVal && !!refVal.$async };
- }
-
- function usePattern(regexStr) {
- var index = patternsHash[regexStr];
- if (index === undefined) {
- index = patternsHash[regexStr] = patterns.length;
- patterns[index] = regexStr;
- }
- return 'pattern' + index;
- }
-
- function useDefault(value) {
- switch (typeof value) {
- case 'boolean':
- case 'number':
- return '' + value;
- case 'string':
- return util.toQuotedString(value);
- case 'object':
- if (value === null) return 'null';
- var valueStr = stableStringify(value);
- var index = defaultsHash[valueStr];
- if (index === undefined) {
- index = defaultsHash[valueStr] = defaults.length;
- defaults[index] = value;
- }
- return 'default' + index;
- }
- }
-
- function useCustomRule(rule, schema, parentSchema, it) {
- if (self._opts.validateSchema !== false) {
- var deps = rule.definition.dependencies;
- if (deps && !deps.every(function(keyword) {
- return Object.prototype.hasOwnProperty.call(parentSchema, keyword);
- }))
- throw new Error('parent schema must have all required keywords: ' + deps.join(','));
-
- var validateSchema = rule.definition.validateSchema;
- if (validateSchema) {
- var valid = validateSchema(schema);
- if (!valid) {
- var message = 'keyword schema is invalid: ' + self.errorsText(validateSchema.errors);
- if (self._opts.validateSchema == 'log') self.logger.error(message);
- else throw new Error(message);
- }
- }
- }
-
- var compile = rule.definition.compile
- , inline = rule.definition.inline
- , macro = rule.definition.macro;
-
- var validate;
- if (compile) {
- validate = compile.call(self, schema, parentSchema, it);
- } else if (macro) {
- validate = macro.call(self, schema, parentSchema, it);
- if (opts.validateSchema !== false) self.validateSchema(validate, true);
- } else if (inline) {
- validate = inline.call(self, it, rule.keyword, schema, parentSchema);
- } else {
- validate = rule.definition.validate;
- if (!validate) return;
- }
-
- if (validate === undefined)
- throw new Error('custom keyword "' + rule.keyword + '"failed to compile');
-
- var index = customRules.length;
- customRules[index] = validate;
-
- return {
- code: 'customRule' + index,
- validate: validate
- };
- }
-}
-
-
-/**
- * Checks if the schema is currently compiled
- * @this Ajv
- * @param {Object} schema schema to compile
- * @param {Object} root root object
- * @param {String} baseId base schema ID
- * @return {Object} object with properties "index" (compilation index) and "compiling" (boolean)
- */
-function checkCompiling(schema, root, baseId) {
- /* jshint validthis: true */
- var index = compIndex.call(this, schema, root, baseId);
- if (index >= 0) return { index: index, compiling: true };
- index = this._compilations.length;
- this._compilations[index] = {
- schema: schema,
- root: root,
- baseId: baseId
- };
- return { index: index, compiling: false };
-}
-
-
-/**
- * Removes the schema from the currently compiled list
- * @this Ajv
- * @param {Object} schema schema to compile
- * @param {Object} root root object
- * @param {String} baseId base schema ID
- */
-function endCompiling(schema, root, baseId) {
- /* jshint validthis: true */
- var i = compIndex.call(this, schema, root, baseId);
- if (i >= 0) this._compilations.splice(i, 1);
-}
-
-
-/**
- * Index of schema compilation in the currently compiled list
- * @this Ajv
- * @param {Object} schema schema to compile
- * @param {Object} root root object
- * @param {String} baseId base schema ID
- * @return {Integer} compilation index
- */
-function compIndex(schema, root, baseId) {
- /* jshint validthis: true */
- for (var i=0; i= 0xD800 && value <= 0xDBFF && pos < len) {
- // high surrogate, and there is a next character
- value = str.charCodeAt(pos);
- if ((value & 0xFC00) == 0xDC00) pos++; // low surrogate
- }
- }
- return length;
-};
-
-},{}],18:[function(require,module,exports){
-'use strict';
-
-
-module.exports = {
- copy: copy,
- checkDataType: checkDataType,
- checkDataTypes: checkDataTypes,
- coerceToTypes: coerceToTypes,
- toHash: toHash,
- getProperty: getProperty,
- escapeQuotes: escapeQuotes,
- equal: require('fast-deep-equal'),
- ucs2length: require('./ucs2length'),
- varOccurences: varOccurences,
- varReplace: varReplace,
- cleanUpCode: cleanUpCode,
- finalCleanUpCode: finalCleanUpCode,
- schemaHasRules: schemaHasRules,
- schemaHasRulesExcept: schemaHasRulesExcept,
- schemaUnknownRules: schemaUnknownRules,
- toQuotedString: toQuotedString,
- getPathExpr: getPathExpr,
- getPath: getPath,
- getData: getData,
- unescapeFragment: unescapeFragment,
- unescapeJsonPointer: unescapeJsonPointer,
- escapeFragment: escapeFragment,
- escapeJsonPointer: escapeJsonPointer
-};
-
-
-function copy(o, to) {
- to = to || {};
- for (var key in o) to[key] = o[key];
- return to;
-}
-
-
-function checkDataType(dataType, data, negate) {
- var EQUAL = negate ? ' !== ' : ' === '
- , AND = negate ? ' || ' : ' && '
- , OK = negate ? '!' : ''
- , NOT = negate ? '' : '!';
- switch (dataType) {
- case 'null': return data + EQUAL + 'null';
- case 'array': return OK + 'Array.isArray(' + data + ')';
- case 'object': return '(' + OK + data + AND +
- 'typeof ' + data + EQUAL + '"object"' + AND +
- NOT + 'Array.isArray(' + data + '))';
- case 'integer': return '(typeof ' + data + EQUAL + '"number"' + AND +
- NOT + '(' + data + ' % 1)' +
- AND + data + EQUAL + data + ')';
- default: return 'typeof ' + data + EQUAL + '"' + dataType + '"';
- }
-}
-
-
-function checkDataTypes(dataTypes, data) {
- switch (dataTypes.length) {
- case 1: return checkDataType(dataTypes[0], data, true);
- default:
- var code = '';
- var types = toHash(dataTypes);
- if (types.array && types.object) {
- code = types.null ? '(': '(!' + data + ' || ';
- code += 'typeof ' + data + ' !== "object")';
- delete types.null;
- delete types.array;
- delete types.object;
- }
- if (types.number) delete types.integer;
- for (var t in types)
- code += (code ? ' && ' : '' ) + checkDataType(t, data, true);
-
- return code;
- }
-}
-
-
-var COERCE_TO_TYPES = toHash([ 'string', 'number', 'integer', 'boolean', 'null' ]);
-function coerceToTypes(optionCoerceTypes, dataTypes) {
- if (Array.isArray(dataTypes)) {
- var types = [];
- for (var i=0; i= lvl) throw new Error('Cannot access property/index ' + up + ' levels up, current level is ' + lvl);
- return paths[lvl - up];
- }
-
- if (up > lvl) throw new Error('Cannot access data ' + up + ' levels up, current level is ' + lvl);
- data = 'data' + ((lvl - up) || '');
- if (!jsonPointer) return data;
- }
-
- var expr = data;
- var segments = jsonPointer.split('/');
- for (var i=0; i',
- $notOp = $isMax ? '>' : '<',
- $errorKeyword = undefined;
- if ($isDataExcl) {
- var $schemaValueExcl = it.util.getData($schemaExcl.$data, $dataLvl, it.dataPathArr),
- $exclusive = 'exclusive' + $lvl,
- $exclType = 'exclType' + $lvl,
- $exclIsNumber = 'exclIsNumber' + $lvl,
- $opExpr = 'op' + $lvl,
- $opStr = '\' + ' + $opExpr + ' + \'';
- out += ' var schemaExcl' + ($lvl) + ' = ' + ($schemaValueExcl) + '; ';
- $schemaValueExcl = 'schemaExcl' + $lvl;
- out += ' var ' + ($exclusive) + '; var ' + ($exclType) + ' = typeof ' + ($schemaValueExcl) + '; if (' + ($exclType) + ' != \'boolean\' && ' + ($exclType) + ' != \'undefined\' && ' + ($exclType) + ' != \'number\') { ';
- var $errorKeyword = $exclusiveKeyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || '_exclusiveLimit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'' + ($exclusiveKeyword) + ' should be boolean\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- out += ' ' + ($exclType) + ' == \'number\' ? ( (' + ($exclusive) + ' = ' + ($schemaValue) + ' === undefined || ' + ($schemaValueExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ') ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValueExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) : ( (' + ($exclusive) + ' = ' + ($schemaValueExcl) + ' === true) ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaValue) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { var op' + ($lvl) + ' = ' + ($exclusive) + ' ? \'' + ($op) + '\' : \'' + ($op) + '=\'; ';
- if ($schema === undefined) {
- $errorKeyword = $exclusiveKeyword;
- $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
- $schemaValue = $schemaValueExcl;
- $isData = $isDataExcl;
- }
- } else {
- var $exclIsNumber = typeof $schemaExcl == 'number',
- $opStr = $op;
- if ($exclIsNumber && $isData) {
- var $opExpr = '\'' + $opStr + '\'';
- out += ' if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- out += ' ( ' + ($schemaValue) + ' === undefined || ' + ($schemaExcl) + ' ' + ($op) + '= ' + ($schemaValue) + ' ? ' + ($data) + ' ' + ($notOp) + '= ' + ($schemaExcl) + ' : ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' ) || ' + ($data) + ' !== ' + ($data) + ') { ';
- } else {
- if ($exclIsNumber && $schema === undefined) {
- $exclusive = true;
- $errorKeyword = $exclusiveKeyword;
- $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
- $schemaValue = $schemaExcl;
- $notOp += '=';
- } else {
- if ($exclIsNumber) $schemaValue = Math[$isMax ? 'min' : 'max']($schemaExcl, $schema);
- if ($schemaExcl === ($exclIsNumber ? $schemaValue : true)) {
- $exclusive = true;
- $errorKeyword = $exclusiveKeyword;
- $errSchemaPath = it.errSchemaPath + '/' + $exclusiveKeyword;
- $notOp += '=';
- } else {
- $exclusive = false;
- $opStr += '=';
- }
- }
- var $opExpr = '\'' + $opStr + '\'';
- out += ' if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- out += ' ' + ($data) + ' ' + ($notOp) + ' ' + ($schemaValue) + ' || ' + ($data) + ' !== ' + ($data) + ') { ';
- }
- }
- $errorKeyword = $errorKeyword || $keyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || '_limit') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { comparison: ' + ($opExpr) + ', limit: ' + ($schemaValue) + ', exclusive: ' + ($exclusive) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be ' + ($opStr) + ' ';
- if ($isData) {
- out += '\' + ' + ($schemaValue);
- } else {
- out += '' + ($schemaValue) + '\'';
- }
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],22:[function(require,module,exports){
-'use strict';
-module.exports = function generate__limitItems(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $errorKeyword;
- var $data = 'data' + ($dataLvl || '');
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $op = $keyword == 'maxItems' ? '>' : '<';
- out += 'if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- out += ' ' + ($data) + '.length ' + ($op) + ' ' + ($schemaValue) + ') { ';
- var $errorKeyword = $keyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || '_limitItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT have ';
- if ($keyword == 'maxItems') {
- out += 'more';
- } else {
- out += 'fewer';
- }
- out += ' than ';
- if ($isData) {
- out += '\' + ' + ($schemaValue) + ' + \'';
- } else {
- out += '' + ($schema);
- }
- out += ' items\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += '} ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],23:[function(require,module,exports){
-'use strict';
-module.exports = function generate__limitLength(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $errorKeyword;
- var $data = 'data' + ($dataLvl || '');
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $op = $keyword == 'maxLength' ? '>' : '<';
- out += 'if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- if (it.opts.unicode === false) {
- out += ' ' + ($data) + '.length ';
- } else {
- out += ' ucs2length(' + ($data) + ') ';
- }
- out += ' ' + ($op) + ' ' + ($schemaValue) + ') { ';
- var $errorKeyword = $keyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || '_limitLength') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT be ';
- if ($keyword == 'maxLength') {
- out += 'longer';
- } else {
- out += 'shorter';
- }
- out += ' than ';
- if ($isData) {
- out += '\' + ' + ($schemaValue) + ' + \'';
- } else {
- out += '' + ($schema);
- }
- out += ' characters\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += '} ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],24:[function(require,module,exports){
-'use strict';
-module.exports = function generate__limitProperties(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $errorKeyword;
- var $data = 'data' + ($dataLvl || '');
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $op = $keyword == 'maxProperties' ? '>' : '<';
- out += 'if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'number\') || ';
- }
- out += ' Object.keys(' + ($data) + ').length ' + ($op) + ' ' + ($schemaValue) + ') { ';
- var $errorKeyword = $keyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || '_limitProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schemaValue) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT have ';
- if ($keyword == 'maxProperties') {
- out += 'more';
- } else {
- out += 'fewer';
- }
- out += ' than ';
- if ($isData) {
- out += '\' + ' + ($schemaValue) + ' + \'';
- } else {
- out += '' + ($schema);
- }
- out += ' properties\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += '} ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],25:[function(require,module,exports){
-'use strict';
-module.exports = function generate_allOf(it, $keyword, $ruleType) {
- var out = ' ';
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $currentBaseId = $it.baseId,
- $allSchemasEmpty = true;
- var arr1 = $schema;
- if (arr1) {
- var $sch, $i = -1,
- l1 = arr1.length - 1;
- while ($i < l1) {
- $sch = arr1[$i += 1];
- if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- $allSchemasEmpty = false;
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + '[' + $i + ']';
- $it.errSchemaPath = $errSchemaPath + '/' + $i;
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- }
- }
- if ($breakOnError) {
- if ($allSchemasEmpty) {
- out += ' if (true) { ';
- } else {
- out += ' ' + ($closingBraces.slice(0, -1)) + ' ';
- }
- }
- out = it.util.cleanUpCode(out);
- return out;
-}
-
-},{}],26:[function(require,module,exports){
-'use strict';
-module.exports = function generate_anyOf(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $noEmptySchema = $schema.every(function($sch) {
- return (it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all));
- });
- if ($noEmptySchema) {
- var $currentBaseId = $it.baseId;
- out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = false; ';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- var arr1 = $schema;
- if (arr1) {
- var $sch, $i = -1,
- l1 = arr1.length - 1;
- while ($i < l1) {
- $sch = arr1[$i += 1];
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + '[' + $i + ']';
- $it.errSchemaPath = $errSchemaPath + '/' + $i;
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- out += ' ' + ($valid) + ' = ' + ($valid) + ' || ' + ($nextValid) + '; if (!' + ($valid) + ') { ';
- $closingBraces += '}';
- }
- }
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += ' ' + ($closingBraces) + ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('anyOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should match some schema in anyOf\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError(vErrors); ';
- } else {
- out += ' validate.errors = vErrors; return false; ';
- }
- }
- out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
- if (it.opts.allErrors) {
- out += ' } ';
- }
- out = it.util.cleanUpCode(out);
- } else {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- }
- return out;
-}
-
-},{}],27:[function(require,module,exports){
-'use strict';
-module.exports = function generate_comment(it, $keyword, $ruleType) {
- var out = ' ';
- var $schema = it.schema[$keyword];
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $comment = it.util.toQuotedString($schema);
- if (it.opts.$comment === true) {
- out += ' console.log(' + ($comment) + ');';
- } else if (typeof it.opts.$comment == 'function') {
- out += ' self._opts.$comment(' + ($comment) + ', ' + (it.util.toQuotedString($errSchemaPath)) + ', validate.root.schema);';
- }
- return out;
-}
-
-},{}],28:[function(require,module,exports){
-'use strict';
-module.exports = function generate_const(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- if (!$isData) {
- out += ' var schema' + ($lvl) + ' = validate.schema' + ($schemaPath) + ';';
- }
- out += 'var ' + ($valid) + ' = equal(' + ($data) + ', schema' + ($lvl) + '); if (!' + ($valid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('const') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValue: schema' + ($lvl) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be equal to constant\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' }';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],29:[function(require,module,exports){
-'use strict';
-module.exports = function generate_contains(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $idx = 'i' + $lvl,
- $dataNxt = $it.dataLevel = it.dataLevel + 1,
- $nextData = 'data' + $dataNxt,
- $currentBaseId = it.baseId,
- $nonEmptySchema = (it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all));
- out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
- if ($nonEmptySchema) {
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- $it.schema = $schema;
- $it.schemaPath = $schemaPath;
- $it.errSchemaPath = $errSchemaPath;
- out += ' var ' + ($nextValid) + ' = false; for (var ' + ($idx) + ' = 0; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
- $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
- var $passData = $data + '[' + $idx + ']';
- $it.dataPathArr[$dataNxt] = $idx;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- out += ' if (' + ($nextValid) + ') break; } ';
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += ' ' + ($closingBraces) + ' if (!' + ($nextValid) + ') {';
- } else {
- out += ' if (' + ($data) + '.length == 0) {';
- }
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('contains') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should contain a valid item\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else { ';
- if ($nonEmptySchema) {
- out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
- }
- if (it.opts.allErrors) {
- out += ' } ';
- }
- out = it.util.cleanUpCode(out);
- return out;
-}
-
-},{}],30:[function(require,module,exports){
-'use strict';
-module.exports = function generate_custom(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $errorKeyword;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $rule = this,
- $definition = 'definition' + $lvl,
- $rDef = $rule.definition,
- $closingBraces = '';
- var $compile, $inline, $macro, $ruleValidate, $validateCode;
- if ($isData && $rDef.$data) {
- $validateCode = 'keywordValidate' + $lvl;
- var $validateSchema = $rDef.validateSchema;
- out += ' var ' + ($definition) + ' = RULES.custom[\'' + ($keyword) + '\'].definition; var ' + ($validateCode) + ' = ' + ($definition) + '.validate;';
- } else {
- $ruleValidate = it.useCustomRule($rule, $schema, it.schema, it);
- if (!$ruleValidate) return;
- $schemaValue = 'validate.schema' + $schemaPath;
- $validateCode = $ruleValidate.code;
- $compile = $rDef.compile;
- $inline = $rDef.inline;
- $macro = $rDef.macro;
- }
- var $ruleErrs = $validateCode + '.errors',
- $i = 'i' + $lvl,
- $ruleErr = 'ruleErr' + $lvl,
- $asyncKeyword = $rDef.async;
- if ($asyncKeyword && !it.async) throw new Error('async keyword in sync schema');
- if (!($inline || $macro)) {
- out += '' + ($ruleErrs) + ' = null;';
- }
- out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
- if ($isData && $rDef.$data) {
- $closingBraces += '}';
- out += ' if (' + ($schemaValue) + ' === undefined) { ' + ($valid) + ' = true; } else { ';
- if ($validateSchema) {
- $closingBraces += '}';
- out += ' ' + ($valid) + ' = ' + ($definition) + '.validateSchema(' + ($schemaValue) + '); if (' + ($valid) + ') { ';
- }
- }
- if ($inline) {
- if ($rDef.statements) {
- out += ' ' + ($ruleValidate.validate) + ' ';
- } else {
- out += ' ' + ($valid) + ' = ' + ($ruleValidate.validate) + '; ';
- }
- } else if ($macro) {
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- $it.schema = $ruleValidate.validate;
- $it.schemaPath = '';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- var $code = it.validate($it).replace(/validate\.schema/g, $validateCode);
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += ' ' + ($code);
- } else {
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = '';
- out += ' ' + ($validateCode) + '.call( ';
- if (it.opts.passContext) {
- out += 'this';
- } else {
- out += 'self';
- }
- if ($compile || $rDef.schema === false) {
- out += ' , ' + ($data) + ' ';
- } else {
- out += ' , ' + ($schemaValue) + ' , ' + ($data) + ' , validate.schema' + (it.schemaPath) + ' ';
- }
- out += ' , (dataPath || \'\')';
- if (it.errorPath != '""') {
- out += ' + ' + (it.errorPath);
- }
- var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
- $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
- out += ' , ' + ($parentData) + ' , ' + ($parentDataProperty) + ' , rootData ) ';
- var def_callRuleValidate = out;
- out = $$outStack.pop();
- if ($rDef.errors === false) {
- out += ' ' + ($valid) + ' = ';
- if ($asyncKeyword) {
- out += 'await ';
- }
- out += '' + (def_callRuleValidate) + '; ';
- } else {
- if ($asyncKeyword) {
- $ruleErrs = 'customErrors' + $lvl;
- out += ' var ' + ($ruleErrs) + ' = null; try { ' + ($valid) + ' = await ' + (def_callRuleValidate) + '; } catch (e) { ' + ($valid) + ' = false; if (e instanceof ValidationError) ' + ($ruleErrs) + ' = e.errors; else throw e; } ';
- } else {
- out += ' ' + ($ruleErrs) + ' = null; ' + ($valid) + ' = ' + (def_callRuleValidate) + '; ';
- }
- }
- }
- if ($rDef.modifying) {
- out += ' if (' + ($parentData) + ') ' + ($data) + ' = ' + ($parentData) + '[' + ($parentDataProperty) + '];';
- }
- out += '' + ($closingBraces);
- if ($rDef.valid) {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- } else {
- out += ' if ( ';
- if ($rDef.valid === undefined) {
- out += ' !';
- if ($macro) {
- out += '' + ($nextValid);
- } else {
- out += '' + ($valid);
- }
- } else {
- out += ' ' + (!$rDef.valid) + ' ';
- }
- out += ') { ';
- $errorKeyword = $rule.keyword;
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = '';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || 'custom') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { keyword: \'' + ($rule.keyword) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should pass "' + ($rule.keyword) + '" keyword validation\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- var def_customError = out;
- out = $$outStack.pop();
- if ($inline) {
- if ($rDef.errors) {
- if ($rDef.errors != 'full') {
- out += ' for (var ' + ($i) + '=' + ($errs) + '; ' + ($i) + ' 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- out += ' ' + ($nextValid) + ' = true; if ( ' + ($data) + (it.util.getProperty($property)) + ' !== undefined ';
- if ($ownProperties) {
- out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($property)) + '\') ';
- }
- out += ') { ';
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + it.util.getProperty($property);
- $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($property);
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- out += ' } ';
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- }
- if ($breakOnError) {
- out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
- }
- out = it.util.cleanUpCode(out);
- return out;
-}
-
-},{}],32:[function(require,module,exports){
-'use strict';
-module.exports = function generate_enum(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $i = 'i' + $lvl,
- $vSchema = 'schema' + $lvl;
- if (!$isData) {
- out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + ';';
- }
- out += 'var ' + ($valid) + ';';
- if ($isData) {
- out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
- }
- out += '' + ($valid) + ' = false;for (var ' + ($i) + '=0; ' + ($i) + '<' + ($vSchema) + '.length; ' + ($i) + '++) if (equal(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + '])) { ' + ($valid) + ' = true; break; }';
- if ($isData) {
- out += ' } ';
- }
- out += ' if (!' + ($valid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('enum') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { allowedValues: schema' + ($lvl) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be equal to one of the allowed values\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' }';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],33:[function(require,module,exports){
-'use strict';
-module.exports = function generate_format(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- if (it.opts.format === false) {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- return out;
- }
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $unknownFormats = it.opts.unknownFormats,
- $allowUnknown = Array.isArray($unknownFormats);
- if ($isData) {
- var $format = 'format' + $lvl,
- $isObject = 'isObject' + $lvl,
- $formatType = 'formatType' + $lvl;
- out += ' var ' + ($format) + ' = formats[' + ($schemaValue) + ']; var ' + ($isObject) + ' = typeof ' + ($format) + ' == \'object\' && !(' + ($format) + ' instanceof RegExp) && ' + ($format) + '.validate; var ' + ($formatType) + ' = ' + ($isObject) + ' && ' + ($format) + '.type || \'string\'; if (' + ($isObject) + ') { ';
- if (it.async) {
- out += ' var async' + ($lvl) + ' = ' + ($format) + '.async; ';
- }
- out += ' ' + ($format) + ' = ' + ($format) + '.validate; } if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
- }
- out += ' (';
- if ($unknownFormats != 'ignore') {
- out += ' (' + ($schemaValue) + ' && !' + ($format) + ' ';
- if ($allowUnknown) {
- out += ' && self._opts.unknownFormats.indexOf(' + ($schemaValue) + ') == -1 ';
- }
- out += ') || ';
- }
- out += ' (' + ($format) + ' && ' + ($formatType) + ' == \'' + ($ruleType) + '\' && !(typeof ' + ($format) + ' == \'function\' ? ';
- if (it.async) {
- out += ' (async' + ($lvl) + ' ? await ' + ($format) + '(' + ($data) + ') : ' + ($format) + '(' + ($data) + ')) ';
- } else {
- out += ' ' + ($format) + '(' + ($data) + ') ';
- }
- out += ' : ' + ($format) + '.test(' + ($data) + '))))) {';
- } else {
- var $format = it.formats[$schema];
- if (!$format) {
- if ($unknownFormats == 'ignore') {
- it.logger.warn('unknown format "' + $schema + '" ignored in schema at path "' + it.errSchemaPath + '"');
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- return out;
- } else if ($allowUnknown && $unknownFormats.indexOf($schema) >= 0) {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- return out;
- } else {
- throw new Error('unknown format "' + $schema + '" is used in schema at path "' + it.errSchemaPath + '"');
- }
- }
- var $isObject = typeof $format == 'object' && !($format instanceof RegExp) && $format.validate;
- var $formatType = $isObject && $format.type || 'string';
- if ($isObject) {
- var $async = $format.async === true;
- $format = $format.validate;
- }
- if ($formatType != $ruleType) {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- return out;
- }
- if ($async) {
- if (!it.async) throw new Error('async format in sync schema');
- var $formatRef = 'formats' + it.util.getProperty($schema) + '.validate';
- out += ' if (!(await ' + ($formatRef) + '(' + ($data) + '))) { ';
- } else {
- out += ' if (! ';
- var $formatRef = 'formats' + it.util.getProperty($schema);
- if ($isObject) $formatRef += '.validate';
- if (typeof $format == 'function') {
- out += ' ' + ($formatRef) + '(' + ($data) + ') ';
- } else {
- out += ' ' + ($formatRef) + '.test(' + ($data) + ') ';
- }
- out += ') { ';
- }
- }
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('format') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { format: ';
- if ($isData) {
- out += '' + ($schemaValue);
- } else {
- out += '' + (it.util.toQuotedString($schema));
- }
- out += ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should match format "';
- if ($isData) {
- out += '\' + ' + ($schemaValue) + ' + \'';
- } else {
- out += '' + (it.util.escapeQuotes($schema));
- }
- out += '"\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + (it.util.toQuotedString($schema));
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],34:[function(require,module,exports){
-'use strict';
-module.exports = function generate_if(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $thenSch = it.schema['then'],
- $elseSch = it.schema['else'],
- $thenPresent = $thenSch !== undefined && (it.opts.strictKeywords ? typeof $thenSch == 'object' && Object.keys($thenSch).length > 0 : it.util.schemaHasRules($thenSch, it.RULES.all)),
- $elsePresent = $elseSch !== undefined && (it.opts.strictKeywords ? typeof $elseSch == 'object' && Object.keys($elseSch).length > 0 : it.util.schemaHasRules($elseSch, it.RULES.all)),
- $currentBaseId = $it.baseId;
- if ($thenPresent || $elsePresent) {
- var $ifClause;
- $it.createErrors = false;
- $it.schema = $schema;
- $it.schemaPath = $schemaPath;
- $it.errSchemaPath = $errSchemaPath;
- out += ' var ' + ($errs) + ' = errors; var ' + ($valid) + ' = true; ';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- $it.createErrors = true;
- out += ' errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
- it.compositeRule = $it.compositeRule = $wasComposite;
- if ($thenPresent) {
- out += ' if (' + ($nextValid) + ') { ';
- $it.schema = it.schema['then'];
- $it.schemaPath = it.schemaPath + '.then';
- $it.errSchemaPath = it.errSchemaPath + '/then';
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
- if ($thenPresent && $elsePresent) {
- $ifClause = 'ifClause' + $lvl;
- out += ' var ' + ($ifClause) + ' = \'then\'; ';
- } else {
- $ifClause = '\'then\'';
- }
- out += ' } ';
- if ($elsePresent) {
- out += ' else { ';
- }
- } else {
- out += ' if (!' + ($nextValid) + ') { ';
- }
- if ($elsePresent) {
- $it.schema = it.schema['else'];
- $it.schemaPath = it.schemaPath + '.else';
- $it.errSchemaPath = it.errSchemaPath + '/else';
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- out += ' ' + ($valid) + ' = ' + ($nextValid) + '; ';
- if ($thenPresent && $elsePresent) {
- $ifClause = 'ifClause' + $lvl;
- out += ' var ' + ($ifClause) + ' = \'else\'; ';
- } else {
- $ifClause = '\'else\'';
- }
- out += ' } ';
- }
- out += ' if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('if') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { failingKeyword: ' + ($ifClause) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should match "\' + ' + ($ifClause) + ' + \'" schema\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError(vErrors); ';
- } else {
- out += ' validate.errors = vErrors; return false; ';
- }
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' else { ';
- }
- out = it.util.cleanUpCode(out);
- } else {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- }
- return out;
-}
-
-},{}],35:[function(require,module,exports){
-'use strict';
-
-//all requires must be explicit because browserify won't work with dynamic requires
-module.exports = {
- '$ref': require('./ref'),
- allOf: require('./allOf'),
- anyOf: require('./anyOf'),
- '$comment': require('./comment'),
- const: require('./const'),
- contains: require('./contains'),
- dependencies: require('./dependencies'),
- 'enum': require('./enum'),
- format: require('./format'),
- 'if': require('./if'),
- items: require('./items'),
- maximum: require('./_limit'),
- minimum: require('./_limit'),
- maxItems: require('./_limitItems'),
- minItems: require('./_limitItems'),
- maxLength: require('./_limitLength'),
- minLength: require('./_limitLength'),
- maxProperties: require('./_limitProperties'),
- minProperties: require('./_limitProperties'),
- multipleOf: require('./multipleOf'),
- not: require('./not'),
- oneOf: require('./oneOf'),
- pattern: require('./pattern'),
- properties: require('./properties'),
- propertyNames: require('./propertyNames'),
- required: require('./required'),
- uniqueItems: require('./uniqueItems'),
- validate: require('./validate')
-};
-
-},{"./_limit":21,"./_limitItems":22,"./_limitLength":23,"./_limitProperties":24,"./allOf":25,"./anyOf":26,"./comment":27,"./const":28,"./contains":29,"./dependencies":31,"./enum":32,"./format":33,"./if":34,"./items":36,"./multipleOf":37,"./not":38,"./oneOf":39,"./pattern":40,"./properties":41,"./propertyNames":42,"./ref":43,"./required":44,"./uniqueItems":45,"./validate":46}],36:[function(require,module,exports){
-'use strict';
-module.exports = function generate_items(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $idx = 'i' + $lvl,
- $dataNxt = $it.dataLevel = it.dataLevel + 1,
- $nextData = 'data' + $dataNxt,
- $currentBaseId = it.baseId;
- out += 'var ' + ($errs) + ' = errors;var ' + ($valid) + ';';
- if (Array.isArray($schema)) {
- var $additionalItems = it.schema.additionalItems;
- if ($additionalItems === false) {
- out += ' ' + ($valid) + ' = ' + ($data) + '.length <= ' + ($schema.length) + '; ';
- var $currErrSchemaPath = $errSchemaPath;
- $errSchemaPath = it.errSchemaPath + '/additionalItems';
- out += ' if (!' + ($valid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('additionalItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { limit: ' + ($schema.length) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT have more than ' + ($schema.length) + ' items\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } ';
- $errSchemaPath = $currErrSchemaPath;
- if ($breakOnError) {
- $closingBraces += '}';
- out += ' else { ';
- }
- }
- var arr1 = $schema;
- if (arr1) {
- var $sch, $i = -1,
- l1 = arr1.length - 1;
- while ($i < l1) {
- $sch = arr1[$i += 1];
- if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($i) + ') { ';
- var $passData = $data + '[' + $i + ']';
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + '[' + $i + ']';
- $it.errSchemaPath = $errSchemaPath + '/' + $i;
- $it.errorPath = it.util.getPathExpr(it.errorPath, $i, it.opts.jsonPointers, true);
- $it.dataPathArr[$dataNxt] = $i;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- }
- }
- if (typeof $additionalItems == 'object' && (it.opts.strictKeywords ? typeof $additionalItems == 'object' && Object.keys($additionalItems).length > 0 : it.util.schemaHasRules($additionalItems, it.RULES.all))) {
- $it.schema = $additionalItems;
- $it.schemaPath = it.schemaPath + '.additionalItems';
- $it.errSchemaPath = it.errSchemaPath + '/additionalItems';
- out += ' ' + ($nextValid) + ' = true; if (' + ($data) + '.length > ' + ($schema.length) + ') { for (var ' + ($idx) + ' = ' + ($schema.length) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
- $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
- var $passData = $data + '[' + $idx + ']';
- $it.dataPathArr[$dataNxt] = $idx;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- if ($breakOnError) {
- out += ' if (!' + ($nextValid) + ') break; ';
- }
- out += ' } } ';
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- } else if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) {
- $it.schema = $schema;
- $it.schemaPath = $schemaPath;
- $it.errSchemaPath = $errSchemaPath;
- out += ' for (var ' + ($idx) + ' = ' + (0) + '; ' + ($idx) + ' < ' + ($data) + '.length; ' + ($idx) + '++) { ';
- $it.errorPath = it.util.getPathExpr(it.errorPath, $idx, it.opts.jsonPointers, true);
- var $passData = $data + '[' + $idx + ']';
- $it.dataPathArr[$dataNxt] = $idx;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- if ($breakOnError) {
- out += ' if (!' + ($nextValid) + ') break; ';
- }
- out += ' }';
- }
- if ($breakOnError) {
- out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
- }
- out = it.util.cleanUpCode(out);
- return out;
-}
-
-},{}],37:[function(require,module,exports){
-'use strict';
-module.exports = function generate_multipleOf(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- out += 'var division' + ($lvl) + ';if (';
- if ($isData) {
- out += ' ' + ($schemaValue) + ' !== undefined && ( typeof ' + ($schemaValue) + ' != \'number\' || ';
- }
- out += ' (division' + ($lvl) + ' = ' + ($data) + ' / ' + ($schemaValue) + ', ';
- if (it.opts.multipleOfPrecision) {
- out += ' Math.abs(Math.round(division' + ($lvl) + ') - division' + ($lvl) + ') > 1e-' + (it.opts.multipleOfPrecision) + ' ';
- } else {
- out += ' division' + ($lvl) + ' !== parseInt(division' + ($lvl) + ') ';
- }
- out += ' ) ';
- if ($isData) {
- out += ' ) ';
- }
- out += ' ) { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('multipleOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { multipleOf: ' + ($schemaValue) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be multiple of ';
- if ($isData) {
- out += '\' + ' + ($schemaValue);
- } else {
- out += '' + ($schemaValue) + '\'';
- }
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += '} ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],38:[function(require,module,exports){
-'use strict';
-module.exports = function generate_not(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) {
- $it.schema = $schema;
- $it.schemaPath = $schemaPath;
- $it.errSchemaPath = $errSchemaPath;
- out += ' var ' + ($errs) + ' = errors; ';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- $it.createErrors = false;
- var $allErrorsOption;
- if ($it.opts.allErrors) {
- $allErrorsOption = $it.opts.allErrors;
- $it.opts.allErrors = false;
- }
- out += ' ' + (it.validate($it)) + ' ';
- $it.createErrors = true;
- if ($allErrorsOption) $it.opts.allErrors = $allErrorsOption;
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += ' if (' + ($nextValid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT be valid\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; } ';
- if (it.opts.allErrors) {
- out += ' } ';
- }
- } else {
- out += ' var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('not') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT be valid\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- if ($breakOnError) {
- out += ' if (false) { ';
- }
- }
- return out;
-}
-
-},{}],39:[function(require,module,exports){
-'use strict';
-module.exports = function generate_oneOf(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $currentBaseId = $it.baseId,
- $prevValid = 'prevValid' + $lvl,
- $passingSchemas = 'passingSchemas' + $lvl;
- out += 'var ' + ($errs) + ' = errors , ' + ($prevValid) + ' = false , ' + ($valid) + ' = false , ' + ($passingSchemas) + ' = null; ';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- var arr1 = $schema;
- if (arr1) {
- var $sch, $i = -1,
- l1 = arr1.length - 1;
- while ($i < l1) {
- $sch = arr1[$i += 1];
- if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + '[' + $i + ']';
- $it.errSchemaPath = $errSchemaPath + '/' + $i;
- out += ' ' + (it.validate($it)) + ' ';
- $it.baseId = $currentBaseId;
- } else {
- out += ' var ' + ($nextValid) + ' = true; ';
- }
- if ($i) {
- out += ' if (' + ($nextValid) + ' && ' + ($prevValid) + ') { ' + ($valid) + ' = false; ' + ($passingSchemas) + ' = [' + ($passingSchemas) + ', ' + ($i) + ']; } else { ';
- $closingBraces += '}';
- }
- out += ' if (' + ($nextValid) + ') { ' + ($valid) + ' = ' + ($prevValid) + ' = true; ' + ($passingSchemas) + ' = ' + ($i) + '; }';
- }
- }
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += '' + ($closingBraces) + 'if (!' + ($valid) + ') { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('oneOf') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { passingSchemas: ' + ($passingSchemas) + ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should match exactly one schema in oneOf\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError(vErrors); ';
- } else {
- out += ' validate.errors = vErrors; return false; ';
- }
- }
- out += '} else { errors = ' + ($errs) + '; if (vErrors !== null) { if (' + ($errs) + ') vErrors.length = ' + ($errs) + '; else vErrors = null; }';
- if (it.opts.allErrors) {
- out += ' } ';
- }
- return out;
-}
-
-},{}],40:[function(require,module,exports){
-'use strict';
-module.exports = function generate_pattern(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- var $regexp = $isData ? '(new RegExp(' + $schemaValue + '))' : it.usePattern($schema);
- out += 'if ( ';
- if ($isData) {
- out += ' (' + ($schemaValue) + ' !== undefined && typeof ' + ($schemaValue) + ' != \'string\') || ';
- }
- out += ' !' + ($regexp) + '.test(' + ($data) + ') ) { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('pattern') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { pattern: ';
- if ($isData) {
- out += '' + ($schemaValue);
- } else {
- out += '' + (it.util.toQuotedString($schema));
- }
- out += ' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should match pattern "';
- if ($isData) {
- out += '\' + ' + ($schemaValue) + ' + \'';
- } else {
- out += '' + (it.util.escapeQuotes($schema));
- }
- out += '"\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + (it.util.toQuotedString($schema));
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += '} ';
- if ($breakOnError) {
- out += ' else { ';
- }
- return out;
-}
-
-},{}],41:[function(require,module,exports){
-'use strict';
-module.exports = function generate_properties(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- var $key = 'key' + $lvl,
- $idx = 'idx' + $lvl,
- $dataNxt = $it.dataLevel = it.dataLevel + 1,
- $nextData = 'data' + $dataNxt,
- $dataProperties = 'dataProperties' + $lvl;
- var $schemaKeys = Object.keys($schema || {}),
- $pProperties = it.schema.patternProperties || {},
- $pPropertyKeys = Object.keys($pProperties),
- $aProperties = it.schema.additionalProperties,
- $someProperties = $schemaKeys.length || $pPropertyKeys.length,
- $noAdditional = $aProperties === false,
- $additionalIsSchema = typeof $aProperties == 'object' && Object.keys($aProperties).length,
- $removeAdditional = it.opts.removeAdditional,
- $checkAdditional = $noAdditional || $additionalIsSchema || $removeAdditional,
- $ownProperties = it.opts.ownProperties,
- $currentBaseId = it.baseId;
- var $required = it.schema.required;
- if ($required && !(it.opts.$data && $required.$data) && $required.length < it.opts.loopRequired) var $requiredHash = it.util.toHash($required);
- out += 'var ' + ($errs) + ' = errors;var ' + ($nextValid) + ' = true;';
- if ($ownProperties) {
- out += ' var ' + ($dataProperties) + ' = undefined;';
- }
- if ($checkAdditional) {
- if ($ownProperties) {
- out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
- } else {
- out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
- }
- if ($someProperties) {
- out += ' var isAdditional' + ($lvl) + ' = !(false ';
- if ($schemaKeys.length) {
- if ($schemaKeys.length > 8) {
- out += ' || validate.schema' + ($schemaPath) + '.hasOwnProperty(' + ($key) + ') ';
- } else {
- var arr1 = $schemaKeys;
- if (arr1) {
- var $propertyKey, i1 = -1,
- l1 = arr1.length - 1;
- while (i1 < l1) {
- $propertyKey = arr1[i1 += 1];
- out += ' || ' + ($key) + ' == ' + (it.util.toQuotedString($propertyKey)) + ' ';
- }
- }
- }
- }
- if ($pPropertyKeys.length) {
- var arr2 = $pPropertyKeys;
- if (arr2) {
- var $pProperty, $i = -1,
- l2 = arr2.length - 1;
- while ($i < l2) {
- $pProperty = arr2[$i += 1];
- out += ' || ' + (it.usePattern($pProperty)) + '.test(' + ($key) + ') ';
- }
- }
- }
- out += ' ); if (isAdditional' + ($lvl) + ') { ';
- }
- if ($removeAdditional == 'all') {
- out += ' delete ' + ($data) + '[' + ($key) + ']; ';
- } else {
- var $currentErrorPath = it.errorPath;
- var $additionalProperty = '\' + ' + $key + ' + \'';
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
- }
- if ($noAdditional) {
- if ($removeAdditional) {
- out += ' delete ' + ($data) + '[' + ($key) + ']; ';
- } else {
- out += ' ' + ($nextValid) + ' = false; ';
- var $currErrSchemaPath = $errSchemaPath;
- $errSchemaPath = it.errSchemaPath + '/additionalProperties';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('additionalProperties') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { additionalProperty: \'' + ($additionalProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is an invalid additional property';
- } else {
- out += 'should NOT have additional properties';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- $errSchemaPath = $currErrSchemaPath;
- if ($breakOnError) {
- out += ' break; ';
- }
- }
- } else if ($additionalIsSchema) {
- if ($removeAdditional == 'failing') {
- out += ' var ' + ($errs) + ' = errors; ';
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- $it.schema = $aProperties;
- $it.schemaPath = it.schemaPath + '.additionalProperties';
- $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
- $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
- var $passData = $data + '[' + $key + ']';
- $it.dataPathArr[$dataNxt] = $key;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- out += ' if (!' + ($nextValid) + ') { errors = ' + ($errs) + '; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete ' + ($data) + '[' + ($key) + ']; } ';
- it.compositeRule = $it.compositeRule = $wasComposite;
- } else {
- $it.schema = $aProperties;
- $it.schemaPath = it.schemaPath + '.additionalProperties';
- $it.errSchemaPath = it.errSchemaPath + '/additionalProperties';
- $it.errorPath = it.opts._errorDataPathProperty ? it.errorPath : it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
- var $passData = $data + '[' + $key + ']';
- $it.dataPathArr[$dataNxt] = $key;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- if ($breakOnError) {
- out += ' if (!' + ($nextValid) + ') break; ';
- }
- }
- }
- it.errorPath = $currentErrorPath;
- }
- if ($someProperties) {
- out += ' } ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- var $useDefaults = it.opts.useDefaults && !it.compositeRule;
- if ($schemaKeys.length) {
- var arr3 = $schemaKeys;
- if (arr3) {
- var $propertyKey, i3 = -1,
- l3 = arr3.length - 1;
- while (i3 < l3) {
- $propertyKey = arr3[i3 += 1];
- var $sch = $schema[$propertyKey];
- if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- var $prop = it.util.getProperty($propertyKey),
- $passData = $data + $prop,
- $hasDefault = $useDefaults && $sch.default !== undefined;
- $it.schema = $sch;
- $it.schemaPath = $schemaPath + $prop;
- $it.errSchemaPath = $errSchemaPath + '/' + it.util.escapeFragment($propertyKey);
- $it.errorPath = it.util.getPath(it.errorPath, $propertyKey, it.opts.jsonPointers);
- $it.dataPathArr[$dataNxt] = it.util.toQuotedString($propertyKey);
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- $code = it.util.varReplace($code, $nextData, $passData);
- var $useData = $passData;
- } else {
- var $useData = $nextData;
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ';
- }
- if ($hasDefault) {
- out += ' ' + ($code) + ' ';
- } else {
- if ($requiredHash && $requiredHash[$propertyKey]) {
- out += ' if ( ' + ($useData) + ' === undefined ';
- if ($ownProperties) {
- out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
- }
- out += ') { ' + ($nextValid) + ' = false; ';
- var $currentErrorPath = it.errorPath,
- $currErrSchemaPath = $errSchemaPath,
- $missingProperty = it.util.escapeQuotes($propertyKey);
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
- }
- $errSchemaPath = it.errSchemaPath + '/required';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- $errSchemaPath = $currErrSchemaPath;
- it.errorPath = $currentErrorPath;
- out += ' } else { ';
- } else {
- if ($breakOnError) {
- out += ' if ( ' + ($useData) + ' === undefined ';
- if ($ownProperties) {
- out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
- }
- out += ') { ' + ($nextValid) + ' = true; } else { ';
- } else {
- out += ' if (' + ($useData) + ' !== undefined ';
- if ($ownProperties) {
- out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
- }
- out += ' ) { ';
- }
- }
- out += ' ' + ($code) + ' } ';
- }
- }
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- }
- }
- if ($pPropertyKeys.length) {
- var arr4 = $pPropertyKeys;
- if (arr4) {
- var $pProperty, i4 = -1,
- l4 = arr4.length - 1;
- while (i4 < l4) {
- $pProperty = arr4[i4 += 1];
- var $sch = $pProperties[$pProperty];
- if ((it.opts.strictKeywords ? typeof $sch == 'object' && Object.keys($sch).length > 0 : it.util.schemaHasRules($sch, it.RULES.all))) {
- $it.schema = $sch;
- $it.schemaPath = it.schemaPath + '.patternProperties' + it.util.getProperty($pProperty);
- $it.errSchemaPath = it.errSchemaPath + '/patternProperties/' + it.util.escapeFragment($pProperty);
- if ($ownProperties) {
- out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
- } else {
- out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
- }
- out += ' if (' + (it.usePattern($pProperty)) + '.test(' + ($key) + ')) { ';
- $it.errorPath = it.util.getPathExpr(it.errorPath, $key, it.opts.jsonPointers);
- var $passData = $data + '[' + $key + ']';
- $it.dataPathArr[$dataNxt] = $key;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- if ($breakOnError) {
- out += ' if (!' + ($nextValid) + ') break; ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' else ' + ($nextValid) + ' = true; ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' if (' + ($nextValid) + ') { ';
- $closingBraces += '}';
- }
- }
- }
- }
- }
- if ($breakOnError) {
- out += ' ' + ($closingBraces) + ' if (' + ($errs) + ' == errors) {';
- }
- out = it.util.cleanUpCode(out);
- return out;
-}
-
-},{}],42:[function(require,module,exports){
-'use strict';
-module.exports = function generate_propertyNames(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $errs = 'errs__' + $lvl;
- var $it = it.util.copy(it);
- var $closingBraces = '';
- $it.level++;
- var $nextValid = 'valid' + $it.level;
- out += 'var ' + ($errs) + ' = errors;';
- if ((it.opts.strictKeywords ? typeof $schema == 'object' && Object.keys($schema).length > 0 : it.util.schemaHasRules($schema, it.RULES.all))) {
- $it.schema = $schema;
- $it.schemaPath = $schemaPath;
- $it.errSchemaPath = $errSchemaPath;
- var $key = 'key' + $lvl,
- $idx = 'idx' + $lvl,
- $i = 'i' + $lvl,
- $invalidName = '\' + ' + $key + ' + \'',
- $dataNxt = $it.dataLevel = it.dataLevel + 1,
- $nextData = 'data' + $dataNxt,
- $dataProperties = 'dataProperties' + $lvl,
- $ownProperties = it.opts.ownProperties,
- $currentBaseId = it.baseId;
- if ($ownProperties) {
- out += ' var ' + ($dataProperties) + ' = undefined; ';
- }
- if ($ownProperties) {
- out += ' ' + ($dataProperties) + ' = ' + ($dataProperties) + ' || Object.keys(' + ($data) + '); for (var ' + ($idx) + '=0; ' + ($idx) + '<' + ($dataProperties) + '.length; ' + ($idx) + '++) { var ' + ($key) + ' = ' + ($dataProperties) + '[' + ($idx) + ']; ';
- } else {
- out += ' for (var ' + ($key) + ' in ' + ($data) + ') { ';
- }
- out += ' var startErrs' + ($lvl) + ' = errors; ';
- var $passData = $key;
- var $wasComposite = it.compositeRule;
- it.compositeRule = $it.compositeRule = true;
- var $code = it.validate($it);
- $it.baseId = $currentBaseId;
- if (it.util.varOccurences($code, $nextData) < 2) {
- out += ' ' + (it.util.varReplace($code, $nextData, $passData)) + ' ';
- } else {
- out += ' var ' + ($nextData) + ' = ' + ($passData) + '; ' + ($code) + ' ';
- }
- it.compositeRule = $it.compositeRule = $wasComposite;
- out += ' if (!' + ($nextValid) + ') { for (var ' + ($i) + '=startErrs' + ($lvl) + '; ' + ($i) + ' 0 : it.util.schemaHasRules($propertySch, it.RULES.all)))) {
- $required[$required.length] = $property;
- }
- }
- }
- } else {
- var $required = $schema;
- }
- }
- if ($isData || $required.length) {
- var $currentErrorPath = it.errorPath,
- $loopRequired = $isData || $required.length >= it.opts.loopRequired,
- $ownProperties = it.opts.ownProperties;
- if ($breakOnError) {
- out += ' var missing' + ($lvl) + '; ';
- if ($loopRequired) {
- if (!$isData) {
- out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
- }
- var $i = 'i' + $lvl,
- $propertyPath = 'schema' + $lvl + '[' + $i + ']',
- $missingProperty = '\' + ' + $propertyPath + ' + \'';
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
- }
- out += ' var ' + ($valid) + ' = true; ';
- if ($isData) {
- out += ' if (schema' + ($lvl) + ' === undefined) ' + ($valid) + ' = true; else if (!Array.isArray(schema' + ($lvl) + ')) ' + ($valid) + ' = false; else {';
- }
- out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { ' + ($valid) + ' = ' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] !== undefined ';
- if ($ownProperties) {
- out += ' && Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
- }
- out += '; if (!' + ($valid) + ') break; } ';
- if ($isData) {
- out += ' } ';
- }
- out += ' if (!' + ($valid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else { ';
- } else {
- out += ' if ( ';
- var arr2 = $required;
- if (arr2) {
- var $propertyKey, $i = -1,
- l2 = arr2.length - 1;
- while ($i < l2) {
- $propertyKey = arr2[$i += 1];
- if ($i) {
- out += ' || ';
- }
- var $prop = it.util.getProperty($propertyKey),
- $useData = $data + $prop;
- out += ' ( ( ' + ($useData) + ' === undefined ';
- if ($ownProperties) {
- out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
- }
- out += ') && (missing' + ($lvl) + ' = ' + (it.util.toQuotedString(it.opts.jsonPointers ? $propertyKey : $prop)) + ') ) ';
- }
- }
- out += ') { ';
- var $propertyPath = 'missing' + $lvl,
- $missingProperty = '\' + ' + $propertyPath + ' + \'';
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.opts.jsonPointers ? it.util.getPathExpr($currentErrorPath, $propertyPath, true) : $currentErrorPath + ' + ' + $propertyPath;
- }
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else { ';
- }
- } else {
- if ($loopRequired) {
- if (!$isData) {
- out += ' var ' + ($vSchema) + ' = validate.schema' + ($schemaPath) + '; ';
- }
- var $i = 'i' + $lvl,
- $propertyPath = 'schema' + $lvl + '[' + $i + ']',
- $missingProperty = '\' + ' + $propertyPath + ' + \'';
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.util.getPathExpr($currentErrorPath, $propertyPath, it.opts.jsonPointers);
- }
- if ($isData) {
- out += ' if (' + ($vSchema) + ' && !Array.isArray(' + ($vSchema) + ')) { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if (' + ($vSchema) + ' !== undefined) { ';
- }
- out += ' for (var ' + ($i) + ' = 0; ' + ($i) + ' < ' + ($vSchema) + '.length; ' + ($i) + '++) { if (' + ($data) + '[' + ($vSchema) + '[' + ($i) + ']] === undefined ';
- if ($ownProperties) {
- out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', ' + ($vSchema) + '[' + ($i) + ']) ';
- }
- out += ') { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ';
- if ($isData) {
- out += ' } ';
- }
- } else {
- var arr3 = $required;
- if (arr3) {
- var $propertyKey, i3 = -1,
- l3 = arr3.length - 1;
- while (i3 < l3) {
- $propertyKey = arr3[i3 += 1];
- var $prop = it.util.getProperty($propertyKey),
- $missingProperty = it.util.escapeQuotes($propertyKey),
- $useData = $data + $prop;
- if (it.opts._errorDataPathProperty) {
- it.errorPath = it.util.getPath($currentErrorPath, $propertyKey, it.opts.jsonPointers);
- }
- out += ' if ( ' + ($useData) + ' === undefined ';
- if ($ownProperties) {
- out += ' || ! Object.prototype.hasOwnProperty.call(' + ($data) + ', \'' + (it.util.escapeQuotes($propertyKey)) + '\') ';
- }
- out += ') { var err = '; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('required') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { missingProperty: \'' + ($missingProperty) + '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'';
- if (it.opts._errorDataPathProperty) {
- out += 'is a required property';
- } else {
- out += 'should have required property \\\'' + ($missingProperty) + '\\\'';
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- out += '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } ';
- }
- }
- }
- }
- it.errorPath = $currentErrorPath;
- } else if ($breakOnError) {
- out += ' if (true) {';
- }
- return out;
-}
-
-},{}],45:[function(require,module,exports){
-'use strict';
-module.exports = function generate_uniqueItems(it, $keyword, $ruleType) {
- var out = ' ';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- var $isData = it.opts.$data && $schema && $schema.$data,
- $schemaValue;
- if ($isData) {
- out += ' var schema' + ($lvl) + ' = ' + (it.util.getData($schema.$data, $dataLvl, it.dataPathArr)) + '; ';
- $schemaValue = 'schema' + $lvl;
- } else {
- $schemaValue = $schema;
- }
- if (($schema || $isData) && it.opts.uniqueItems !== false) {
- if ($isData) {
- out += ' var ' + ($valid) + '; if (' + ($schemaValue) + ' === false || ' + ($schemaValue) + ' === undefined) ' + ($valid) + ' = true; else if (typeof ' + ($schemaValue) + ' != \'boolean\') ' + ($valid) + ' = false; else { ';
- }
- out += ' var i = ' + ($data) + '.length , ' + ($valid) + ' = true , j; if (i > 1) { ';
- var $itemType = it.schema.items && it.schema.items.type,
- $typeIsArray = Array.isArray($itemType);
- if (!$itemType || $itemType == 'object' || $itemType == 'array' || ($typeIsArray && ($itemType.indexOf('object') >= 0 || $itemType.indexOf('array') >= 0))) {
- out += ' outer: for (;i--;) { for (j = i; j--;) { if (equal(' + ($data) + '[i], ' + ($data) + '[j])) { ' + ($valid) + ' = false; break outer; } } } ';
- } else {
- out += ' var itemIndices = {}, item; for (;i--;) { var item = ' + ($data) + '[i]; ';
- var $method = 'checkDataType' + ($typeIsArray ? 's' : '');
- out += ' if (' + (it.util[$method]($itemType, 'item', true)) + ') continue; ';
- if ($typeIsArray) {
- out += ' if (typeof item == \'string\') item = \'"\' + item; ';
- }
- out += ' if (typeof itemIndices[item] == \'number\') { ' + ($valid) + ' = false; j = itemIndices[item]; break; } itemIndices[item] = i; } ';
- }
- out += ' } ';
- if ($isData) {
- out += ' } ';
- }
- out += ' if (!' + ($valid) + ') { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ('uniqueItems') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { i: i, j: j } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should NOT have duplicate items (items ## \' + j + \' and \' + i + \' are identical)\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: ';
- if ($isData) {
- out += 'validate.schema' + ($schemaPath);
- } else {
- out += '' + ($schema);
- }
- out += ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } ';
- if ($breakOnError) {
- out += ' else { ';
- }
- } else {
- if ($breakOnError) {
- out += ' if (true) { ';
- }
- }
- return out;
-}
-
-},{}],46:[function(require,module,exports){
-'use strict';
-module.exports = function generate_validate(it, $keyword, $ruleType) {
- var out = '';
- var $async = it.schema.$async === true,
- $refKeywords = it.util.schemaHasRulesExcept(it.schema, it.RULES.all, '$ref'),
- $id = it.self._getId(it.schema);
- if (it.opts.strictKeywords) {
- var $unknownKwd = it.util.schemaUnknownRules(it.schema, it.RULES.keywords);
- if ($unknownKwd) {
- var $keywordsMsg = 'unknown keyword: ' + $unknownKwd;
- if (it.opts.strictKeywords === 'log') it.logger.warn($keywordsMsg);
- else throw new Error($keywordsMsg);
- }
- }
- if (it.isTop) {
- out += ' var validate = ';
- if ($async) {
- it.async = true;
- out += 'async ';
- }
- out += 'function(data, dataPath, parentData, parentDataProperty, rootData) { \'use strict\'; ';
- if ($id && (it.opts.sourceCode || it.opts.processCode)) {
- out += ' ' + ('/\*# sourceURL=' + $id + ' */') + ' ';
- }
- }
- if (typeof it.schema == 'boolean' || !($refKeywords || it.schema.$ref)) {
- var $keyword = 'false schema';
- var $lvl = it.level;
- var $dataLvl = it.dataLevel;
- var $schema = it.schema[$keyword];
- var $schemaPath = it.schemaPath + it.util.getProperty($keyword);
- var $errSchemaPath = it.errSchemaPath + '/' + $keyword;
- var $breakOnError = !it.opts.allErrors;
- var $errorKeyword;
- var $data = 'data' + ($dataLvl || '');
- var $valid = 'valid' + $lvl;
- if (it.schema === false) {
- if (it.isTop) {
- $breakOnError = true;
- } else {
- out += ' var ' + ($valid) + ' = false; ';
- }
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || 'false schema') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: {} ';
- if (it.opts.messages !== false) {
- out += ' , message: \'boolean schema is false\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: false , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- } else {
- if (it.isTop) {
- if ($async) {
- out += ' return data; ';
- } else {
- out += ' validate.errors = null; return true; ';
- }
- } else {
- out += ' var ' + ($valid) + ' = true; ';
- }
- }
- if (it.isTop) {
- out += ' }; return validate; ';
- }
- return out;
- }
- if (it.isTop) {
- var $top = it.isTop,
- $lvl = it.level = 0,
- $dataLvl = it.dataLevel = 0,
- $data = 'data';
- it.rootId = it.resolve.fullPath(it.self._getId(it.root.schema));
- it.baseId = it.baseId || it.rootId;
- delete it.isTop;
- it.dataPathArr = [undefined];
- if (it.schema.default !== undefined && it.opts.useDefaults && it.opts.strictDefaults) {
- var $defaultMsg = 'default is ignored in the schema root';
- if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
- else throw new Error($defaultMsg);
- }
- out += ' var vErrors = null; ';
- out += ' var errors = 0; ';
- out += ' if (rootData === undefined) rootData = data; ';
- } else {
- var $lvl = it.level,
- $dataLvl = it.dataLevel,
- $data = 'data' + ($dataLvl || '');
- if ($id) it.baseId = it.resolve.url(it.baseId, $id);
- if ($async && !it.async) throw new Error('async schema in sync schema');
- out += ' var errs_' + ($lvl) + ' = errors;';
- }
- var $valid = 'valid' + $lvl,
- $breakOnError = !it.opts.allErrors,
- $closingBraces1 = '',
- $closingBraces2 = '';
- var $errorKeyword;
- var $typeSchema = it.schema.type,
- $typeIsArray = Array.isArray($typeSchema);
- if ($typeSchema && it.opts.nullable && it.schema.nullable === true) {
- if ($typeIsArray) {
- if ($typeSchema.indexOf('null') == -1) $typeSchema = $typeSchema.concat('null');
- } else if ($typeSchema != 'null') {
- $typeSchema = [$typeSchema, 'null'];
- $typeIsArray = true;
- }
- }
- if ($typeIsArray && $typeSchema.length == 1) {
- $typeSchema = $typeSchema[0];
- $typeIsArray = false;
- }
- if (it.schema.$ref && $refKeywords) {
- if (it.opts.extendRefs == 'fail') {
- throw new Error('$ref: validation keywords used in schema at path "' + it.errSchemaPath + '" (see option extendRefs)');
- } else if (it.opts.extendRefs !== true) {
- $refKeywords = false;
- it.logger.warn('$ref: keywords ignored in schema at path "' + it.errSchemaPath + '"');
- }
- }
- if (it.schema.$comment && it.opts.$comment) {
- out += ' ' + (it.RULES.all.$comment.code(it, '$comment'));
- }
- if ($typeSchema) {
- if (it.opts.coerceTypes) {
- var $coerceToTypes = it.util.coerceToTypes(it.opts.coerceTypes, $typeSchema);
- }
- var $rulesGroup = it.RULES.types[$typeSchema];
- if ($coerceToTypes || $typeIsArray || $rulesGroup === true || ($rulesGroup && !$shouldUseGroup($rulesGroup))) {
- var $schemaPath = it.schemaPath + '.type',
- $errSchemaPath = it.errSchemaPath + '/type';
- var $schemaPath = it.schemaPath + '.type',
- $errSchemaPath = it.errSchemaPath + '/type',
- $method = $typeIsArray ? 'checkDataTypes' : 'checkDataType';
- out += ' if (' + (it.util[$method]($typeSchema, $data, true)) + ') { ';
- if ($coerceToTypes) {
- var $dataType = 'dataType' + $lvl,
- $coerced = 'coerced' + $lvl;
- out += ' var ' + ($dataType) + ' = typeof ' + ($data) + '; ';
- if (it.opts.coerceTypes == 'array') {
- out += ' if (' + ($dataType) + ' == \'object\' && Array.isArray(' + ($data) + ')) ' + ($dataType) + ' = \'array\'; ';
- }
- out += ' var ' + ($coerced) + ' = undefined; ';
- var $bracesCoercion = '';
- var arr1 = $coerceToTypes;
- if (arr1) {
- var $type, $i = -1,
- l1 = arr1.length - 1;
- while ($i < l1) {
- $type = arr1[$i += 1];
- if ($i) {
- out += ' if (' + ($coerced) + ' === undefined) { ';
- $bracesCoercion += '}';
- }
- if (it.opts.coerceTypes == 'array' && $type != 'array') {
- out += ' if (' + ($dataType) + ' == \'array\' && ' + ($data) + '.length == 1) { ' + ($coerced) + ' = ' + ($data) + ' = ' + ($data) + '[0]; ' + ($dataType) + ' = typeof ' + ($data) + '; } ';
- }
- if ($type == 'string') {
- out += ' if (' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\') ' + ($coerced) + ' = \'\' + ' + ($data) + '; else if (' + ($data) + ' === null) ' + ($coerced) + ' = \'\'; ';
- } else if ($type == 'number' || $type == 'integer') {
- out += ' if (' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' === null || (' + ($dataType) + ' == \'string\' && ' + ($data) + ' && ' + ($data) + ' == +' + ($data) + ' ';
- if ($type == 'integer') {
- out += ' && !(' + ($data) + ' % 1)';
- }
- out += ')) ' + ($coerced) + ' = +' + ($data) + '; ';
- } else if ($type == 'boolean') {
- out += ' if (' + ($data) + ' === \'false\' || ' + ($data) + ' === 0 || ' + ($data) + ' === null) ' + ($coerced) + ' = false; else if (' + ($data) + ' === \'true\' || ' + ($data) + ' === 1) ' + ($coerced) + ' = true; ';
- } else if ($type == 'null') {
- out += ' if (' + ($data) + ' === \'\' || ' + ($data) + ' === 0 || ' + ($data) + ' === false) ' + ($coerced) + ' = null; ';
- } else if (it.opts.coerceTypes == 'array' && $type == 'array') {
- out += ' if (' + ($dataType) + ' == \'string\' || ' + ($dataType) + ' == \'number\' || ' + ($dataType) + ' == \'boolean\' || ' + ($data) + ' == null) ' + ($coerced) + ' = [' + ($data) + ']; ';
- }
- }
- }
- out += ' ' + ($bracesCoercion) + ' if (' + ($coerced) + ' === undefined) { ';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be ';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } else { ';
- var $parentData = $dataLvl ? 'data' + (($dataLvl - 1) || '') : 'parentData',
- $parentDataProperty = $dataLvl ? it.dataPathArr[$dataLvl] : 'parentDataProperty';
- out += ' ' + ($data) + ' = ' + ($coerced) + '; ';
- if (!$dataLvl) {
- out += 'if (' + ($parentData) + ' !== undefined)';
- }
- out += ' ' + ($parentData) + '[' + ($parentDataProperty) + '] = ' + ($coerced) + '; } ';
- } else {
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be ';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- }
- out += ' } ';
- }
- }
- if (it.schema.$ref && !$refKeywords) {
- out += ' ' + (it.RULES.all.$ref.code(it, '$ref')) + ' ';
- if ($breakOnError) {
- out += ' } if (errors === ';
- if ($top) {
- out += '0';
- } else {
- out += 'errs_' + ($lvl);
- }
- out += ') { ';
- $closingBraces2 += '}';
- }
- } else {
- var arr2 = it.RULES;
- if (arr2) {
- var $rulesGroup, i2 = -1,
- l2 = arr2.length - 1;
- while (i2 < l2) {
- $rulesGroup = arr2[i2 += 1];
- if ($shouldUseGroup($rulesGroup)) {
- if ($rulesGroup.type) {
- out += ' if (' + (it.util.checkDataType($rulesGroup.type, $data)) + ') { ';
- }
- if (it.opts.useDefaults) {
- if ($rulesGroup.type == 'object' && it.schema.properties) {
- var $schema = it.schema.properties,
- $schemaKeys = Object.keys($schema);
- var arr3 = $schemaKeys;
- if (arr3) {
- var $propertyKey, i3 = -1,
- l3 = arr3.length - 1;
- while (i3 < l3) {
- $propertyKey = arr3[i3 += 1];
- var $sch = $schema[$propertyKey];
- if ($sch.default !== undefined) {
- var $passData = $data + it.util.getProperty($propertyKey);
- if (it.compositeRule) {
- if (it.opts.strictDefaults) {
- var $defaultMsg = 'default is ignored for: ' + $passData;
- if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
- else throw new Error($defaultMsg);
- }
- } else {
- out += ' if (' + ($passData) + ' === undefined ';
- if (it.opts.useDefaults == 'empty') {
- out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
- }
- out += ' ) ' + ($passData) + ' = ';
- if (it.opts.useDefaults == 'shared') {
- out += ' ' + (it.useDefault($sch.default)) + ' ';
- } else {
- out += ' ' + (JSON.stringify($sch.default)) + ' ';
- }
- out += '; ';
- }
- }
- }
- }
- } else if ($rulesGroup.type == 'array' && Array.isArray(it.schema.items)) {
- var arr4 = it.schema.items;
- if (arr4) {
- var $sch, $i = -1,
- l4 = arr4.length - 1;
- while ($i < l4) {
- $sch = arr4[$i += 1];
- if ($sch.default !== undefined) {
- var $passData = $data + '[' + $i + ']';
- if (it.compositeRule) {
- if (it.opts.strictDefaults) {
- var $defaultMsg = 'default is ignored for: ' + $passData;
- if (it.opts.strictDefaults === 'log') it.logger.warn($defaultMsg);
- else throw new Error($defaultMsg);
- }
- } else {
- out += ' if (' + ($passData) + ' === undefined ';
- if (it.opts.useDefaults == 'empty') {
- out += ' || ' + ($passData) + ' === null || ' + ($passData) + ' === \'\' ';
- }
- out += ' ) ' + ($passData) + ' = ';
- if (it.opts.useDefaults == 'shared') {
- out += ' ' + (it.useDefault($sch.default)) + ' ';
- } else {
- out += ' ' + (JSON.stringify($sch.default)) + ' ';
- }
- out += '; ';
- }
- }
- }
- }
- }
- }
- var arr5 = $rulesGroup.rules;
- if (arr5) {
- var $rule, i5 = -1,
- l5 = arr5.length - 1;
- while (i5 < l5) {
- $rule = arr5[i5 += 1];
- if ($shouldUseRule($rule)) {
- var $code = $rule.code(it, $rule.keyword, $rulesGroup.type);
- if ($code) {
- out += ' ' + ($code) + ' ';
- if ($breakOnError) {
- $closingBraces1 += '}';
- }
- }
- }
- }
- }
- if ($breakOnError) {
- out += ' ' + ($closingBraces1) + ' ';
- $closingBraces1 = '';
- }
- if ($rulesGroup.type) {
- out += ' } ';
- if ($typeSchema && $typeSchema === $rulesGroup.type && !$coerceToTypes) {
- out += ' else { ';
- var $schemaPath = it.schemaPath + '.type',
- $errSchemaPath = it.errSchemaPath + '/type';
- var $$outStack = $$outStack || [];
- $$outStack.push(out);
- out = ''; /* istanbul ignore else */
- if (it.createErrors !== false) {
- out += ' { keyword: \'' + ($errorKeyword || 'type') + '\' , dataPath: (dataPath || \'\') + ' + (it.errorPath) + ' , schemaPath: ' + (it.util.toQuotedString($errSchemaPath)) + ' , params: { type: \'';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' } ';
- if (it.opts.messages !== false) {
- out += ' , message: \'should be ';
- if ($typeIsArray) {
- out += '' + ($typeSchema.join(","));
- } else {
- out += '' + ($typeSchema);
- }
- out += '\' ';
- }
- if (it.opts.verbose) {
- out += ' , schema: validate.schema' + ($schemaPath) + ' , parentSchema: validate.schema' + (it.schemaPath) + ' , data: ' + ($data) + ' ';
- }
- out += ' } ';
- } else {
- out += ' {} ';
- }
- var __err = out;
- out = $$outStack.pop();
- if (!it.compositeRule && $breakOnError) {
- /* istanbul ignore if */
- if (it.async) {
- out += ' throw new ValidationError([' + (__err) + ']); ';
- } else {
- out += ' validate.errors = [' + (__err) + ']; return false; ';
- }
- } else {
- out += ' var err = ' + (__err) + '; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ';
- }
- out += ' } ';
- }
- }
- if ($breakOnError) {
- out += ' if (errors === ';
- if ($top) {
- out += '0';
- } else {
- out += 'errs_' + ($lvl);
- }
- out += ') { ';
- $closingBraces2 += '}';
- }
- }
- }
- }
- }
- if ($breakOnError) {
- out += ' ' + ($closingBraces2) + ' ';
- }
- if ($top) {
- if ($async) {
- out += ' if (errors === 0) return data; ';
- out += ' else throw new ValidationError(vErrors); ';
- } else {
- out += ' validate.errors = vErrors; ';
- out += ' return errors === 0; ';
- }
- out += ' }; return validate;';
- } else {
- out += ' var ' + ($valid) + ' = errors === errs_' + ($lvl) + ';';
- }
- out = it.util.cleanUpCode(out);
- if ($top) {
- out = it.util.finalCleanUpCode(out, $async);
- }
-
- function $shouldUseGroup($rulesGroup) {
- var rules = $rulesGroup.rules;
- for (var i = 0; i < rules.length; i++)
- if ($shouldUseRule(rules[i])) return true;
- }
-
- function $shouldUseRule($rule) {
- return it.schema[$rule.keyword] !== undefined || ($rule.implements && $ruleImplementsSomeKeyword($rule));
- }
-
- function $ruleImplementsSomeKeyword($rule) {
- var impl = $rule.implements;
- for (var i = 0; i < impl.length; i++)
- if (it.schema[impl[i]] !== undefined) return true;
- }
- return out;
-}
-
-},{}],47:[function(require,module,exports){
-'use strict';
-
-var IDENTIFIER = /^[a-z_$][a-z0-9_$-]*$/i;
-var customRuleCode = require('./dotjs/custom');
-var definitionSchema = require('./definition_schema');
-
-module.exports = {
- add: addKeyword,
- get: getKeyword,
- remove: removeKeyword,
- validate: validateKeyword
-};
-
-
-/**
- * Define custom keyword
- * @this Ajv
- * @param {String} keyword custom keyword, should be unique (including different from all standard, custom and macro keywords).
- * @param {Object} definition keyword definition object with properties `type` (type(s) which the keyword applies to), `validate` or `compile`.
- * @return {Ajv} this for method chaining
- */
-function addKeyword(keyword, definition) {
- /* jshint validthis: true */
- /* eslint no-shadow: 0 */
- var RULES = this.RULES;
- if (RULES.keywords[keyword])
- throw new Error('Keyword ' + keyword + ' is already defined');
-
- if (!IDENTIFIER.test(keyword))
- throw new Error('Keyword ' + keyword + ' is not a valid identifier');
-
- if (definition) {
- this.validateKeyword(definition, true);
-
- var dataType = definition.type;
- if (Array.isArray(dataType)) {
- for (var i=0; i= 0.12
- * 3. Auto detected promise based on first sucessful require of
- * known promise libraries. Note this is a last resort, as the
- * loaded library is non-deterministic. node.js >= 0.12 will
- * always use global.Promise over this priority list.
- * 4. Throws error.
- *
- * For Browser:
- *
- * 1. Previous registration
- * 2. window.Promise
- * 3. Throws error.
- *
- * Options:
- *
- * Promise: Desired Promise constructor
- * global: Boolean - Should the registration be cached in a global variable to
- * allow cross dependency/bundle registration? (default true)
- */
-module.exports = function(root, loadImplementation){
- return function register(implementation, opts){
- implementation = implementation || null
- opts = opts || {}
- // global registration unless explicitly {global: false} in options (default true)
- var registerGlobal = opts.global !== false;
-
- // load any previous global registration
- if(registered === null && registerGlobal){
- registered = root[REGISTRATION_KEY] || null
- }
-
- if(registered !== null
- && implementation !== null
- && registered.implementation !== implementation){
- // Throw error if attempting to redefine implementation
- throw new Error('any-promise already defined as "'+registered.implementation+
- '". You can only register an implementation before the first '+
- ' call to require("any-promise") and an implementation cannot be changed')
- }
-
- if(registered === null){
- // use provided implementation
- if(implementation !== null && typeof opts.Promise !== 'undefined'){
- registered = {
- Promise: opts.Promise,
- implementation: implementation
- }
- } else {
- // require implementation if implementation is specified but not provided
- registered = loadImplementation(implementation)
- }
-
- if(registerGlobal){
- // register preference globally in case multiple installations
- root[REGISTRATION_KEY] = registered
- }
- }
-
- return registered
- }
-}
-
-},{}],53:[function(require,module,exports){
-"use strict";
-module.exports = require('./loader')(window, loadImplementation)
-
-/**
- * Browser specific loadImplementation. Always uses `window.Promise`
- *
- * To register a custom implementation, must register with `Promise` option.
- */
-function loadImplementation(){
- if(typeof window.Promise === 'undefined'){
- throw new Error("any-promise browser requires a polyfill or explicit registration"+
- " e.g: require('any-promise/register/bluebird')")
- }
- return {
- Promise: window.Promise,
- implementation: 'window.Promise'
- }
-}
-
-},{"./loader":52}],54:[function(require,module,exports){
+},{}],9:[function(require,module,exports){
'use strict';
module.exports = function (arr) {
if (!Array.isArray(arr)) {
@@ -7139,7 +655,7 @@ module.exports = function (arr) {
return ret;
};
-},{}],55:[function(require,module,exports){
+},{}],10:[function(require,module,exports){
/**
* An abstraction for slicing an arraybuffer even when
* ArrayBuffer.prototype.slice is not supported
@@ -7170,7 +686,7 @@ module.exports = function(arraybuffer, start, end) {
return result.buffer;
};
-},{}],56:[function(require,module,exports){
+},{}],11:[function(require,module,exports){
var asn1 = exports;
asn1.bignum = require('bn.js');
@@ -7181,7 +697,7 @@ asn1.constants = require('./asn1/constants');
asn1.decoders = require('./asn1/decoders');
asn1.encoders = require('./asn1/encoders');
-},{"./asn1/api":57,"./asn1/base":59,"./asn1/constants":63,"./asn1/decoders":65,"./asn1/encoders":68,"bn.js":171}],57:[function(require,module,exports){
+},{"./asn1/api":12,"./asn1/base":14,"./asn1/constants":18,"./asn1/decoders":20,"./asn1/encoders":23,"bn.js":135}],12:[function(require,module,exports){
var asn1 = require('../asn1');
var inherits = require('inherits');
@@ -7244,7 +760,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
return this._getEncoder(enc).encode(data, reporter);
};
-},{"../asn1":56,"inherits":453,"vm":1788}],58:[function(require,module,exports){
+},{"../asn1":11,"inherits":317,"vm":1523}],13:[function(require,module,exports){
var inherits = require('inherits');
var Reporter = require('../base').Reporter;
var Buffer = require('buffer').Buffer;
@@ -7362,7 +878,7 @@ EncoderBuffer.prototype.join = function join(out, offset) {
return out;
};
-},{"../base":59,"buffer":217,"inherits":453}],59:[function(require,module,exports){
+},{"../base":14,"buffer":181,"inherits":317}],14:[function(require,module,exports){
var base = exports;
base.Reporter = require('./reporter').Reporter;
@@ -7370,7 +886,7 @@ base.DecoderBuffer = require('./buffer').DecoderBuffer;
base.EncoderBuffer = require('./buffer').EncoderBuffer;
base.Node = require('./node');
-},{"./buffer":58,"./node":60,"./reporter":61}],60:[function(require,module,exports){
+},{"./buffer":13,"./node":15,"./reporter":16}],15:[function(require,module,exports){
var Reporter = require('../base').Reporter;
var EncoderBuffer = require('../base').EncoderBuffer;
var DecoderBuffer = require('../base').DecoderBuffer;
@@ -8006,7 +1522,7 @@ Node.prototype._isPrintstr = function isPrintstr(str) {
return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
};
-},{"../base":59,"minimalistic-assert":1303}],61:[function(require,module,exports){
+},{"../base":14,"minimalistic-assert":1129}],16:[function(require,module,exports){
var inherits = require('inherits');
function Reporter(options) {
@@ -8129,7 +1645,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) {
return this;
};
-},{"inherits":453}],62:[function(require,module,exports){
+},{"inherits":317}],17:[function(require,module,exports){
var constants = require('../constants');
exports.tagClass = {
@@ -8173,7 +1689,7 @@ exports.tag = {
};
exports.tagByName = constants._reverse(exports.tag);
-},{"../constants":63}],63:[function(require,module,exports){
+},{"../constants":18}],18:[function(require,module,exports){
var constants = exports;
// Helper
@@ -8194,7 +1710,7 @@ constants._reverse = function reverse(map) {
constants.der = require('./der');
-},{"./der":62}],64:[function(require,module,exports){
+},{"./der":17}],19:[function(require,module,exports){
var inherits = require('inherits');
var asn1 = require('../../asn1');
@@ -8520,13 +2036,13 @@ function derDecodeLen(buf, primitive, fail) {
return len;
}
-},{"../../asn1":56,"inherits":453}],65:[function(require,module,exports){
+},{"../../asn1":11,"inherits":317}],20:[function(require,module,exports){
var decoders = exports;
decoders.der = require('./der');
decoders.pem = require('./pem');
-},{"./der":64,"./pem":66}],66:[function(require,module,exports){
+},{"./der":19,"./pem":21}],21:[function(require,module,exports){
var inherits = require('inherits');
var Buffer = require('buffer').Buffer;
@@ -8577,7 +2093,7 @@ PEMDecoder.prototype.decode = function decode(data, options) {
return DERDecoder.prototype.decode.call(this, input, options);
};
-},{"./der":64,"buffer":217,"inherits":453}],67:[function(require,module,exports){
+},{"./der":19,"buffer":181,"inherits":317}],22:[function(require,module,exports){
var inherits = require('inherits');
var Buffer = require('buffer').Buffer;
@@ -8874,13 +2390,13 @@ function encodeTag(tag, primitive, cls, reporter) {
return res;
}
-},{"../../asn1":56,"buffer":217,"inherits":453}],68:[function(require,module,exports){
+},{"../../asn1":11,"buffer":181,"inherits":317}],23:[function(require,module,exports){
var encoders = exports;
encoders.der = require('./der');
encoders.pem = require('./pem');
-},{"./der":67,"./pem":69}],69:[function(require,module,exports){
+},{"./der":22,"./pem":24}],24:[function(require,module,exports){
var inherits = require('inherits');
var DEREncoder = require('./der');
@@ -8903,694 +2419,7 @@ PEMEncoder.prototype.encode = function encode(data, options) {
return out.join('\n');
};
-},{"./der":67,"inherits":453}],70:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-
-module.exports = {
-
- newInvalidAsn1Error: function (msg) {
- var e = new Error();
- e.name = 'InvalidAsn1Error';
- e.message = msg || '';
- return e;
- }
-
-};
-
-},{}],71:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-var errors = require('./errors');
-var types = require('./types');
-
-var Reader = require('./reader');
-var Writer = require('./writer');
-
-
-// --- Exports
-
-module.exports = {
-
- Reader: Reader,
-
- Writer: Writer
-
-};
-
-for (var t in types) {
- if (types.hasOwnProperty(t))
- module.exports[t] = types[t];
-}
-for (var e in errors) {
- if (errors.hasOwnProperty(e))
- module.exports[e] = errors[e];
-}
-
-},{"./errors":70,"./reader":72,"./types":73,"./writer":74}],72:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-var assert = require('assert');
-var Buffer = require('safer-buffer').Buffer;
-
-var ASN1 = require('./types');
-var errors = require('./errors');
-
-
-// --- Globals
-
-var newInvalidAsn1Error = errors.newInvalidAsn1Error;
-
-
-
-// --- API
-
-function Reader(data) {
- if (!data || !Buffer.isBuffer(data))
- throw new TypeError('data must be a node Buffer');
-
- this._buf = data;
- this._size = data.length;
-
- // These hold the "current" state
- this._len = 0;
- this._offset = 0;
-}
-
-Object.defineProperty(Reader.prototype, 'length', {
- enumerable: true,
- get: function () { return (this._len); }
-});
-
-Object.defineProperty(Reader.prototype, 'offset', {
- enumerable: true,
- get: function () { return (this._offset); }
-});
-
-Object.defineProperty(Reader.prototype, 'remain', {
- get: function () { return (this._size - this._offset); }
-});
-
-Object.defineProperty(Reader.prototype, 'buffer', {
- get: function () { return (this._buf.slice(this._offset)); }
-});
-
-
-/**
- * Reads a single byte and advances offset; you can pass in `true` to make this
- * a "peek" operation (i.e., get the byte, but don't advance the offset).
- *
- * @param {Boolean} peek true means don't move offset.
- * @return {Number} the next byte, null if not enough data.
- */
-Reader.prototype.readByte = function (peek) {
- if (this._size - this._offset < 1)
- return null;
-
- var b = this._buf[this._offset] & 0xff;
-
- if (!peek)
- this._offset += 1;
-
- return b;
-};
-
-
-Reader.prototype.peek = function () {
- return this.readByte(true);
-};
-
-
-/**
- * Reads a (potentially) variable length off the BER buffer. This call is
- * not really meant to be called directly, as callers have to manipulate
- * the internal buffer afterwards.
- *
- * As a result of this call, you can call `Reader.length`, until the
- * next thing called that does a readLength.
- *
- * @return {Number} the amount of offset to advance the buffer.
- * @throws {InvalidAsn1Error} on bad ASN.1
- */
-Reader.prototype.readLength = function (offset) {
- if (offset === undefined)
- offset = this._offset;
-
- if (offset >= this._size)
- return null;
-
- var lenB = this._buf[offset++] & 0xff;
- if (lenB === null)
- return null;
-
- if ((lenB & 0x80) === 0x80) {
- lenB &= 0x7f;
-
- if (lenB === 0)
- throw newInvalidAsn1Error('Indefinite length not supported');
-
- if (lenB > 4)
- throw newInvalidAsn1Error('encoding too long');
-
- if (this._size - offset < lenB)
- return null;
-
- this._len = 0;
- for (var i = 0; i < lenB; i++)
- this._len = (this._len << 8) + (this._buf[offset++] & 0xff);
-
- } else {
- // Wasn't a variable length
- this._len = lenB;
- }
-
- return offset;
-};
-
-
-/**
- * Parses the next sequence in this BER buffer.
- *
- * To get the length of the sequence, call `Reader.length`.
- *
- * @return {Number} the sequence's tag.
- */
-Reader.prototype.readSequence = function (tag) {
- var seq = this.peek();
- if (seq === null)
- return null;
- if (tag !== undefined && tag !== seq)
- throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
- ': got 0x' + seq.toString(16));
-
- var o = this.readLength(this._offset + 1); // stored in `length`
- if (o === null)
- return null;
-
- this._offset = o;
- return seq;
-};
-
-
-Reader.prototype.readInt = function () {
- return this._readTag(ASN1.Integer);
-};
-
-
-Reader.prototype.readBoolean = function () {
- return (this._readTag(ASN1.Boolean) === 0 ? false : true);
-};
-
-
-Reader.prototype.readEnumeration = function () {
- return this._readTag(ASN1.Enumeration);
-};
-
-
-Reader.prototype.readString = function (tag, retbuf) {
- if (!tag)
- tag = ASN1.OctetString;
-
- var b = this.peek();
- if (b === null)
- return null;
-
- if (b !== tag)
- throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
- ': got 0x' + b.toString(16));
-
- var o = this.readLength(this._offset + 1); // stored in `length`
-
- if (o === null)
- return null;
-
- if (this.length > this._size - o)
- return null;
-
- this._offset = o;
-
- if (this.length === 0)
- return retbuf ? Buffer.alloc(0) : '';
-
- var str = this._buf.slice(this._offset, this._offset + this.length);
- this._offset += this.length;
-
- return retbuf ? str : str.toString('utf8');
-};
-
-Reader.prototype.readOID = function (tag) {
- if (!tag)
- tag = ASN1.OID;
-
- var b = this.readString(tag, true);
- if (b === null)
- return null;
-
- var values = [];
- var value = 0;
-
- for (var i = 0; i < b.length; i++) {
- var byte = b[i] & 0xff;
-
- value <<= 7;
- value += byte & 0x7f;
- if ((byte & 0x80) === 0) {
- values.push(value);
- value = 0;
- }
- }
-
- value = values.shift();
- values.unshift(value % 40);
- values.unshift((value / 40) >> 0);
-
- return values.join('.');
-};
-
-
-Reader.prototype._readTag = function (tag) {
- assert.ok(tag !== undefined);
-
- var b = this.peek();
-
- if (b === null)
- return null;
-
- if (b !== tag)
- throw newInvalidAsn1Error('Expected 0x' + tag.toString(16) +
- ': got 0x' + b.toString(16));
-
- var o = this.readLength(this._offset + 1); // stored in `length`
- if (o === null)
- return null;
-
- if (this.length > 4)
- throw newInvalidAsn1Error('Integer too long: ' + this.length);
-
- if (this.length > this._size - o)
- return null;
- this._offset = o;
-
- var fb = this._buf[this._offset];
- var value = 0;
-
- for (var i = 0; i < this.length; i++) {
- value <<= 8;
- value |= (this._buf[this._offset++] & 0xff);
- }
-
- if ((fb & 0x80) === 0x80 && i !== 4)
- value -= (1 << (i * 8));
-
- return value >> 0;
-};
-
-
-
-// --- Exported API
-
-module.exports = Reader;
-
-},{"./errors":70,"./types":73,"assert":78,"safer-buffer":1594}],73:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-
-module.exports = {
- EOC: 0,
- Boolean: 1,
- Integer: 2,
- BitString: 3,
- OctetString: 4,
- Null: 5,
- OID: 6,
- ObjectDescriptor: 7,
- External: 8,
- Real: 9, // float
- Enumeration: 10,
- PDV: 11,
- Utf8String: 12,
- RelativeOID: 13,
- Sequence: 16,
- Set: 17,
- NumericString: 18,
- PrintableString: 19,
- T61String: 20,
- VideotexString: 21,
- IA5String: 22,
- UTCTime: 23,
- GeneralizedTime: 24,
- GraphicString: 25,
- VisibleString: 26,
- GeneralString: 28,
- UniversalString: 29,
- CharacterString: 30,
- BMPString: 31,
- Constructor: 32,
- Context: 128
-};
-
-},{}],74:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-var assert = require('assert');
-var Buffer = require('safer-buffer').Buffer;
-var ASN1 = require('./types');
-var errors = require('./errors');
-
-
-// --- Globals
-
-var newInvalidAsn1Error = errors.newInvalidAsn1Error;
-
-var DEFAULT_OPTS = {
- size: 1024,
- growthFactor: 8
-};
-
-
-// --- Helpers
-
-function merge(from, to) {
- assert.ok(from);
- assert.equal(typeof (from), 'object');
- assert.ok(to);
- assert.equal(typeof (to), 'object');
-
- var keys = Object.getOwnPropertyNames(from);
- keys.forEach(function (key) {
- if (to[key])
- return;
-
- var value = Object.getOwnPropertyDescriptor(from, key);
- Object.defineProperty(to, key, value);
- });
-
- return to;
-}
-
-
-
-// --- API
-
-function Writer(options) {
- options = merge(DEFAULT_OPTS, options || {});
-
- this._buf = Buffer.alloc(options.size || 1024);
- this._size = this._buf.length;
- this._offset = 0;
- this._options = options;
-
- // A list of offsets in the buffer where we need to insert
- // sequence tag/len pairs.
- this._seq = [];
-}
-
-Object.defineProperty(Writer.prototype, 'buffer', {
- get: function () {
- if (this._seq.length)
- throw newInvalidAsn1Error(this._seq.length + ' unended sequence(s)');
-
- return (this._buf.slice(0, this._offset));
- }
-});
-
-Writer.prototype.writeByte = function (b) {
- if (typeof (b) !== 'number')
- throw new TypeError('argument must be a Number');
-
- this._ensure(1);
- this._buf[this._offset++] = b;
-};
-
-
-Writer.prototype.writeInt = function (i, tag) {
- if (typeof (i) !== 'number')
- throw new TypeError('argument must be a Number');
- if (typeof (tag) !== 'number')
- tag = ASN1.Integer;
-
- var sz = 4;
-
- while ((((i & 0xff800000) === 0) || ((i & 0xff800000) === 0xff800000 >> 0)) &&
- (sz > 1)) {
- sz--;
- i <<= 8;
- }
-
- if (sz > 4)
- throw newInvalidAsn1Error('BER ints cannot be > 0xffffffff');
-
- this._ensure(2 + sz);
- this._buf[this._offset++] = tag;
- this._buf[this._offset++] = sz;
-
- while (sz-- > 0) {
- this._buf[this._offset++] = ((i & 0xff000000) >>> 24);
- i <<= 8;
- }
-
-};
-
-
-Writer.prototype.writeNull = function () {
- this.writeByte(ASN1.Null);
- this.writeByte(0x00);
-};
-
-
-Writer.prototype.writeEnumeration = function (i, tag) {
- if (typeof (i) !== 'number')
- throw new TypeError('argument must be a Number');
- if (typeof (tag) !== 'number')
- tag = ASN1.Enumeration;
-
- return this.writeInt(i, tag);
-};
-
-
-Writer.prototype.writeBoolean = function (b, tag) {
- if (typeof (b) !== 'boolean')
- throw new TypeError('argument must be a Boolean');
- if (typeof (tag) !== 'number')
- tag = ASN1.Boolean;
-
- this._ensure(3);
- this._buf[this._offset++] = tag;
- this._buf[this._offset++] = 0x01;
- this._buf[this._offset++] = b ? 0xff : 0x00;
-};
-
-
-Writer.prototype.writeString = function (s, tag) {
- if (typeof (s) !== 'string')
- throw new TypeError('argument must be a string (was: ' + typeof (s) + ')');
- if (typeof (tag) !== 'number')
- tag = ASN1.OctetString;
-
- var len = Buffer.byteLength(s);
- this.writeByte(tag);
- this.writeLength(len);
- if (len) {
- this._ensure(len);
- this._buf.write(s, this._offset);
- this._offset += len;
- }
-};
-
-
-Writer.prototype.writeBuffer = function (buf, tag) {
- if (typeof (tag) !== 'number')
- throw new TypeError('tag must be a number');
- if (!Buffer.isBuffer(buf))
- throw new TypeError('argument must be a buffer');
-
- this.writeByte(tag);
- this.writeLength(buf.length);
- this._ensure(buf.length);
- buf.copy(this._buf, this._offset, 0, buf.length);
- this._offset += buf.length;
-};
-
-
-Writer.prototype.writeStringArray = function (strings) {
- if ((!strings instanceof Array))
- throw new TypeError('argument must be an Array[String]');
-
- var self = this;
- strings.forEach(function (s) {
- self.writeString(s);
- });
-};
-
-// This is really to solve DER cases, but whatever for now
-Writer.prototype.writeOID = function (s, tag) {
- if (typeof (s) !== 'string')
- throw new TypeError('argument must be a string');
- if (typeof (tag) !== 'number')
- tag = ASN1.OID;
-
- if (!/^([0-9]+\.){3,}[0-9]+$/.test(s))
- throw new Error('argument is not a valid OID string');
-
- function encodeOctet(bytes, octet) {
- if (octet < 128) {
- bytes.push(octet);
- } else if (octet < 16384) {
- bytes.push((octet >>> 7) | 0x80);
- bytes.push(octet & 0x7F);
- } else if (octet < 2097152) {
- bytes.push((octet >>> 14) | 0x80);
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
- bytes.push(octet & 0x7F);
- } else if (octet < 268435456) {
- bytes.push((octet >>> 21) | 0x80);
- bytes.push(((octet >>> 14) | 0x80) & 0xFF);
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
- bytes.push(octet & 0x7F);
- } else {
- bytes.push(((octet >>> 28) | 0x80) & 0xFF);
- bytes.push(((octet >>> 21) | 0x80) & 0xFF);
- bytes.push(((octet >>> 14) | 0x80) & 0xFF);
- bytes.push(((octet >>> 7) | 0x80) & 0xFF);
- bytes.push(octet & 0x7F);
- }
- }
-
- var tmp = s.split('.');
- var bytes = [];
- bytes.push(parseInt(tmp[0], 10) * 40 + parseInt(tmp[1], 10));
- tmp.slice(2).forEach(function (b) {
- encodeOctet(bytes, parseInt(b, 10));
- });
-
- var self = this;
- this._ensure(2 + bytes.length);
- this.writeByte(tag);
- this.writeLength(bytes.length);
- bytes.forEach(function (b) {
- self.writeByte(b);
- });
-};
-
-
-Writer.prototype.writeLength = function (len) {
- if (typeof (len) !== 'number')
- throw new TypeError('argument must be a Number');
-
- this._ensure(4);
-
- if (len <= 0x7f) {
- this._buf[this._offset++] = len;
- } else if (len <= 0xff) {
- this._buf[this._offset++] = 0x81;
- this._buf[this._offset++] = len;
- } else if (len <= 0xffff) {
- this._buf[this._offset++] = 0x82;
- this._buf[this._offset++] = len >> 8;
- this._buf[this._offset++] = len;
- } else if (len <= 0xffffff) {
- this._buf[this._offset++] = 0x83;
- this._buf[this._offset++] = len >> 16;
- this._buf[this._offset++] = len >> 8;
- this._buf[this._offset++] = len;
- } else {
- throw newInvalidAsn1Error('Length too long (> 4 bytes)');
- }
-};
-
-Writer.prototype.startSequence = function (tag) {
- if (typeof (tag) !== 'number')
- tag = ASN1.Sequence | ASN1.Constructor;
-
- this.writeByte(tag);
- this._seq.push(this._offset);
- this._ensure(3);
- this._offset += 3;
-};
-
-
-Writer.prototype.endSequence = function () {
- var seq = this._seq.pop();
- var start = seq + 3;
- var len = this._offset - start;
-
- if (len <= 0x7f) {
- this._shift(start, len, -2);
- this._buf[seq] = len;
- } else if (len <= 0xff) {
- this._shift(start, len, -1);
- this._buf[seq] = 0x81;
- this._buf[seq + 1] = len;
- } else if (len <= 0xffff) {
- this._buf[seq] = 0x82;
- this._buf[seq + 1] = len >> 8;
- this._buf[seq + 2] = len;
- } else if (len <= 0xffffff) {
- this._shift(start, len, 1);
- this._buf[seq] = 0x83;
- this._buf[seq + 1] = len >> 16;
- this._buf[seq + 2] = len >> 8;
- this._buf[seq + 3] = len;
- } else {
- throw newInvalidAsn1Error('Sequence too long');
- }
-};
-
-
-Writer.prototype._shift = function (start, len, shift) {
- assert.ok(start !== undefined);
- assert.ok(len !== undefined);
- assert.ok(shift);
-
- this._buf.copy(this._buf, start + shift, start, start + len);
- this._offset += shift;
-};
-
-Writer.prototype._ensure = function (len) {
- assert.ok(len);
-
- if (this._size - this._offset < len) {
- var sz = this._size * this._options.growthFactor;
- if (sz - this._offset < len)
- sz += len;
-
- var buf = Buffer.alloc(sz);
-
- this._buf.copy(buf, 0, 0, this._offset);
- this._buf = buf;
- this._size = sz;
- }
-};
-
-
-
-// --- Exported API
-
-module.exports = Writer;
-
-},{"./errors":70,"./types":73,"assert":78,"safer-buffer":1594}],75:[function(require,module,exports){
-// Copyright 2011 Mark Cavage All rights reserved.
-
-// If you have no idea what ASN.1 or BER is, see this:
-// ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc
-
-var Ber = require('./ber/index');
-
-
-
-// --- Exported API
-
-module.exports = {
-
- Ber: Ber,
-
- BerReader: Ber.Reader,
-
- BerWriter: Ber.Writer
-
-};
-
-},{"./ber/index":71}],76:[function(require,module,exports){
+},{"./der":22,"inherits":317}],25:[function(require,module,exports){
"use strict";
const hasBigInt64 = typeof BigUint64Array !== "undefined";
@@ -9916,222 +2745,7 @@ function demangle(exports, baseModule) {
exports.demangle = demangle;
-},{}],77:[function(require,module,exports){
-(function (Buffer,process){
-// Copyright (c) 2012, Mark Cavage. All rights reserved.
-// Copyright 2015 Joyent, Inc.
-
-var assert = require('assert');
-var Stream = require('stream').Stream;
-var util = require('util');
-
-
-///--- Globals
-
-/* JSSTYLED */
-var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
-
-
-///--- Internal
-
-function _capitalize(str) {
- return (str.charAt(0).toUpperCase() + str.slice(1));
-}
-
-function _toss(name, expected, oper, arg, actual) {
- throw new assert.AssertionError({
- message: util.format('%s (%s) is required', name, expected),
- actual: (actual === undefined) ? typeof (arg) : actual(arg),
- expected: expected,
- operator: oper || '===',
- stackStartFunction: _toss.caller
- });
-}
-
-function _getClass(arg) {
- return (Object.prototype.toString.call(arg).slice(8, -1));
-}
-
-function noop() {
- // Why even bother with asserts?
-}
-
-
-///--- Exports
-
-var types = {
- bool: {
- check: function (arg) { return typeof (arg) === 'boolean'; }
- },
- func: {
- check: function (arg) { return typeof (arg) === 'function'; }
- },
- string: {
- check: function (arg) { return typeof (arg) === 'string'; }
- },
- object: {
- check: function (arg) {
- return typeof (arg) === 'object' && arg !== null;
- }
- },
- number: {
- check: function (arg) {
- return typeof (arg) === 'number' && !isNaN(arg);
- }
- },
- finite: {
- check: function (arg) {
- return typeof (arg) === 'number' && !isNaN(arg) && isFinite(arg);
- }
- },
- buffer: {
- check: function (arg) { return Buffer.isBuffer(arg); },
- operator: 'Buffer.isBuffer'
- },
- array: {
- check: function (arg) { return Array.isArray(arg); },
- operator: 'Array.isArray'
- },
- stream: {
- check: function (arg) { return arg instanceof Stream; },
- operator: 'instanceof',
- actual: _getClass
- },
- date: {
- check: function (arg) { return arg instanceof Date; },
- operator: 'instanceof',
- actual: _getClass
- },
- regexp: {
- check: function (arg) { return arg instanceof RegExp; },
- operator: 'instanceof',
- actual: _getClass
- },
- uuid: {
- check: function (arg) {
- return typeof (arg) === 'string' && UUID_REGEXP.test(arg);
- },
- operator: 'isUUID'
- }
-};
-
-function _setExports(ndebug) {
- var keys = Object.keys(types);
- var out;
-
- /* re-export standard assert */
- if (process.env.NODE_NDEBUG) {
- out = noop;
- } else {
- out = function (arg, msg) {
- if (!arg) {
- _toss(msg, 'true', arg);
- }
- };
- }
-
- /* standard checks */
- keys.forEach(function (k) {
- if (ndebug) {
- out[k] = noop;
- return;
- }
- var type = types[k];
- out[k] = function (arg, msg) {
- if (!type.check(arg)) {
- _toss(msg, k, type.operator, arg, type.actual);
- }
- };
- });
-
- /* optional checks */
- keys.forEach(function (k) {
- var name = 'optional' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- out[name] = function (arg, msg) {
- if (arg === undefined || arg === null) {
- return;
- }
- if (!type.check(arg)) {
- _toss(msg, k, type.operator, arg, type.actual);
- }
- };
- });
-
- /* arrayOf checks */
- keys.forEach(function (k) {
- var name = 'arrayOf' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- var expected = '[' + k + ']';
- out[name] = function (arg, msg) {
- if (!Array.isArray(arg)) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- var i;
- for (i = 0; i < arg.length; i++) {
- if (!type.check(arg[i])) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- }
- };
- });
-
- /* optionalArrayOf checks */
- keys.forEach(function (k) {
- var name = 'optionalArrayOf' + _capitalize(k);
- if (ndebug) {
- out[name] = noop;
- return;
- }
- var type = types[k];
- var expected = '[' + k + ']';
- out[name] = function (arg, msg) {
- if (arg === undefined || arg === null) {
- return;
- }
- if (!Array.isArray(arg)) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- var i;
- for (i = 0; i < arg.length; i++) {
- if (!type.check(arg[i])) {
- _toss(msg, expected, type.operator, arg, type.actual);
- }
- }
- };
- });
-
- /* re-export built-in assertions */
- Object.keys(assert).forEach(function (k) {
- if (k === 'AssertionError') {
- out[k] = assert[k];
- return;
- }
- if (ndebug) {
- out[k] = noop;
- return;
- }
- out[k] = assert[k];
- });
-
- /* export ourselves (for unit tests _only_) */
- out._setExports = _setExports;
-
- return out;
-}
-
-module.exports = _setExports(process.env.NODE_NDEBUG);
-
-}).call(this,{"isBuffer":require("../is-buffer/index.js")},require('_process'))
-},{"../is-buffer/index.js":766,"_process":1438,"assert":78,"stream":1715,"util":1776}],78:[function(require,module,exports){
+},{}],26:[function(require,module,exports){
(function (global){
'use strict';
@@ -10641,7 +3255,7 @@ var objectKeys = Object.keys || function (obj) {
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"object-assign":1388,"util/":81}],79:[function(require,module,exports){
+},{"object-assign":1226,"util/":29}],27:[function(require,module,exports){
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
@@ -10666,14 +3280,14 @@ if (typeof Object.create === 'function') {
}
}
-},{}],80:[function(require,module,exports){
+},{}],28:[function(require,module,exports){
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
-},{}],81:[function(require,module,exports){
+},{}],29:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
@@ -11263,7 +3877,7 @@ function hasOwnProperty(obj, prop) {
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./support/isBuffer":80,"_process":1438,"inherits":79}],82:[function(require,module,exports){
+},{"./support/isBuffer":28,"_process":1258,"inherits":27}],30:[function(require,module,exports){
'use strict'
const toArray = async (iterator) => {
@@ -11278,7 +3892,7 @@ const toArray = async (iterator) => {
module.exports = toArray
-},{}],83:[function(require,module,exports){
+},{}],31:[function(require,module,exports){
'use strict'
async function * batch (source, size) {
@@ -11303,7 +3917,7 @@ async function * batch (source, size) {
module.exports = batch
-},{}],84:[function(require,module,exports){
+},{}],32:[function(require,module,exports){
'use strict'
const first = async (iterator) => {
@@ -11314,7 +3928,7 @@ const first = async (iterator) => {
module.exports = first
-},{}],85:[function(require,module,exports){
+},{}],33:[function(require,module,exports){
'use strict'
const last = async (iterator) => {
@@ -11329,7 +3943,7 @@ const last = async (iterator) => {
module.exports = last
-},{}],86:[function(require,module,exports){
+},{}],34:[function(require,module,exports){
const getIterator = require('get-iterator')
const toIterable = require('pull-stream-to-async-iterator')
@@ -11403,7 +4017,7 @@ toPull.sink = sink => {
module.exports = toPull
-},{"get-iterator":388,"pull-stream-to-async-iterator":1493}],87:[function(require,module,exports){
+},{"get-iterator":281,"pull-stream-to-async-iterator":1309}],35:[function(require,module,exports){
(function (process){
"use strict";
@@ -11531,7 +4145,7 @@ asyncIteratorToStream.obj = (iterable, options) => asyncIteratorToStream(iterabl
}, options));
}).call(this,require('_process'))
-},{"_process":1438,"readable-stream":102}],88:[function(require,module,exports){
+},{"_process":1258,"readable-stream":50}],36:[function(require,module,exports){
'use strict';
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
@@ -11660,7 +4274,7 @@ createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
module.exports.codes = codes;
-},{}],89:[function(require,module,exports){
+},{}],37:[function(require,module,exports){
(function (process){
'use strict'
@@ -11681,7 +4295,7 @@ module.exports.emitExperimentalWarning = process.emitWarning
: noop;
}).call(this,require('_process'))
-},{"_process":1438}],90:[function(require,module,exports){
+},{"_process":1258}],38:[function(require,module,exports){
(function (process){
// Copyright Joyent, Inc. and other Node contributors.
//
@@ -11823,7 +4437,7 @@ Object.defineProperty(Duplex.prototype, 'destroyed', {
}
});
}).call(this,require('_process'))
-},{"./_stream_readable":92,"./_stream_writable":94,"_process":1438,"inherits":453}],91:[function(require,module,exports){
+},{"./_stream_readable":40,"./_stream_writable":42,"_process":1258,"inherits":317}],39:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -11863,7 +4477,7 @@ function PassThrough(options) {
PassThrough.prototype._transform = function (chunk, encoding, cb) {
cb(null, chunk);
};
-},{"./_stream_transform":93,"inherits":453}],92:[function(require,module,exports){
+},{"./_stream_transform":41,"inherits":317}],40:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
@@ -12953,7 +5567,7 @@ function indexOf(xs, x) {
return -1;
}
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../errors":88,"../experimentalWarning":89,"./_stream_duplex":90,"./internal/streams/async_iterator":95,"./internal/streams/buffer_list":96,"./internal/streams/destroy":97,"./internal/streams/state":100,"./internal/streams/stream":101,"_process":1438,"buffer":217,"events":370,"inherits":453,"string_decoder/":1741,"util":182}],93:[function(require,module,exports){
+},{"../errors":36,"../experimentalWarning":37,"./_stream_duplex":38,"./internal/streams/async_iterator":43,"./internal/streams/buffer_list":44,"./internal/streams/destroy":45,"./internal/streams/state":48,"./internal/streams/stream":49,"_process":1258,"buffer":181,"events":272,"inherits":317,"string_decoder/":52,"util":146}],41:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -13155,7 +5769,7 @@ function done(stream, er, data) {
if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
return stream.push(null);
}
-},{"../errors":88,"./_stream_duplex":90,"inherits":453}],94:[function(require,module,exports){
+},{"../errors":36,"./_stream_duplex":38,"inherits":317}],42:[function(require,module,exports){
(function (process,global){
// Copyright Joyent, Inc. and other Node contributors.
//
@@ -13841,7 +6455,7 @@ Writable.prototype._destroy = function (err, cb) {
cb(err);
};
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"../errors":88,"./_stream_duplex":90,"./internal/streams/destroy":97,"./internal/streams/state":100,"./internal/streams/stream":101,"_process":1438,"buffer":217,"inherits":453,"util-deprecate":1773}],95:[function(require,module,exports){
+},{"../errors":36,"./_stream_duplex":38,"./internal/streams/destroy":45,"./internal/streams/state":48,"./internal/streams/stream":49,"_process":1258,"buffer":181,"inherits":317,"util-deprecate":1510}],43:[function(require,module,exports){
(function (process){
'use strict';
@@ -14051,7 +6665,7 @@ var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterat
module.exports = createReadableStreamAsyncIterator;
}).call(this,require('_process'))
-},{"./end-of-stream":98,"_process":1438}],96:[function(require,module,exports){
+},{"./end-of-stream":46,"_process":1258}],44:[function(require,module,exports){
'use strict';
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; var ownKeys = Object.keys(source); if (typeof Object.getOwnPropertySymbols === 'function') { ownKeys = ownKeys.concat(Object.getOwnPropertySymbols(source).filter(function (sym) { return Object.getOwnPropertyDescriptor(source, sym).enumerable; })); } ownKeys.forEach(function (key) { _defineProperty(target, key, source[key]); }); } return target; }
@@ -14241,7 +6855,7 @@ function () {
return BufferList;
}();
-},{"buffer":217,"util":182}],97:[function(require,module,exports){
+},{"buffer":181,"util":146}],45:[function(require,module,exports){
(function (process){
'use strict'; // undocumented cb() API, needed for core, not for public API
@@ -14329,7 +6943,7 @@ module.exports = {
undestroy: undestroy
};
}).call(this,require('_process'))
-},{"_process":1438}],98:[function(require,module,exports){
+},{"_process":1258}],46:[function(require,module,exports){
// Ported from https://github.com/mafintosh/end-of-stream with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
@@ -14434,7 +7048,7 @@ function eos(stream, opts, callback) {
}
module.exports = eos;
-},{"../../../errors":88}],99:[function(require,module,exports){
+},{"../../../errors":36}],47:[function(require,module,exports){
// Ported from https://github.com/mafintosh/pump with
// permission from the author, Mathias Buus (@mafintosh).
'use strict';
@@ -14532,7 +7146,7 @@ function pipeline() {
}
module.exports = pipeline;
-},{"../../../errors":88,"./end-of-stream":98}],100:[function(require,module,exports){
+},{"../../../errors":36,"./end-of-stream":46}],48:[function(require,module,exports){
'use strict';
var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
@@ -14560,10 +7174,10 @@ function getHighWaterMark(state, options, duplexKey, isDuplex) {
module.exports = {
getHighWaterMark: getHighWaterMark
};
-},{"../../../errors":88}],101:[function(require,module,exports){
+},{"../../../errors":36}],49:[function(require,module,exports){
module.exports = require('events').EventEmitter;
-},{"events":370}],102:[function(require,module,exports){
+},{"events":272}],50:[function(require,module,exports){
exports = module.exports = require('./lib/_stream_readable.js');
exports.Stream = exports;
exports.Readable = exports;
@@ -14574,7 +7188,370 @@ exports.PassThrough = require('./lib/_stream_passthrough.js');
exports.finished = require('./lib/internal/streams/end-of-stream.js');
exports.pipeline = require('./lib/internal/streams/pipeline.js');
-},{"./lib/_stream_duplex.js":90,"./lib/_stream_passthrough.js":91,"./lib/_stream_readable.js":92,"./lib/_stream_transform.js":93,"./lib/_stream_writable.js":94,"./lib/internal/streams/end-of-stream.js":98,"./lib/internal/streams/pipeline.js":99}],103:[function(require,module,exports){
+},{"./lib/_stream_duplex.js":38,"./lib/_stream_passthrough.js":39,"./lib/_stream_readable.js":40,"./lib/_stream_transform.js":41,"./lib/_stream_writable.js":42,"./lib/internal/streams/end-of-stream.js":46,"./lib/internal/streams/pipeline.js":47}],51:[function(require,module,exports){
+/* eslint-disable node/no-deprecated-api */
+var buffer = require('buffer')
+var Buffer = buffer.Buffer
+
+// alternative to using Object.keys for old browsers
+function copyProps (src, dst) {
+ for (var key in src) {
+ dst[key] = src[key]
+ }
+}
+if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
+ module.exports = buffer
+} else {
+ // Copy properties from require('buffer')
+ copyProps(buffer, exports)
+ exports.Buffer = SafeBuffer
+}
+
+function SafeBuffer (arg, encodingOrOffset, length) {
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.prototype = Object.create(Buffer.prototype)
+
+// Copy static methods from Buffer
+copyProps(Buffer, SafeBuffer)
+
+SafeBuffer.from = function (arg, encodingOrOffset, length) {
+ if (typeof arg === 'number') {
+ throw new TypeError('Argument must not be a number')
+ }
+ return Buffer(arg, encodingOrOffset, length)
+}
+
+SafeBuffer.alloc = function (size, fill, encoding) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ var buf = Buffer(size)
+ if (fill !== undefined) {
+ if (typeof encoding === 'string') {
+ buf.fill(fill, encoding)
+ } else {
+ buf.fill(fill)
+ }
+ } else {
+ buf.fill(0)
+ }
+ return buf
+}
+
+SafeBuffer.allocUnsafe = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return Buffer(size)
+}
+
+SafeBuffer.allocUnsafeSlow = function (size) {
+ if (typeof size !== 'number') {
+ throw new TypeError('Argument must be a number')
+ }
+ return buffer.SlowBuffer(size)
+}
+
+},{"buffer":181}],52:[function(require,module,exports){
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+'use strict';
+
+/**/
+
+var Buffer = require('safe-buffer').Buffer;
+/**/
+
+var isEncoding = Buffer.isEncoding || function (encoding) {
+ encoding = '' + encoding;
+ switch (encoding && encoding.toLowerCase()) {
+ case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
+ return true;
+ default:
+ return false;
+ }
+};
+
+function _normalizeEncoding(enc) {
+ if (!enc) return 'utf8';
+ var retried;
+ while (true) {
+ switch (enc) {
+ case 'utf8':
+ case 'utf-8':
+ return 'utf8';
+ case 'ucs2':
+ case 'ucs-2':
+ case 'utf16le':
+ case 'utf-16le':
+ return 'utf16le';
+ case 'latin1':
+ case 'binary':
+ return 'latin1';
+ case 'base64':
+ case 'ascii':
+ case 'hex':
+ return enc;
+ default:
+ if (retried) return; // undefined
+ enc = ('' + enc).toLowerCase();
+ retried = true;
+ }
+ }
+};
+
+// Do not cache `Buffer.isEncoding` when checking encoding names as some
+// modules monkey-patch it to support additional encodings
+function normalizeEncoding(enc) {
+ var nenc = _normalizeEncoding(enc);
+ if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
+ return nenc || enc;
+}
+
+// StringDecoder provides an interface for efficiently splitting a series of
+// buffers into a series of JS strings without breaking apart multi-byte
+// characters.
+exports.StringDecoder = StringDecoder;
+function StringDecoder(encoding) {
+ this.encoding = normalizeEncoding(encoding);
+ var nb;
+ switch (this.encoding) {
+ case 'utf16le':
+ this.text = utf16Text;
+ this.end = utf16End;
+ nb = 4;
+ break;
+ case 'utf8':
+ this.fillLast = utf8FillLast;
+ nb = 4;
+ break;
+ case 'base64':
+ this.text = base64Text;
+ this.end = base64End;
+ nb = 3;
+ break;
+ default:
+ this.write = simpleWrite;
+ this.end = simpleEnd;
+ return;
+ }
+ this.lastNeed = 0;
+ this.lastTotal = 0;
+ this.lastChar = Buffer.allocUnsafe(nb);
+}
+
+StringDecoder.prototype.write = function (buf) {
+ if (buf.length === 0) return '';
+ var r;
+ var i;
+ if (this.lastNeed) {
+ r = this.fillLast(buf);
+ if (r === undefined) return '';
+ i = this.lastNeed;
+ this.lastNeed = 0;
+ } else {
+ i = 0;
+ }
+ if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
+ return r || '';
+};
+
+StringDecoder.prototype.end = utf8End;
+
+// Returns only complete characters in a Buffer
+StringDecoder.prototype.text = utf8Text;
+
+// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
+StringDecoder.prototype.fillLast = function (buf) {
+ if (this.lastNeed <= buf.length) {
+ buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
+ return this.lastChar.toString(this.encoding, 0, this.lastTotal);
+ }
+ buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
+ this.lastNeed -= buf.length;
+};
+
+// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
+// continuation byte. If an invalid byte is detected, -2 is returned.
+function utf8CheckByte(byte) {
+ if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
+ return byte >> 6 === 0x02 ? -1 : -2;
+}
+
+// Checks at most 3 bytes at the end of a Buffer in order to detect an
+// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
+// needed to complete the UTF-8 character (if applicable) are returned.
+function utf8CheckIncomplete(self, buf, i) {
+ var j = buf.length - 1;
+ if (j < i) return 0;
+ var nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) self.lastNeed = nb - 1;
+ return nb;
+ }
+ if (--j < i || nb === -2) return 0;
+ nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) self.lastNeed = nb - 2;
+ return nb;
+ }
+ if (--j < i || nb === -2) return 0;
+ nb = utf8CheckByte(buf[j]);
+ if (nb >= 0) {
+ if (nb > 0) {
+ if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
+ }
+ return nb;
+ }
+ return 0;
+}
+
+// Validates as many continuation bytes for a multi-byte UTF-8 character as
+// needed or are available. If we see a non-continuation byte where we expect
+// one, we "replace" the validated continuation bytes we've seen so far with
+// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
+// behavior. The continuation byte check is included three times in the case
+// where all of the continuation bytes for a character exist in the same buffer.
+// It is also done this way as a slight performance increase instead of using a
+// loop.
+function utf8CheckExtraBytes(self, buf, p) {
+ if ((buf[0] & 0xC0) !== 0x80) {
+ self.lastNeed = 0;
+ return '\ufffd';
+ }
+ if (self.lastNeed > 1 && buf.length > 1) {
+ if ((buf[1] & 0xC0) !== 0x80) {
+ self.lastNeed = 1;
+ return '\ufffd';
+ }
+ if (self.lastNeed > 2 && buf.length > 2) {
+ if ((buf[2] & 0xC0) !== 0x80) {
+ self.lastNeed = 2;
+ return '\ufffd';
+ }
+ }
+ }
+}
+
+// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
+function utf8FillLast(buf) {
+ var p = this.lastTotal - this.lastNeed;
+ var r = utf8CheckExtraBytes(this, buf, p);
+ if (r !== undefined) return r;
+ if (this.lastNeed <= buf.length) {
+ buf.copy(this.lastChar, p, 0, this.lastNeed);
+ return this.lastChar.toString(this.encoding, 0, this.lastTotal);
+ }
+ buf.copy(this.lastChar, p, 0, buf.length);
+ this.lastNeed -= buf.length;
+}
+
+// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
+// partial character, the character's bytes are buffered until the required
+// number of bytes are available.
+function utf8Text(buf, i) {
+ var total = utf8CheckIncomplete(this, buf, i);
+ if (!this.lastNeed) return buf.toString('utf8', i);
+ this.lastTotal = total;
+ var end = buf.length - (total - this.lastNeed);
+ buf.copy(this.lastChar, 0, end);
+ return buf.toString('utf8', i, end);
+}
+
+// For UTF-8, a replacement character is added when ending on a partial
+// character.
+function utf8End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) return r + '\ufffd';
+ return r;
+}
+
+// UTF-16LE typically needs two bytes per character, but even if we have an even
+// number of bytes available, we need to check if we end on a leading/high
+// surrogate. In that case, we need to wait for the next two bytes in order to
+// decode the last character properly.
+function utf16Text(buf, i) {
+ if ((buf.length - i) % 2 === 0) {
+ var r = buf.toString('utf16le', i);
+ if (r) {
+ var c = r.charCodeAt(r.length - 1);
+ if (c >= 0xD800 && c <= 0xDBFF) {
+ this.lastNeed = 2;
+ this.lastTotal = 4;
+ this.lastChar[0] = buf[buf.length - 2];
+ this.lastChar[1] = buf[buf.length - 1];
+ return r.slice(0, -1);
+ }
+ }
+ return r;
+ }
+ this.lastNeed = 1;
+ this.lastTotal = 2;
+ this.lastChar[0] = buf[buf.length - 1];
+ return buf.toString('utf16le', i, buf.length - 1);
+}
+
+// For UTF-16LE we do not explicitly append special replacement characters if we
+// end on a partial character, we simply let v8 handle that.
+function utf16End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) {
+ var end = this.lastTotal - this.lastNeed;
+ return r + this.lastChar.toString('utf16le', 0, end);
+ }
+ return r;
+}
+
+function base64Text(buf, i) {
+ var n = (buf.length - i) % 3;
+ if (n === 0) return buf.toString('base64', i);
+ this.lastNeed = 3 - n;
+ this.lastTotal = 3;
+ if (n === 1) {
+ this.lastChar[0] = buf[buf.length - 1];
+ } else {
+ this.lastChar[0] = buf[buf.length - 2];
+ this.lastChar[1] = buf[buf.length - 1];
+ }
+ return buf.toString('base64', i, buf.length - n);
+}
+
+function base64End(buf) {
+ var r = buf && buf.length ? this.write(buf) : '';
+ if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
+ return r;
+}
+
+// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
+function simpleWrite(buf) {
+ return buf.toString(this.encoding);
+}
+
+function simpleEnd(buf) {
+ return buf && buf.length ? this.write(buf) : '';
+}
+},{"safe-buffer":51}],53:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -14685,7 +7662,7 @@ function rethrow(error) {
throw error;
}
module.exports = exports['default'];
-},{"./internal/initialParams":124,"./internal/setImmediate":133,"lodash/isObject":1285}],104:[function(require,module,exports){
+},{"./internal/initialParams":74,"./internal/setImmediate":83,"lodash/isObject":1114}],54:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -14747,7 +7724,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default));
module.exports = exports['default'];
-},{"./internal/createTester":116,"./internal/doParallel":118,"./internal/findGetResult":122,"lodash/identity":1278}],105:[function(require,module,exports){
+},{"./internal/createTester":66,"./internal/doParallel":68,"./internal/findGetResult":72,"lodash/identity":1107}],55:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -14796,7 +7773,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(_identity2.default, _findGetResult2.default));
module.exports = exports['default'];
-},{"./internal/createTester":116,"./internal/doParallelLimit":119,"./internal/findGetResult":122,"lodash/identity":1278}],106:[function(require,module,exports){
+},{"./internal/createTester":66,"./internal/doParallelLimit":69,"./internal/findGetResult":72,"lodash/identity":1107}],56:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -14879,7 +7856,7 @@ function eachLimit(coll, iteratee, callback) {
(0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
}
module.exports = exports['default'];
-},{"./eachOf":108,"./internal/withoutIndex":135,"./internal/wrapAsync":136}],107:[function(require,module,exports){
+},{"./eachOf":58,"./internal/withoutIndex":85,"./internal/wrapAsync":86}],57:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -14925,7 +7902,7 @@ function eachLimit(coll, limit, iteratee, callback) {
(0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback);
}
module.exports = exports['default'];
-},{"./internal/eachOfLimit":120,"./internal/withoutIndex":135,"./internal/wrapAsync":136}],108:[function(require,module,exports){
+},{"./internal/eachOfLimit":70,"./internal/withoutIndex":85,"./internal/wrapAsync":86}],58:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15037,7 +8014,7 @@ var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity);
* });
*/
module.exports = exports['default'];
-},{"./eachOfLimit":109,"./internal/breakLoop":115,"./internal/doLimit":117,"./internal/once":128,"./internal/onlyOnce":129,"./internal/wrapAsync":136,"lodash/isArrayLike":1281,"lodash/noop":1291}],109:[function(require,module,exports){
+},{"./eachOfLimit":59,"./internal/breakLoop":65,"./internal/doLimit":67,"./internal/once":78,"./internal/onlyOnce":79,"./internal/wrapAsync":86,"lodash/isArrayLike":1110,"lodash/noop":1120}],59:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15079,7 +8056,7 @@ function eachOfLimit(coll, limit, iteratee, callback) {
(0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback);
}
module.exports = exports['default'];
-},{"./internal/eachOfLimit":120,"./internal/wrapAsync":136}],110:[function(require,module,exports){
+},{"./internal/eachOfLimit":70,"./internal/wrapAsync":86}],60:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15115,7 +8092,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1);
module.exports = exports['default'];
-},{"./eachOfLimit":109,"./internal/doLimit":117}],111:[function(require,module,exports){
+},{"./eachOfLimit":59,"./internal/doLimit":67}],61:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15153,7 +8130,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1);
module.exports = exports['default'];
-},{"./eachLimit":107,"./internal/doLimit":117}],112:[function(require,module,exports){
+},{"./eachLimit":57,"./internal/doLimit":67}],62:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15204,7 +8181,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default));
module.exports = exports['default'];
-},{"./internal/createTester":116,"./internal/doParallel":118,"./internal/notId":127}],113:[function(require,module,exports){
+},{"./internal/createTester":66,"./internal/doParallel":68,"./internal/notId":77}],63:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15250,7 +8227,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)(_filter2.default);
module.exports = exports['default'];
-},{"./internal/doParallel":118,"./internal/filter":121}],114:[function(require,module,exports){
+},{"./internal/doParallel":68,"./internal/filter":71}],64:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15339,7 +8316,7 @@ DLL.prototype.remove = function (testFn) {
return this;
};
module.exports = exports["default"];
-},{}],115:[function(require,module,exports){
+},{}],65:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15349,7 +8326,7 @@ Object.defineProperty(exports, "__esModule", {
// See #1064, #1293
exports.default = {};
module.exports = exports["default"];
-},{}],116:[function(require,module,exports){
+},{}],66:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15394,7 +8371,7 @@ function _createTester(check, getResult) {
};
}
module.exports = exports['default'];
-},{"./breakLoop":115,"lodash/noop":1291}],117:[function(require,module,exports){
+},{"./breakLoop":65,"lodash/noop":1120}],67:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15407,7 +8384,7 @@ function doLimit(fn, limit) {
};
}
module.exports = exports["default"];
-},{}],118:[function(require,module,exports){
+},{}],68:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15431,7 +8408,7 @@ function doParallel(fn) {
};
}
module.exports = exports['default'];
-},{"../eachOf":108,"./wrapAsync":136}],119:[function(require,module,exports){
+},{"../eachOf":58,"./wrapAsync":86}],69:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15455,7 +8432,7 @@ function doParallelLimit(fn) {
};
}
module.exports = exports['default'];
-},{"./eachOfLimit":120,"./wrapAsync":136}],120:[function(require,module,exports){
+},{"./eachOfLimit":70,"./wrapAsync":86}],70:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15530,7 +8507,7 @@ function _eachOfLimit(limit) {
};
}
module.exports = exports['default'];
-},{"./breakLoop":115,"./iterator":125,"./once":128,"./onlyOnce":129,"lodash/noop":1291}],121:[function(require,module,exports){
+},{"./breakLoop":65,"./iterator":75,"./once":78,"./onlyOnce":79,"lodash/noop":1120}],71:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15606,7 +8583,7 @@ function _filter(eachfn, coll, iteratee, callback) {
filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default);
}
module.exports = exports['default'];
-},{"./wrapAsync":136,"lodash/_arrayMap":1222,"lodash/_baseProperty":1233,"lodash/isArrayLike":1281,"lodash/noop":1291}],122:[function(require,module,exports){
+},{"./wrapAsync":86,"lodash/_arrayMap":1051,"lodash/_baseProperty":1062,"lodash/isArrayLike":1110,"lodash/noop":1120}],72:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15617,7 +8594,7 @@ function _findGetResult(v, x) {
return x;
}
module.exports = exports["default"];
-},{}],123:[function(require,module,exports){
+},{}],73:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15631,7 +8608,7 @@ exports.default = function (coll) {
var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator;
module.exports = exports['default'];
-},{}],124:[function(require,module,exports){
+},{}],74:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15653,7 +8630,7 @@ var _slice2 = _interopRequireDefault(_slice);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
module.exports = exports['default'];
-},{"./slice":134}],125:[function(require,module,exports){
+},{"./slice":84}],75:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15712,7 +8689,7 @@ function iterator(coll) {
return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll);
}
module.exports = exports['default'];
-},{"./getIterator":123,"lodash/isArrayLike":1281,"lodash/keys":1289}],126:[function(require,module,exports){
+},{"./getIterator":73,"lodash/isArrayLike":1110,"lodash/keys":1118}],76:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15748,7 +8725,7 @@ function _asyncMap(eachfn, arr, iteratee, callback) {
});
}
module.exports = exports['default'];
-},{"./wrapAsync":136,"lodash/noop":1291}],127:[function(require,module,exports){
+},{"./wrapAsync":86,"lodash/noop":1120}],77:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15759,7 +8736,7 @@ function notId(v) {
return !v;
}
module.exports = exports["default"];
-},{}],128:[function(require,module,exports){
+},{}],78:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15775,7 +8752,7 @@ function once(fn) {
};
}
module.exports = exports["default"];
-},{}],129:[function(require,module,exports){
+},{}],79:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -15791,7 +8768,7 @@ function onlyOnce(fn) {
};
}
module.exports = exports["default"];
-},{}],130:[function(require,module,exports){
+},{}],80:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -15834,7 +8811,7 @@ function _parallel(eachfn, tasks, callback) {
});
}
module.exports = exports['default'];
-},{"./slice":134,"./wrapAsync":136,"lodash/isArrayLike":1281,"lodash/noop":1291}],131:[function(require,module,exports){
+},{"./slice":84,"./wrapAsync":86,"lodash/isArrayLike":1110,"lodash/noop":1120}],81:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16039,7 +9016,7 @@ function queue(worker, concurrency, payload) {
return q;
}
module.exports = exports['default'];
-},{"./DoublyLinkedList":114,"./onlyOnce":129,"./setImmediate":133,"./wrapAsync":136,"lodash/_baseIndexOf":1227,"lodash/isArray":1280,"lodash/noop":1291}],132:[function(require,module,exports){
+},{"./DoublyLinkedList":64,"./onlyOnce":79,"./setImmediate":83,"./wrapAsync":86,"lodash/_baseIndexOf":1056,"lodash/isArray":1109,"lodash/noop":1120}],82:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16061,7 +9038,7 @@ function reject(eachfn, arr, iteratee, callback) {
}, callback);
}
module.exports = exports['default'];
-},{"./filter":121}],133:[function(require,module,exports){
+},{"./filter":71}],83:[function(require,module,exports){
(function (process,setImmediate){
'use strict';
@@ -16106,7 +9083,7 @@ if (hasSetImmediate) {
exports.default = wrap(_defer);
}).call(this,require('_process'),require("timers").setImmediate)
-},{"./slice":134,"_process":1438,"timers":1749}],134:[function(require,module,exports){
+},{"./slice":84,"_process":1258,"timers":1500}],84:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -16123,7 +9100,7 @@ function slice(arrayLike, start) {
return newArr;
}
module.exports = exports["default"];
-},{}],135:[function(require,module,exports){
+},{}],85:[function(require,module,exports){
"use strict";
Object.defineProperty(exports, "__esModule", {
@@ -16136,7 +9113,7 @@ function _withoutIndex(iteratee) {
};
}
module.exports = exports["default"];
-},{}],136:[function(require,module,exports){
+},{}],86:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16162,7 +9139,7 @@ function wrapAsync(asyncFn) {
exports.default = wrapAsync;
exports.isAsync = isAsync;
-},{"../asyncify":103}],137:[function(require,module,exports){
+},{"../asyncify":53}],87:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16217,7 +9194,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)(_map2.default);
module.exports = exports['default'];
-},{"./internal/doParallel":118,"./internal/map":126}],138:[function(require,module,exports){
+},{"./internal/doParallel":68,"./internal/map":76}],88:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16255,7 +9232,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallelLimit2.default)(_map2.default);
module.exports = exports['default'];
-},{"./internal/doParallelLimit":119,"./internal/map":126}],139:[function(require,module,exports){
+},{"./internal/doParallelLimit":69,"./internal/map":76}],89:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16292,7 +9269,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doLimit2.default)(_mapLimit2.default, 1);
module.exports = exports['default'];
-},{"./internal/doLimit":117,"./mapLimit":138}],140:[function(require,module,exports){
+},{"./internal/doLimit":67,"./mapLimit":88}],90:[function(require,module,exports){
(function (process,setImmediate){
'use strict';
@@ -16346,7 +9323,7 @@ if (_setImmediate.hasNextTick) {
exports.default = (0, _setImmediate.wrap)(_defer);
module.exports = exports['default'];
}).call(this,require('_process'),require("timers").setImmediate)
-},{"./internal/setImmediate":133,"_process":1438,"timers":1749}],141:[function(require,module,exports){
+},{"./internal/setImmediate":83,"_process":1258,"timers":1500}],91:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16437,7 +9414,7 @@ function parallelLimit(tasks, callback) {
(0, _parallel2.default)(_eachOf2.default, tasks, callback);
}
module.exports = exports['default'];
-},{"./eachOf":108,"./internal/parallel":130}],142:[function(require,module,exports){
+},{"./eachOf":58,"./internal/parallel":80}],92:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16568,7 +9545,7 @@ module.exports = exports['default'];
* console.log('finished processing bar');
* });
*/
-},{"./internal/queue":131,"./internal/wrapAsync":136}],143:[function(require,module,exports){
+},{"./internal/queue":81,"./internal/wrapAsync":86}],93:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16614,7 +9591,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)(_reject2.default);
module.exports = exports['default'];
-},{"./internal/doParallel":118,"./internal/reject":132}],144:[function(require,module,exports){
+},{"./internal/doParallel":68,"./internal/reject":82}],94:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16771,7 +9748,7 @@ function retry(opts, task, callback) {
retryAttempt();
}
module.exports = exports['default'];
-},{"./internal/wrapAsync":136,"lodash/constant":1275,"lodash/noop":1291}],145:[function(require,module,exports){
+},{"./internal/wrapAsync":86,"lodash/constant":1104,"lodash/noop":1120}],95:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16857,7 +9834,7 @@ function series(tasks, callback) {
(0, _parallel2.default)(_eachOfSeries2.default, tasks, callback);
}
module.exports = exports['default'];
-},{"./eachOfSeries":110,"./internal/parallel":130}],146:[function(require,module,exports){
+},{"./eachOfSeries":60,"./internal/parallel":80}],96:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16903,7 +9880,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = _setImmediate2.default;
module.exports = exports['default'];
-},{"./internal/setImmediate":133}],147:[function(require,module,exports){
+},{"./internal/setImmediate":83}],97:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -16956,7 +9933,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default));
module.exports = exports['default'];
-},{"./internal/createTester":116,"./internal/doParallel":118,"lodash/identity":1278}],148:[function(require,module,exports){
+},{"./internal/createTester":66,"./internal/doParallel":68,"lodash/identity":1107}],98:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17000,7 +9977,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doParallelLimit2.default)((0, _createTester2.default)(Boolean, _identity2.default));
module.exports = exports['default'];
-},{"./internal/createTester":116,"./internal/doParallelLimit":119,"lodash/identity":1278}],149:[function(require,module,exports){
+},{"./internal/createTester":66,"./internal/doParallelLimit":69,"lodash/identity":1107}],99:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17039,7 +10016,7 @@ function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { de
*/
exports.default = (0, _doLimit2.default)(_someLimit2.default, 1);
module.exports = exports['default'];
-},{"./internal/doLimit":117,"./someLimit":148}],150:[function(require,module,exports){
+},{"./internal/doLimit":67,"./someLimit":98}],100:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17129,7 +10106,7 @@ function timeout(asyncFn, milliseconds, info) {
});
}
module.exports = exports['default'];
-},{"./internal/initialParams":124,"./internal/wrapAsync":136}],151:[function(require,module,exports){
+},{"./internal/initialParams":74,"./internal/wrapAsync":86}],101:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17211,7 +10188,7 @@ function tryEach(tasks, callback) {
});
}
module.exports = exports['default'];
-},{"./eachSeries":111,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/noop":1291}],152:[function(require,module,exports){
+},{"./eachSeries":61,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/noop":1120}],102:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17325,7 +10302,7 @@ module.exports = exports['default'];
* callback(null, 'done');
* }
*/
-},{"./internal/once":128,"./internal/onlyOnce":129,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/isArray":1280,"lodash/noop":1291}],153:[function(require,module,exports){
+},{"./internal/once":78,"./internal/onlyOnce":79,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/isArray":1109,"lodash/noop":1120}],103:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
@@ -17398,655 +10375,7 @@ function whilst(test, iteratee, callback) {
_iteratee(next);
}
module.exports = exports['default'];
-},{"./internal/onlyOnce":129,"./internal/slice":134,"./internal/wrapAsync":136,"lodash/noop":1291}],154:[function(require,module,exports){
-
-/*!
- * Copyright 2010 LearnBoost
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-/**
- * Module dependencies.
- */
-
-var crypto = require('crypto')
- , parse = require('url').parse
- ;
-
-/**
- * Valid keys.
- */
-
-var keys =
- [ 'acl'
- , 'location'
- , 'logging'
- , 'notification'
- , 'partNumber'
- , 'policy'
- , 'requestPayment'
- , 'torrent'
- , 'uploadId'
- , 'uploads'
- , 'versionId'
- , 'versioning'
- , 'versions'
- , 'website'
- ]
-
-/**
- * Return an "Authorization" header value with the given `options`
- * in the form of "AWS :"
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function authorization (options) {
- return 'AWS ' + options.key + ':' + sign(options)
-}
-
-module.exports = authorization
-module.exports.authorization = authorization
-
-/**
- * Simple HMAC-SHA1 Wrapper
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function hmacSha1 (options) {
- return crypto.createHmac('sha1', options.secret).update(options.message).digest('base64')
-}
-
-module.exports.hmacSha1 = hmacSha1
-
-/**
- * Create a base64 sha1 HMAC for `options`.
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function sign (options) {
- options.message = stringToSign(options)
- return hmacSha1(options)
-}
-module.exports.sign = sign
-
-/**
- * Create a base64 sha1 HMAC for `options`.
- *
- * Specifically to be used with S3 presigned URLs
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function signQuery (options) {
- options.message = queryStringToSign(options)
- return hmacSha1(options)
-}
-module.exports.signQuery= signQuery
-
-/**
- * Return a string for sign() with the given `options`.
- *
- * Spec:
- *
- * \n
- * \n
- * \n
- * \n
- * [headers\n]
- *
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function stringToSign (options) {
- var headers = options.amazonHeaders || ''
- if (headers) headers += '\n'
- var r =
- [ options.verb
- , options.md5
- , options.contentType
- , options.date ? options.date.toUTCString() : ''
- , headers + options.resource
- ]
- return r.join('\n')
-}
-module.exports.stringToSign = stringToSign
-
-/**
- * Return a string for sign() with the given `options`, but is meant exclusively
- * for S3 presigned URLs
- *
- * Spec:
- *
- * \n
- *
- *
- * @param {Object} options
- * @return {String}
- * @api private
- */
-
-function queryStringToSign (options){
- return 'GET\n\n\n' + options.date + '\n' + options.resource
-}
-module.exports.queryStringToSign = queryStringToSign
-
-/**
- * Perform the following:
- *
- * - ignore non-amazon headers
- * - lowercase fields
- * - sort lexicographically
- * - trim whitespace between ":"
- * - join with newline
- *
- * @param {Object} headers
- * @return {String}
- * @api private
- */
-
-function canonicalizeHeaders (headers) {
- var buf = []
- , fields = Object.keys(headers)
- ;
- for (var i = 0, len = fields.length; i < len; ++i) {
- var field = fields[i]
- , val = headers[field]
- , field = field.toLowerCase()
- ;
- if (0 !== field.indexOf('x-amz')) continue
- buf.push(field + ':' + val)
- }
- return buf.sort().join('\n')
-}
-module.exports.canonicalizeHeaders = canonicalizeHeaders
-
-/**
- * Perform the following:
- *
- * - ignore non sub-resources
- * - sort lexicographically
- *
- * @param {String} resource
- * @return {String}
- * @api private
- */
-
-function canonicalizeResource (resource) {
- var url = parse(resource, true)
- , path = url.pathname
- , buf = []
- ;
-
- Object.keys(url.query).forEach(function(key){
- if (!~keys.indexOf(key)) return
- var val = '' == url.query[key] ? '' : '=' + encodeURIComponent(url.query[key])
- buf.push(key + val)
- })
-
- return path + (buf.length ? '?' + buf.sort().join('&') : '')
-}
-module.exports.canonicalizeResource = canonicalizeResource
-
-},{"crypto":236,"url":1769}],155:[function(require,module,exports){
-(function (process,Buffer){
-var aws4 = exports,
- url = require('url'),
- querystring = require('querystring'),
- crypto = require('crypto'),
- lru = require('./lru'),
- credentialsCache = lru(1000)
-
-// http://docs.amazonwebservices.com/general/latest/gr/signature-version-4.html
-
-function hmac(key, string, encoding) {
- return crypto.createHmac('sha256', key).update(string, 'utf8').digest(encoding)
-}
-
-function hash(string, encoding) {
- return crypto.createHash('sha256').update(string, 'utf8').digest(encoding)
-}
-
-// This function assumes the string has already been percent encoded
-function encodeRfc3986(urlEncodedString) {
- return urlEncodedString.replace(/[!'()*]/g, function(c) {
- return '%' + c.charCodeAt(0).toString(16).toUpperCase()
- })
-}
-
-// request: { path | body, [host], [method], [headers], [service], [region] }
-// credentials: { accessKeyId, secretAccessKey, [sessionToken] }
-function RequestSigner(request, credentials) {
-
- if (typeof request === 'string') request = url.parse(request)
-
- var headers = request.headers = (request.headers || {}),
- hostParts = this.matchHost(request.hostname || request.host || headers.Host || headers.host)
-
- this.request = request
- this.credentials = credentials || this.defaultCredentials()
-
- this.service = request.service || hostParts[0] || ''
- this.region = request.region || hostParts[1] || 'us-east-1'
-
- // SES uses a different domain from the service name
- if (this.service === 'email') this.service = 'ses'
-
- if (!request.method && request.body)
- request.method = 'POST'
-
- if (!headers.Host && !headers.host) {
- headers.Host = request.hostname || request.host || this.createHost()
-
- // If a port is specified explicitly, use it as is
- if (request.port)
- headers.Host += ':' + request.port
- }
- if (!request.hostname && !request.host)
- request.hostname = headers.Host || headers.host
-
- this.isCodeCommitGit = this.service === 'codecommit' && request.method === 'GIT'
-}
-
-RequestSigner.prototype.matchHost = function(host) {
- var match = (host || '').match(/([^\.]+)\.(?:([^\.]*)\.)?amazonaws\.com(\.cn)?$/)
- var hostParts = (match || []).slice(1, 3)
-
- // ES's hostParts are sometimes the other way round, if the value that is expected
- // to be region equals ‘es’ switch them back
- // e.g. search-cluster-name-aaaa00aaaa0aaa0aaaaaaa0aaa.us-east-1.es.amazonaws.com
- if (hostParts[1] === 'es')
- hostParts = hostParts.reverse()
-
- return hostParts
-}
-
-// http://docs.aws.amazon.com/general/latest/gr/rande.html
-RequestSigner.prototype.isSingleRegion = function() {
- // Special case for S3 and SimpleDB in us-east-1
- if (['s3', 'sdb'].indexOf(this.service) >= 0 && this.region === 'us-east-1') return true
-
- return ['cloudfront', 'ls', 'route53', 'iam', 'importexport', 'sts']
- .indexOf(this.service) >= 0
-}
-
-RequestSigner.prototype.createHost = function() {
- var region = this.isSingleRegion() ? '' :
- (this.service === 's3' && this.region !== 'us-east-1' ? '-' : '.') + this.region,
- service = this.service === 'ses' ? 'email' : this.service
- return service + region + '.amazonaws.com'
-}
-
-RequestSigner.prototype.prepareRequest = function() {
- this.parsePath()
-
- var request = this.request, headers = request.headers, query
-
- if (request.signQuery) {
-
- this.parsedPath.query = query = this.parsedPath.query || {}
-
- if (this.credentials.sessionToken)
- query['X-Amz-Security-Token'] = this.credentials.sessionToken
-
- if (this.service === 's3' && !query['X-Amz-Expires'])
- query['X-Amz-Expires'] = 86400
-
- if (query['X-Amz-Date'])
- this.datetime = query['X-Amz-Date']
- else
- query['X-Amz-Date'] = this.getDateTime()
-
- query['X-Amz-Algorithm'] = 'AWS4-HMAC-SHA256'
- query['X-Amz-Credential'] = this.credentials.accessKeyId + '/' + this.credentialString()
- query['X-Amz-SignedHeaders'] = this.signedHeaders()
-
- } else {
-
- if (!request.doNotModifyHeaders && !this.isCodeCommitGit) {
- if (request.body && !headers['Content-Type'] && !headers['content-type'])
- headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8'
-
- if (request.body && !headers['Content-Length'] && !headers['content-length'])
- headers['Content-Length'] = Buffer.byteLength(request.body)
-
- if (this.credentials.sessionToken && !headers['X-Amz-Security-Token'] && !headers['x-amz-security-token'])
- headers['X-Amz-Security-Token'] = this.credentials.sessionToken
-
- if (this.service === 's3' && !headers['X-Amz-Content-Sha256'] && !headers['x-amz-content-sha256'])
- headers['X-Amz-Content-Sha256'] = hash(this.request.body || '', 'hex')
-
- if (headers['X-Amz-Date'] || headers['x-amz-date'])
- this.datetime = headers['X-Amz-Date'] || headers['x-amz-date']
- else
- headers['X-Amz-Date'] = this.getDateTime()
- }
-
- delete headers.Authorization
- delete headers.authorization
- }
-}
-
-RequestSigner.prototype.sign = function() {
- if (!this.parsedPath) this.prepareRequest()
-
- if (this.request.signQuery) {
- this.parsedPath.query['X-Amz-Signature'] = this.signature()
- } else {
- this.request.headers.Authorization = this.authHeader()
- }
-
- this.request.path = this.formatPath()
-
- return this.request
-}
-
-RequestSigner.prototype.getDateTime = function() {
- if (!this.datetime) {
- var headers = this.request.headers,
- date = new Date(headers.Date || headers.date || new Date)
-
- this.datetime = date.toISOString().replace(/[:\-]|\.\d{3}/g, '')
-
- // Remove the trailing 'Z' on the timestamp string for CodeCommit git access
- if (this.isCodeCommitGit) this.datetime = this.datetime.slice(0, -1)
- }
- return this.datetime
-}
-
-RequestSigner.prototype.getDate = function() {
- return this.getDateTime().substr(0, 8)
-}
-
-RequestSigner.prototype.authHeader = function() {
- return [
- 'AWS4-HMAC-SHA256 Credential=' + this.credentials.accessKeyId + '/' + this.credentialString(),
- 'SignedHeaders=' + this.signedHeaders(),
- 'Signature=' + this.signature(),
- ].join(', ')
-}
-
-RequestSigner.prototype.signature = function() {
- var date = this.getDate(),
- cacheKey = [this.credentials.secretAccessKey, date, this.region, this.service].join(),
- kDate, kRegion, kService, kCredentials = credentialsCache.get(cacheKey)
- if (!kCredentials) {
- kDate = hmac('AWS4' + this.credentials.secretAccessKey, date)
- kRegion = hmac(kDate, this.region)
- kService = hmac(kRegion, this.service)
- kCredentials = hmac(kService, 'aws4_request')
- credentialsCache.set(cacheKey, kCredentials)
- }
- return hmac(kCredentials, this.stringToSign(), 'hex')
-}
-
-RequestSigner.prototype.stringToSign = function() {
- return [
- 'AWS4-HMAC-SHA256',
- this.getDateTime(),
- this.credentialString(),
- hash(this.canonicalString(), 'hex'),
- ].join('\n')
-}
-
-RequestSigner.prototype.canonicalString = function() {
- if (!this.parsedPath) this.prepareRequest()
-
- var pathStr = this.parsedPath.path,
- query = this.parsedPath.query,
- headers = this.request.headers,
- queryStr = '',
- normalizePath = this.service !== 's3',
- decodePath = this.service === 's3' || this.request.doNotEncodePath,
- decodeSlashesInPath = this.service === 's3',
- firstValOnly = this.service === 's3',
- bodyHash
-
- if (this.service === 's3' && this.request.signQuery) {
- bodyHash = 'UNSIGNED-PAYLOAD'
- } else if (this.isCodeCommitGit) {
- bodyHash = ''
- } else {
- bodyHash = headers['X-Amz-Content-Sha256'] || headers['x-amz-content-sha256'] ||
- hash(this.request.body || '', 'hex')
- }
-
- if (query) {
- queryStr = encodeRfc3986(querystring.stringify(Object.keys(query).sort().reduce(function(obj, key) {
- if (!key) return obj
- obj[key] = !Array.isArray(query[key]) ? query[key] :
- (firstValOnly ? query[key][0] : query[key].slice().sort())
- return obj
- }, {})))
- }
- if (pathStr !== '/') {
- if (normalizePath) pathStr = pathStr.replace(/\/{2,}/g, '/')
- pathStr = pathStr.split('/').reduce(function(path, piece) {
- if (normalizePath && piece === '..') {
- path.pop()
- } else if (!normalizePath || piece !== '.') {
- if (decodePath) piece = decodeURIComponent(piece)
- path.push(encodeRfc3986(encodeURIComponent(piece)))
- }
- return path
- }, []).join('/')
- if (pathStr[0] !== '/') pathStr = '/' + pathStr
- if (decodeSlashesInPath) pathStr = pathStr.replace(/%2F/g, '/')
- }
-
- return [
- this.request.method || 'GET',
- pathStr,
- queryStr,
- this.canonicalHeaders() + '\n',
- this.signedHeaders(),
- bodyHash,
- ].join('\n')
-}
-
-RequestSigner.prototype.canonicalHeaders = function() {
- var headers = this.request.headers
- function trimAll(header) {
- return header.toString().trim().replace(/\s+/g, ' ')
- }
- return Object.keys(headers)
- .sort(function(a, b) { return a.toLowerCase() < b.toLowerCase() ? -1 : 1 })
- .map(function(key) { return key.toLowerCase() + ':' + trimAll(headers[key]) })
- .join('\n')
-}
-
-RequestSigner.prototype.signedHeaders = function() {
- return Object.keys(this.request.headers)
- .map(function(key) { return key.toLowerCase() })
- .sort()
- .join(';')
-}
-
-RequestSigner.prototype.credentialString = function() {
- return [
- this.getDate(),
- this.region,
- this.service,
- 'aws4_request',
- ].join('/')
-}
-
-RequestSigner.prototype.defaultCredentials = function() {
- var env = process.env
- return {
- accessKeyId: env.AWS_ACCESS_KEY_ID || env.AWS_ACCESS_KEY,
- secretAccessKey: env.AWS_SECRET_ACCESS_KEY || env.AWS_SECRET_KEY,
- sessionToken: env.AWS_SESSION_TOKEN,
- }
-}
-
-RequestSigner.prototype.parsePath = function() {
- var path = this.request.path || '/',
- queryIx = path.indexOf('?'),
- query = null
-
- if (queryIx >= 0) {
- query = querystring.parse(path.slice(queryIx + 1))
- path = path.slice(0, queryIx)
- }
-
- // S3 doesn't always encode characters > 127 correctly and
- // all services don't encode characters > 255 correctly
- // So if there are non-reserved chars (and it's not already all % encoded), just encode them all
- if (/[^0-9A-Za-z!'()*\-._~%/]/.test(path)) {
- path = path.split('/').map(function(piece) {
- return encodeURIComponent(decodeURIComponent(piece))
- }).join('/')
- }
-
- this.parsedPath = {
- path: path,
- query: query,
- }
-}
-
-RequestSigner.prototype.formatPath = function() {
- var path = this.parsedPath.path,
- query = this.parsedPath.query
-
- if (!query) return path
-
- // Services don't support empty query string keys
- if (query[''] != null) delete query['']
-
- return path + '?' + encodeRfc3986(querystring.stringify(query))
-}
-
-aws4.RequestSigner = RequestSigner
-
-aws4.sign = function(request, credentials) {
- return new RequestSigner(request, credentials).sign()
-}
-
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"./lru":156,"_process":1438,"buffer":217,"crypto":236,"querystring":1547,"url":1769}],156:[function(require,module,exports){
-module.exports = function(size) {
- return new LruCache(size)
-}
-
-function LruCache(size) {
- this.capacity = size | 0
- this.map = Object.create(null)
- this.list = new DoublyLinkedList()
-}
-
-LruCache.prototype.get = function(key) {
- var node = this.map[key]
- if (node == null) return undefined
- this.used(node)
- return node.val
-}
-
-LruCache.prototype.set = function(key, val) {
- var node = this.map[key]
- if (node != null) {
- node.val = val
- } else {
- if (!this.capacity) this.prune()
- if (!this.capacity) return false
- node = new DoublyLinkedNode(key, val)
- this.map[key] = node
- this.capacity--
- }
- this.used(node)
- return true
-}
-
-LruCache.prototype.used = function(node) {
- this.list.moveToFront(node)
-}
-
-LruCache.prototype.prune = function() {
- var node = this.list.pop()
- if (node != null) {
- delete this.map[node.key]
- this.capacity++
- }
-}
-
-
-function DoublyLinkedList() {
- this.firstNode = null
- this.lastNode = null
-}
-
-DoublyLinkedList.prototype.moveToFront = function(node) {
- if (this.firstNode == node) return
-
- this.remove(node)
-
- if (this.firstNode == null) {
- this.firstNode = node
- this.lastNode = node
- node.prev = null
- node.next = null
- } else {
- node.prev = null
- node.next = this.firstNode
- node.next.prev = node
- this.firstNode = node
- }
-}
-
-DoublyLinkedList.prototype.pop = function() {
- var lastNode = this.lastNode
- if (lastNode != null) {
- this.remove(lastNode)
- }
- return lastNode
-}
-
-DoublyLinkedList.prototype.remove = function(node) {
- if (this.firstNode == node) {
- this.firstNode = node.next
- } else if (node.prev != null) {
- node.prev.next = node.next
- }
- if (this.lastNode == node) {
- this.lastNode = node.prev
- } else if (node.next != null) {
- node.next.prev = node.prev
- }
-}
-
-
-function DoublyLinkedNode(key, val) {
- this.key = key
- this.val = val
- this.prev = null
- this.next = null
-}
-
-},{}],157:[function(require,module,exports){
+},{"./internal/onlyOnce":79,"./internal/slice":84,"./internal/wrapAsync":86,"lodash/noop":1120}],104:[function(require,module,exports){
/**
* Expose `Backoff`.
@@ -18133,7 +10462,7 @@ Backoff.prototype.setJitter = function(jitter){
};
-},{}],158:[function(require,module,exports){
+},{}],105:[function(require,module,exports){
'use strict'
// base-x encoding / decoding
// Copyright (c) 2018 base-x contributors
@@ -18255,7 +10584,7 @@ function base (ALPHABET) {
}
module.exports = base
-},{"safe-buffer":1593}],159:[function(require,module,exports){
+},{"safe-buffer":1371}],106:[function(require,module,exports){
var RFC4648 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
var RFC4648_HEX = '0123456789ABCDEFGHIJKLMNOPQRSTUV'
var CROCKFORD = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'
@@ -18313,7 +10642,7 @@ module.exports = function base32Encode (buffer, variant, options) {
return output
}
-},{}],160:[function(require,module,exports){
+},{}],107:[function(require,module,exports){
"use strict";
/**
@@ -18627,7 +10956,7 @@ exports.crockford = crockford;
exports.rfc4648 = rfc4648;
exports.base32hex = base32hex;
-},{}],161:[function(require,module,exports){
+},{}],108:[function(require,module,exports){
/*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
@@ -18696,7 +11025,7 @@ exports.base32hex = base32hex;
};
})();
-},{}],162:[function(require,module,exports){
+},{}],109:[function(require,module,exports){
'use strict'
exports.byteLength = byteLength
@@ -18764,8 +11093,7 @@ function toByteArray (b64) {
? validLen - 4
: validLen
- var i
- for (i = 0; i < len; i += 4) {
+ for (var i = 0; i < len; i += 4) {
tmp =
(revLookup[b64.charCodeAt(i)] << 18) |
(revLookup[b64.charCodeAt(i + 1)] << 12) |
@@ -18850,565 +11178,7 @@ function fromByteArray (uint8) {
return parts.join('')
}
-},{}],163:[function(require,module,exports){
-'use strict';
-
-var crypto_hash_sha512 = require('tweetnacl').lowlevel.crypto_hash;
-
-/*
- * This file is a 1:1 port from the OpenBSD blowfish.c and bcrypt_pbkdf.c. As a
- * result, it retains the original copyright and license. The two files are
- * under slightly different (but compatible) licenses, and are here combined in
- * one file.
- *
- * Credit for the actual porting work goes to:
- * Devi Mandiri
- */
-
-/*
- * The Blowfish portions are under the following license:
- *
- * Blowfish block cipher for OpenBSD
- * Copyright 1997 Niels Provos
- * All rights reserved.
- *
- * Implementation advice by David Mazieres .
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. The name of the author may not be used to endorse or promote products
- * derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
- * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
- * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
- * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
- * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * The bcrypt_pbkdf portions are under the following license:
- *
- * Copyright (c) 2013 Ted Unangst
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
- * Performance improvements (Javascript-specific):
- *
- * Copyright 2016, Joyent Inc
- * Author: Alex Wilson
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-// Ported from OpenBSD bcrypt_pbkdf.c v1.9
-
-var BLF_J = 0;
-
-var Blowfish = function() {
- this.S = [
- new Uint32Array([
- 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
- 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
- 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
- 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
- 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
- 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
- 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
- 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
- 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
- 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
- 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
- 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
- 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
- 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
- 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
- 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
- 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
- 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
- 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
- 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
- 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
- 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
- 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
- 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
- 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
- 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
- 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
- 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
- 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
- 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
- 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
- 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
- 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
- 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
- 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
- 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
- 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
- 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
- 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
- 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
- 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
- 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
- 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
- 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
- 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
- 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
- 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
- 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
- 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
- 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
- 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
- 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
- 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
- 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
- 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
- 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
- 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
- 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
- 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
- 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
- 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
- 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
- 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
- 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a]),
- new Uint32Array([
- 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
- 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
- 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
- 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
- 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
- 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
- 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
- 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
- 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
- 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
- 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
- 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
- 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
- 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
- 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
- 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
- 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
- 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
- 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
- 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
- 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
- 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
- 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
- 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
- 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
- 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
- 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
- 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
- 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
- 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
- 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
- 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
- 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
- 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
- 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
- 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
- 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
- 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
- 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
- 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
- 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
- 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
- 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
- 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
- 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
- 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
- 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
- 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
- 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
- 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
- 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
- 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
- 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
- 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
- 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
- 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
- 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
- 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
- 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
- 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
- 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
- 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
- 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
- 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7]),
- new Uint32Array([
- 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
- 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
- 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
- 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
- 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
- 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
- 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
- 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
- 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
- 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
- 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
- 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
- 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
- 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
- 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
- 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
- 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
- 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
- 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
- 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
- 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
- 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
- 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
- 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
- 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
- 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
- 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
- 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
- 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
- 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
- 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
- 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
- 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
- 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
- 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
- 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
- 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
- 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
- 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
- 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
- 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
- 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
- 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
- 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
- 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
- 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
- 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
- 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
- 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
- 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
- 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
- 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
- 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
- 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
- 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
- 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
- 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
- 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
- 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
- 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
- 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
- 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
- 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
- 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0]),
- new Uint32Array([
- 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
- 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
- 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
- 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
- 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
- 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
- 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
- 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
- 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
- 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
- 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
- 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
- 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
- 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
- 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
- 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
- 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
- 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
- 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
- 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
- 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
- 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
- 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
- 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
- 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
- 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
- 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
- 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
- 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
- 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
- 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
- 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
- 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
- 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
- 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
- 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
- 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
- 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
- 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
- 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
- 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
- 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
- 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
- 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
- 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
- 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
- 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
- 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
- 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
- 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
- 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
- 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
- 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
- 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
- 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
- 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
- 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
- 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
- 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
- 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
- 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
- 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
- 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
- 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6])
- ];
- this.P = new Uint32Array([
- 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
- 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
- 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
- 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
- 0x9216d5d9, 0x8979fb1b]);
-};
-
-function F(S, x8, i) {
- return (((S[0][x8[i+3]] +
- S[1][x8[i+2]]) ^
- S[2][x8[i+1]]) +
- S[3][x8[i]]);
-};
-
-Blowfish.prototype.encipher = function(x, x8) {
- if (x8 === undefined) {
- x8 = new Uint8Array(x.buffer);
- if (x.byteOffset !== 0)
- x8 = x8.subarray(x.byteOffset);
- }
- x[0] ^= this.P[0];
- for (var i = 1; i < 16; i += 2) {
- x[1] ^= F(this.S, x8, 0) ^ this.P[i];
- x[0] ^= F(this.S, x8, 4) ^ this.P[i+1];
- }
- var t = x[0];
- x[0] = x[1] ^ this.P[17];
- x[1] = t;
-};
-
-Blowfish.prototype.decipher = function(x) {
- var x8 = new Uint8Array(x.buffer);
- if (x.byteOffset !== 0)
- x8 = x8.subarray(x.byteOffset);
- x[0] ^= this.P[17];
- for (var i = 16; i > 0; i -= 2) {
- x[1] ^= F(this.S, x8, 0) ^ this.P[i];
- x[0] ^= F(this.S, x8, 4) ^ this.P[i-1];
- }
- var t = x[0];
- x[0] = x[1] ^ this.P[0];
- x[1] = t;
-};
-
-function stream2word(data, databytes){
- var i, temp = 0;
- for (i = 0; i < 4; i++, BLF_J++) {
- if (BLF_J >= databytes) BLF_J = 0;
- temp = (temp << 8) | data[BLF_J];
- }
- return temp;
-};
-
-Blowfish.prototype.expand0state = function(key, keybytes) {
- var d = new Uint32Array(2), i, k;
- var d8 = new Uint8Array(d.buffer);
-
- for (i = 0, BLF_J = 0; i < 18; i++) {
- this.P[i] ^= stream2word(key, keybytes);
- }
- BLF_J = 0;
-
- for (i = 0; i < 18; i += 2) {
- this.encipher(d, d8);
- this.P[i] = d[0];
- this.P[i+1] = d[1];
- }
-
- for (i = 0; i < 4; i++) {
- for (k = 0; k < 256; k += 2) {
- this.encipher(d, d8);
- this.S[i][k] = d[0];
- this.S[i][k+1] = d[1];
- }
- }
-};
-
-Blowfish.prototype.expandstate = function(data, databytes, key, keybytes) {
- var d = new Uint32Array(2), i, k;
-
- for (i = 0, BLF_J = 0; i < 18; i++) {
- this.P[i] ^= stream2word(key, keybytes);
- }
-
- for (i = 0, BLF_J = 0; i < 18; i += 2) {
- d[0] ^= stream2word(data, databytes);
- d[1] ^= stream2word(data, databytes);
- this.encipher(d);
- this.P[i] = d[0];
- this.P[i+1] = d[1];
- }
-
- for (i = 0; i < 4; i++) {
- for (k = 0; k < 256; k += 2) {
- d[0] ^= stream2word(data, databytes);
- d[1] ^= stream2word(data, databytes);
- this.encipher(d);
- this.S[i][k] = d[0];
- this.S[i][k+1] = d[1];
- }
- }
- BLF_J = 0;
-};
-
-Blowfish.prototype.enc = function(data, blocks) {
- for (var i = 0; i < blocks; i++) {
- this.encipher(data.subarray(i*2));
- }
-};
-
-Blowfish.prototype.dec = function(data, blocks) {
- for (var i = 0; i < blocks; i++) {
- this.decipher(data.subarray(i*2));
- }
-};
-
-var BCRYPT_BLOCKS = 8,
- BCRYPT_HASHSIZE = 32;
-
-function bcrypt_hash(sha2pass, sha2salt, out) {
- var state = new Blowfish(),
- cdata = new Uint32Array(BCRYPT_BLOCKS), i,
- ciphertext = new Uint8Array([79,120,121,99,104,114,111,109,97,116,105,
- 99,66,108,111,119,102,105,115,104,83,119,97,116,68,121,110,97,109,
- 105,116,101]); //"OxychromaticBlowfishSwatDynamite"
-
- state.expandstate(sha2salt, 64, sha2pass, 64);
- for (i = 0; i < 64; i++) {
- state.expand0state(sha2salt, 64);
- state.expand0state(sha2pass, 64);
- }
-
- for (i = 0; i < BCRYPT_BLOCKS; i++)
- cdata[i] = stream2word(ciphertext, ciphertext.byteLength);
- for (i = 0; i < 64; i++)
- state.enc(cdata, cdata.byteLength / 8);
-
- for (i = 0; i < BCRYPT_BLOCKS; i++) {
- out[4*i+3] = cdata[i] >>> 24;
- out[4*i+2] = cdata[i] >>> 16;
- out[4*i+1] = cdata[i] >>> 8;
- out[4*i+0] = cdata[i];
- }
-};
-
-function bcrypt_pbkdf(pass, passlen, salt, saltlen, key, keylen, rounds) {
- var sha2pass = new Uint8Array(64),
- sha2salt = new Uint8Array(64),
- out = new Uint8Array(BCRYPT_HASHSIZE),
- tmpout = new Uint8Array(BCRYPT_HASHSIZE),
- countsalt = new Uint8Array(saltlen+4),
- i, j, amt, stride, dest, count,
- origkeylen = keylen;
-
- if (rounds < 1)
- return -1;
- if (passlen === 0 || saltlen === 0 || keylen === 0 ||
- keylen > (out.byteLength * out.byteLength) || saltlen > (1<<20))
- return -1;
-
- stride = Math.floor((keylen + out.byteLength - 1) / out.byteLength);
- amt = Math.floor((keylen + stride - 1) / stride);
-
- for (i = 0; i < saltlen; i++)
- countsalt[i] = salt[i];
-
- crypto_hash_sha512(sha2pass, pass, passlen);
-
- for (count = 1; keylen > 0; count++) {
- countsalt[saltlen+0] = count >>> 24;
- countsalt[saltlen+1] = count >>> 16;
- countsalt[saltlen+2] = count >>> 8;
- countsalt[saltlen+3] = count;
-
- crypto_hash_sha512(sha2salt, countsalt, saltlen + 4);
- bcrypt_hash(sha2pass, sha2salt, tmpout);
- for (i = out.byteLength; i--;)
- out[i] = tmpout[i];
-
- for (i = 1; i < rounds; i++) {
- crypto_hash_sha512(sha2salt, tmpout, tmpout.byteLength);
- bcrypt_hash(sha2pass, sha2salt, tmpout);
- for (j = 0; j < out.byteLength; j++)
- out[j] ^= tmpout[j];
- }
-
- amt = Math.min(amt, keylen);
- for (i = 0; i < amt; i++) {
- dest = i * stride + (count - 1);
- if (dest >= origkeylen)
- break;
- key[dest] = out[i];
- }
- keylen -= i;
- }
-
- return 0;
-};
-
-module.exports = {
- BLOCKS: BCRYPT_BLOCKS,
- HASHSIZE: BCRYPT_HASHSIZE,
- hash: bcrypt_hash,
- pbkdf: bcrypt_pbkdf
-};
-
-},{"tweetnacl":1762}],164:[function(require,module,exports){
+},{}],110:[function(require,module,exports){
;(function (globalObject) {
'use strict';
@@ -22312,7 +14082,7 @@ module.exports = {
}
})(this);
-},{}],165:[function(require,module,exports){
+},{}],111:[function(require,module,exports){
// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
// NOTE: SIGHASH byte ignored AND restricted, truncate before use
@@ -22427,7 +14197,427 @@ module.exports = {
encode: encode
}
-},{"safe-buffer":1593}],166:[function(require,module,exports){
+},{"safe-buffer":1371}],112:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+var DuplexStream = require('readable-stream').Duplex
+ , util = require('util')
+
+function BufferList (callback) {
+ if (!(this instanceof BufferList))
+ return new BufferList(callback)
+
+ this._bufs = []
+ this.length = 0
+
+ if (typeof callback == 'function') {
+ this._callback = callback
+
+ var piper = function piper (err) {
+ if (this._callback) {
+ this._callback(err)
+ this._callback = null
+ }
+ }.bind(this)
+
+ this.on('pipe', function onPipe (src) {
+ src.on('error', piper)
+ })
+ this.on('unpipe', function onUnpipe (src) {
+ src.removeListener('error', piper)
+ })
+ } else {
+ this.append(callback)
+ }
+
+ DuplexStream.call(this)
+}
+
+
+util.inherits(BufferList, DuplexStream)
+
+
+BufferList.prototype._offset = function _offset (offset) {
+ var tot = 0, i = 0, _t
+ if (offset === 0) return [ 0, 0 ]
+ for (; i < this._bufs.length; i++) {
+ _t = tot + this._bufs[i].length
+ if (offset < _t || i == this._bufs.length - 1) {
+ return [ i, offset - tot ]
+ }
+ tot = _t
+ }
+}
+
+BufferList.prototype._reverseOffset = function (blOffset) {
+ var bufferId = blOffset[0]
+ var offset = blOffset[1]
+ for (var i = 0; i < bufferId; i++) {
+ offset += this._bufs[i].length
+ }
+ return offset
+}
+
+BufferList.prototype.append = function append (buf) {
+ var i = 0
+
+ if (Buffer.isBuffer(buf)) {
+ this._appendBuffer(buf)
+ } else if (Array.isArray(buf)) {
+ for (; i < buf.length; i++)
+ this.append(buf[i])
+ } else if (buf instanceof BufferList) {
+ // unwrap argument into individual BufferLists
+ for (; i < buf._bufs.length; i++)
+ this.append(buf._bufs[i])
+ } else if (buf != null) {
+ // coerce number arguments to strings, since Buffer(number) does
+ // uninitialized memory allocation
+ if (typeof buf == 'number')
+ buf = buf.toString()
+
+ this._appendBuffer(Buffer.from(buf))
+ }
+
+ return this
+}
+
+
+BufferList.prototype._appendBuffer = function appendBuffer (buf) {
+ this._bufs.push(buf)
+ this.length += buf.length
+}
+
+
+BufferList.prototype._write = function _write (buf, encoding, callback) {
+ this._appendBuffer(buf)
+
+ if (typeof callback == 'function')
+ callback()
+}
+
+
+BufferList.prototype._read = function _read (size) {
+ if (!this.length)
+ return this.push(null)
+
+ size = Math.min(size, this.length)
+ this.push(this.slice(0, size))
+ this.consume(size)
+}
+
+
+BufferList.prototype.end = function end (chunk) {
+ DuplexStream.prototype.end.call(this, chunk)
+
+ if (this._callback) {
+ this._callback(null, this.slice())
+ this._callback = null
+ }
+}
+
+
+BufferList.prototype.get = function get (index) {
+ if (index > this.length || index < 0) {
+ return undefined
+ }
+ var offset = this._offset(index)
+ return this._bufs[offset[0]][offset[1]]
+}
+
+
+BufferList.prototype.slice = function slice (start, end) {
+ if (typeof start == 'number' && start < 0)
+ start += this.length
+ if (typeof end == 'number' && end < 0)
+ end += this.length
+ return this.copy(null, 0, start, end)
+}
+
+
+BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) {
+ if (typeof srcStart != 'number' || srcStart < 0)
+ srcStart = 0
+ if (typeof srcEnd != 'number' || srcEnd > this.length)
+ srcEnd = this.length
+ if (srcStart >= this.length)
+ return dst || Buffer.alloc(0)
+ if (srcEnd <= 0)
+ return dst || Buffer.alloc(0)
+
+ var copy = !!dst
+ , off = this._offset(srcStart)
+ , len = srcEnd - srcStart
+ , bytes = len
+ , bufoff = (copy && dstStart) || 0
+ , start = off[1]
+ , l
+ , i
+
+ // copy/slice everything
+ if (srcStart === 0 && srcEnd == this.length) {
+ if (!copy) { // slice, but full concat if multiple buffers
+ return this._bufs.length === 1
+ ? this._bufs[0]
+ : Buffer.concat(this._bufs, this.length)
+ }
+
+ // copy, need to copy individual buffers
+ for (i = 0; i < this._bufs.length; i++) {
+ this._bufs[i].copy(dst, bufoff)
+ bufoff += this._bufs[i].length
+ }
+
+ return dst
+ }
+
+ // easy, cheap case where it's a subset of one of the buffers
+ if (bytes <= this._bufs[off[0]].length - start) {
+ return copy
+ ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes)
+ : this._bufs[off[0]].slice(start, start + bytes)
+ }
+
+ if (!copy) // a slice, we need something to copy in to
+ dst = Buffer.allocUnsafe(len)
+
+ for (i = off[0]; i < this._bufs.length; i++) {
+ l = this._bufs[i].length - start
+
+ if (bytes > l) {
+ this._bufs[i].copy(dst, bufoff, start)
+ } else {
+ this._bufs[i].copy(dst, bufoff, start, start + bytes)
+ break
+ }
+
+ bufoff += l
+ bytes -= l
+
+ if (start)
+ start = 0
+ }
+
+ return dst
+}
+
+BufferList.prototype.shallowSlice = function shallowSlice (start, end) {
+ start = start || 0
+ end = typeof end !== 'number' ? this.length : end
+
+ if (start < 0)
+ start += this.length
+ if (end < 0)
+ end += this.length
+
+ if (start === end) {
+ return new BufferList()
+ }
+ var startOffset = this._offset(start)
+ , endOffset = this._offset(end)
+ , buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1)
+
+ if (endOffset[1] == 0)
+ buffers.pop()
+ else
+ buffers[buffers.length-1] = buffers[buffers.length-1].slice(0, endOffset[1])
+
+ if (startOffset[1] != 0)
+ buffers[0] = buffers[0].slice(startOffset[1])
+
+ return new BufferList(buffers)
+}
+
+BufferList.prototype.toString = function toString (encoding, start, end) {
+ return this.slice(start, end).toString(encoding)
+}
+
+BufferList.prototype.consume = function consume (bytes) {
+ while (this._bufs.length) {
+ if (bytes >= this._bufs[0].length) {
+ bytes -= this._bufs[0].length
+ this.length -= this._bufs[0].length
+ this._bufs.shift()
+ } else {
+ this._bufs[0] = this._bufs[0].slice(bytes)
+ this.length -= bytes
+ break
+ }
+ }
+ return this
+}
+
+
+BufferList.prototype.duplicate = function duplicate () {
+ var i = 0
+ , copy = new BufferList()
+
+ for (; i < this._bufs.length; i++)
+ copy.append(this._bufs[i])
+
+ return copy
+}
+
+
+BufferList.prototype._destroy = function _destroy (err, cb) {
+ this._bufs.length = 0
+ this.length = 0
+ cb(err)
+}
+
+
+BufferList.prototype.indexOf = function (search, offset, encoding) {
+ if (encoding === undefined && typeof offset === 'string') {
+ encoding = offset
+ offset = undefined
+ }
+ if (typeof search === 'function' || Array.isArray(search)) {
+ throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.')
+ } else if (typeof search === 'number') {
+ search = Buffer.from([search])
+ } else if (typeof search === 'string') {
+ search = Buffer.from(search, encoding)
+ } else if (search instanceof BufferList) {
+ search = search.slice()
+ } else if (!Buffer.isBuffer(search)) {
+ search = Buffer.from(search)
+ }
+
+ offset = Number(offset || 0)
+ if (isNaN(offset)) {
+ offset = 0
+ }
+
+ if (offset < 0) {
+ offset = this.length + offset
+ }
+
+ if (offset < 0) {
+ offset = 0
+ }
+
+ if (search.length === 0) {
+ return offset > this.length ? this.length : offset
+ }
+
+ var blOffset = this._offset(offset)
+ var blIndex = blOffset[0] // index of which internal buffer we're working on
+ var buffOffset = blOffset[1] // offset of the internal buffer we're working on
+
+ // scan over each buffer
+ for (blIndex; blIndex < this._bufs.length; blIndex++) {
+ var buff = this._bufs[blIndex]
+ while(buffOffset < buff.length) {
+ var availableWindow = buff.length - buffOffset
+ if (availableWindow >= search.length) {
+ var nativeSearchResult = buff.indexOf(search, buffOffset)
+ if (nativeSearchResult !== -1) {
+ return this._reverseOffset([blIndex, nativeSearchResult])
+ }
+ buffOffset = buff.length - search.length + 1 // end of native search window
+ } else {
+ var revOffset = this._reverseOffset([blIndex, buffOffset])
+ if (this._match(revOffset, search)) {
+ return revOffset
+ }
+ buffOffset++
+ }
+ }
+ buffOffset = 0
+ }
+ return -1
+}
+
+BufferList.prototype._match = function(offset, search) {
+ if (this.length - offset < search.length) {
+ return false
+ }
+ for (var searchOffset = 0; searchOffset < search.length ; searchOffset++) {
+ if(this.get(offset + searchOffset) !== search[searchOffset]){
+ return false
+ }
+ }
+ return true
+}
+
+
+;(function () {
+ var methods = {
+ 'readDoubleBE' : 8
+ , 'readDoubleLE' : 8
+ , 'readFloatBE' : 4
+ , 'readFloatLE' : 4
+ , 'readInt32BE' : 4
+ , 'readInt32LE' : 4
+ , 'readUInt32BE' : 4
+ , 'readUInt32LE' : 4
+ , 'readInt16BE' : 2
+ , 'readInt16LE' : 2
+ , 'readUInt16BE' : 2
+ , 'readUInt16LE' : 2
+ , 'readInt8' : 1
+ , 'readUInt8' : 1
+ , 'readIntBE' : null
+ , 'readIntLE' : null
+ , 'readUIntBE' : null
+ , 'readUIntLE' : null
+ }
+
+ for (var m in methods) {
+ (function (m) {
+ if (methods[m] === null) {
+ BufferList.prototype[m] = function (offset, byteLength) {
+ return this.slice(offset, offset + byteLength)[m](0, byteLength)
+ }
+ }
+ else {
+ BufferList.prototype[m] = function (offset) {
+ return this.slice(offset, offset + methods[m])[m](0)
+ }
+ }
+ }(m))
+ }
+}())
+
+
+module.exports = BufferList
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"readable-stream":127,"util":1512}],113:[function(require,module,exports){
+arguments[4][36][0].apply(exports,arguments)
+},{"dup":36}],114:[function(require,module,exports){
+arguments[4][37][0].apply(exports,arguments)
+},{"_process":1258,"dup":37}],115:[function(require,module,exports){
+arguments[4][38][0].apply(exports,arguments)
+},{"./_stream_readable":117,"./_stream_writable":119,"_process":1258,"dup":38,"inherits":317}],116:[function(require,module,exports){
+arguments[4][39][0].apply(exports,arguments)
+},{"./_stream_transform":118,"dup":39,"inherits":317}],117:[function(require,module,exports){
+arguments[4][40][0].apply(exports,arguments)
+},{"../errors":113,"../experimentalWarning":114,"./_stream_duplex":115,"./internal/streams/async_iterator":120,"./internal/streams/buffer_list":121,"./internal/streams/destroy":122,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":129,"util":146}],118:[function(require,module,exports){
+arguments[4][41][0].apply(exports,arguments)
+},{"../errors":113,"./_stream_duplex":115,"dup":41,"inherits":317}],119:[function(require,module,exports){
+arguments[4][42][0].apply(exports,arguments)
+},{"../errors":113,"./_stream_duplex":115,"./internal/streams/destroy":122,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],120:[function(require,module,exports){
+arguments[4][43][0].apply(exports,arguments)
+},{"./end-of-stream":123,"_process":1258,"dup":43}],121:[function(require,module,exports){
+arguments[4][44][0].apply(exports,arguments)
+},{"buffer":181,"dup":44,"util":146}],122:[function(require,module,exports){
+arguments[4][45][0].apply(exports,arguments)
+},{"_process":1258,"dup":45}],123:[function(require,module,exports){
+arguments[4][46][0].apply(exports,arguments)
+},{"../../../errors":113,"dup":46}],124:[function(require,module,exports){
+arguments[4][47][0].apply(exports,arguments)
+},{"../../../errors":113,"./end-of-stream":123,"dup":47}],125:[function(require,module,exports){
+arguments[4][48][0].apply(exports,arguments)
+},{"../../../errors":113,"dup":48}],126:[function(require,module,exports){
+arguments[4][49][0].apply(exports,arguments)
+},{"dup":49,"events":272}],127:[function(require,module,exports){
+arguments[4][50][0].apply(exports,arguments)
+},{"./lib/_stream_duplex.js":115,"./lib/_stream_passthrough.js":116,"./lib/_stream_readable.js":117,"./lib/_stream_transform.js":118,"./lib/_stream_writable.js":119,"./lib/internal/streams/end-of-stream.js":123,"./lib/internal/streams/pipeline.js":124,"dup":50}],128:[function(require,module,exports){
+arguments[4][51][0].apply(exports,arguments)
+},{"buffer":181,"dup":51}],129:[function(require,module,exports){
+arguments[4][52][0].apply(exports,arguments)
+},{"dup":52,"safe-buffer":128}],130:[function(require,module,exports){
// Blake2B in pure Javascript
// Adapted from the reference implementation in RFC7693
// Ported to Javascript by DC - https://github.com/dcposch
@@ -22702,7 +14892,7 @@ module.exports = {
blake2bFinal: blake2bFinal
}
-},{"./util":169}],167:[function(require,module,exports){
+},{"./util":133}],131:[function(require,module,exports){
// BLAKE2s hash function in pure Javascript
// Adapted from the reference implementation in RFC7693
// Ported to Javascript by DC - https://github.com/dcposch
@@ -22894,7 +15084,7 @@ module.exports = {
blake2sFinal: blake2sFinal
}
-},{"./util":169}],168:[function(require,module,exports){
+},{"./util":133}],132:[function(require,module,exports){
var b2b = require('./blake2b')
var b2s = require('./blake2s')
@@ -22911,7 +15101,7 @@ module.exports = {
blake2sFinal: b2s.blake2sFinal
}
-},{"./blake2b":166,"./blake2s":167}],169:[function(require,module,exports){
+},{"./blake2b":130,"./blake2s":131}],133:[function(require,module,exports){
(function (Buffer){
var ERROR_MSG_INPUT = 'Input must be an string, Buffer or Uint8Array'
@@ -22996,7 +15186,7 @@ module.exports = {
}
}).call(this,require("buffer").Buffer)
-},{"buffer":217}],170:[function(require,module,exports){
+},{"buffer":181}],134:[function(require,module,exports){
/**
* Create a blob builder even when vendor prefixes exist
*/
@@ -23004,7 +15194,7 @@ module.exports = {
var BlobBuilder = typeof BlobBuilder !== 'undefined' ? BlobBuilder :
typeof WebKitBlobBuilder !== 'undefined' ? WebKitBlobBuilder :
typeof MSBlobBuilder !== 'undefined' ? MSBlobBuilder :
- typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
+ typeof MozBlobBuilder !== 'undefined' ? MozBlobBuilder :
false;
/**
@@ -23098,7 +15288,7 @@ module.exports = (function() {
}
})();
-},{}],171:[function(require,module,exports){
+},{}],135:[function(require,module,exports){
(function (module, exports) {
'use strict';
@@ -26527,7 +18717,7 @@ module.exports = (function() {
};
})(typeof module === 'undefined' || module, this);
-},{"buffer":182}],172:[function(require,module,exports){
+},{"buffer":146}],136:[function(require,module,exports){
'use strict'
const Bignumber = require('bignumber.js').BigNumber
@@ -26602,7 +18792,7 @@ exports.PARENT = {
UTF8_STRING: 5
}
-},{"bignumber.js":164}],173:[function(require,module,exports){
+},{"bignumber.js":110}],137:[function(require,module,exports){
module.exports = function decodeAsm (stdlib, foreign, buffer) {
'use asm'
@@ -27939,7 +20129,7 @@ module.exports = function decodeAsm (stdlib, foreign, buffer) {
}
}
-},{}],174:[function(require,module,exports){
+},{}],138:[function(require,module,exports){
(function (global,Buffer){
'use strict'
@@ -28564,7 +20754,7 @@ Decoder.decodeFirst = Decoder.decode
module.exports = Decoder
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
-},{"./constants":172,"./decoder.asm":173,"./simple":178,"./tagged":179,"./utils":180,"bignumber.js":164,"buffer":217,"ieee754":451,"iso-url":802}],175:[function(require,module,exports){
+},{"./constants":136,"./decoder.asm":137,"./simple":142,"./tagged":143,"./utils":144,"bignumber.js":110,"buffer":181,"ieee754":315,"iso-url":641}],139:[function(require,module,exports){
(function (Buffer){
'use strict'
@@ -28747,7 +20937,7 @@ function collectObject (val) {
}
}).call(this,require("buffer").Buffer)
-},{"./decoder":174,"./utils":180,"buffer":217}],176:[function(require,module,exports){
+},{"./decoder":138,"./utils":144,"buffer":181}],140:[function(require,module,exports){
(function (Buffer){
'use strict'
@@ -29271,7 +21461,7 @@ class Encoder {
module.exports = Encoder
}).call(this,require("buffer").Buffer)
-},{"./constants":172,"./utils":180,"bignumber.js":164,"buffer":217,"iso-url":802}],177:[function(require,module,exports){
+},{"./constants":136,"./utils":144,"bignumber.js":110,"buffer":181,"iso-url":641}],141:[function(require,module,exports){
'use strict'
// exports.Commented = require('./commented')
@@ -29295,7 +21485,7 @@ exports.leveldb = {
name: 'cbor'
}
-},{"./decoder":174,"./diagnose":175,"./encoder":176,"./simple":178,"./tagged":179}],178:[function(require,module,exports){
+},{"./decoder":138,"./diagnose":139,"./encoder":140,"./simple":142,"./tagged":143}],142:[function(require,module,exports){
'use strict'
const constants = require('./constants')
@@ -29404,7 +21594,7 @@ class Simple {
module.exports = Simple
-},{"./constants":172}],179:[function(require,module,exports){
+},{"./constants":136}],143:[function(require,module,exports){
'use strict'
/**
@@ -29484,7 +21674,7 @@ class Tagged {
module.exports = Tagged
-},{}],180:[function(require,module,exports){
+},{}],144:[function(require,module,exports){
(function (Buffer){
'use strict'
@@ -29661,7 +21851,7 @@ exports.nextPowerOf2 = (n) => {
}
}).call(this,require("buffer").Buffer)
-},{"./constants":172,"bignumber.js":164,"buffer":217}],181:[function(require,module,exports){
+},{"./constants":136,"bignumber.js":110,"buffer":181}],145:[function(require,module,exports){
var r;
module.exports = function rand(len) {
@@ -29728,9 +21918,9 @@ if (typeof self === 'object') {
}
}
-},{"crypto":182}],182:[function(require,module,exports){
+},{"crypto":146}],146:[function(require,module,exports){
-},{}],183:[function(require,module,exports){
+},{}],147:[function(require,module,exports){
// based on the aes implimentation in triple sec
// https://github.com/keybase/triplesec
// which is in turn based on the one from crypto-js
@@ -29960,7 +22150,7 @@ AES.prototype.scrub = function () {
module.exports.AES = AES
-},{"safe-buffer":1593}],184:[function(require,module,exports){
+},{"safe-buffer":1371}],148:[function(require,module,exports){
var aes = require('./aes')
var Buffer = require('safe-buffer').Buffer
var Transform = require('cipher-base')
@@ -30079,7 +22269,7 @@ StreamCipher.prototype.setAAD = function setAAD (buf) {
module.exports = StreamCipher
-},{"./aes":183,"./ghash":188,"./incr32":189,"buffer-xor":216,"cipher-base":223,"inherits":453,"safe-buffer":1593}],185:[function(require,module,exports){
+},{"./aes":147,"./ghash":152,"./incr32":153,"buffer-xor":180,"cipher-base":186,"inherits":317,"safe-buffer":1371}],149:[function(require,module,exports){
var ciphers = require('./encrypter')
var deciphers = require('./decrypter')
var modes = require('./modes/list.json')
@@ -30094,7 +22284,7 @@ exports.createDecipher = exports.Decipher = deciphers.createDecipher
exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers
-},{"./decrypter":186,"./encrypter":187,"./modes/list.json":197}],186:[function(require,module,exports){
+},{"./decrypter":150,"./encrypter":151,"./modes/list.json":161}],150:[function(require,module,exports){
var AuthCipher = require('./authCipher')
var Buffer = require('safe-buffer').Buffer
var MODES = require('./modes')
@@ -30220,7 +22410,7 @@ function createDecipher (suite, password) {
exports.createDecipher = createDecipher
exports.createDecipheriv = createDecipheriv
-},{"./aes":183,"./authCipher":184,"./modes":196,"./streamCipher":199,"cipher-base":223,"evp_bytestokey":371,"inherits":453,"safe-buffer":1593}],187:[function(require,module,exports){
+},{"./aes":147,"./authCipher":148,"./modes":160,"./streamCipher":163,"cipher-base":186,"evp_bytestokey":273,"inherits":317,"safe-buffer":1371}],151:[function(require,module,exports){
var MODES = require('./modes')
var AuthCipher = require('./authCipher')
var Buffer = require('safe-buffer').Buffer
@@ -30336,7 +22526,7 @@ function createCipher (suite, password) {
exports.createCipheriv = createCipheriv
exports.createCipher = createCipher
-},{"./aes":183,"./authCipher":184,"./modes":196,"./streamCipher":199,"cipher-base":223,"evp_bytestokey":371,"inherits":453,"safe-buffer":1593}],188:[function(require,module,exports){
+},{"./aes":147,"./authCipher":148,"./modes":160,"./streamCipher":163,"cipher-base":186,"evp_bytestokey":273,"inherits":317,"safe-buffer":1371}],152:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var ZEROES = Buffer.alloc(16, 0)
@@ -30427,7 +22617,7 @@ GHASH.prototype.final = function (abl, bl) {
module.exports = GHASH
-},{"safe-buffer":1593}],189:[function(require,module,exports){
+},{"safe-buffer":1371}],153:[function(require,module,exports){
function incr32 (iv) {
var len = iv.length
var item
@@ -30444,7 +22634,7 @@ function incr32 (iv) {
}
module.exports = incr32
-},{}],190:[function(require,module,exports){
+},{}],154:[function(require,module,exports){
var xor = require('buffer-xor')
exports.encrypt = function (self, block) {
@@ -30463,7 +22653,7 @@ exports.decrypt = function (self, block) {
return xor(out, pad)
}
-},{"buffer-xor":216}],191:[function(require,module,exports){
+},{"buffer-xor":180}],155:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var xor = require('buffer-xor')
@@ -30498,7 +22688,7 @@ exports.encrypt = function (self, data, decrypt) {
return out
}
-},{"buffer-xor":216,"safe-buffer":1593}],192:[function(require,module,exports){
+},{"buffer-xor":180,"safe-buffer":1371}],156:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
function encryptByte (self, byteParam, decrypt) {
@@ -30542,7 +22732,7 @@ exports.encrypt = function (self, chunk, decrypt) {
return out
}
-},{"safe-buffer":1593}],193:[function(require,module,exports){
+},{"safe-buffer":1371}],157:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
function encryptByte (self, byteParam, decrypt) {
@@ -30569,7 +22759,7 @@ exports.encrypt = function (self, chunk, decrypt) {
return out
}
-},{"safe-buffer":1593}],194:[function(require,module,exports){
+},{"safe-buffer":1371}],158:[function(require,module,exports){
var xor = require('buffer-xor')
var Buffer = require('safe-buffer').Buffer
var incr32 = require('../incr32')
@@ -30601,7 +22791,7 @@ exports.encrypt = function (self, chunk) {
return xor(chunk, pad)
}
-},{"../incr32":189,"buffer-xor":216,"safe-buffer":1593}],195:[function(require,module,exports){
+},{"../incr32":153,"buffer-xor":180,"safe-buffer":1371}],159:[function(require,module,exports){
exports.encrypt = function (self, block) {
return self._cipher.encryptBlock(block)
}
@@ -30610,7 +22800,7 @@ exports.decrypt = function (self, block) {
return self._cipher.decryptBlock(block)
}
-},{}],196:[function(require,module,exports){
+},{}],160:[function(require,module,exports){
var modeModules = {
ECB: require('./ecb'),
CBC: require('./cbc'),
@@ -30630,7 +22820,7 @@ for (var key in modes) {
module.exports = modes
-},{"./cbc":190,"./cfb":191,"./cfb1":192,"./cfb8":193,"./ctr":194,"./ecb":195,"./list.json":197,"./ofb":198}],197:[function(require,module,exports){
+},{"./cbc":154,"./cfb":155,"./cfb1":156,"./cfb8":157,"./ctr":158,"./ecb":159,"./list.json":161,"./ofb":162}],161:[function(require,module,exports){
module.exports={
"aes-128-ecb": {
"cipher": "AES",
@@ -30823,7 +23013,7 @@ module.exports={
}
}
-},{}],198:[function(require,module,exports){
+},{}],162:[function(require,module,exports){
(function (Buffer){
var xor = require('buffer-xor')
@@ -30843,7 +23033,7 @@ exports.encrypt = function (self, chunk) {
}
}).call(this,require("buffer").Buffer)
-},{"buffer":217,"buffer-xor":216}],199:[function(require,module,exports){
+},{"buffer":181,"buffer-xor":180}],163:[function(require,module,exports){
var aes = require('./aes')
var Buffer = require('safe-buffer').Buffer
var Transform = require('cipher-base')
@@ -30872,7 +23062,7 @@ StreamCipher.prototype._final = function () {
module.exports = StreamCipher
-},{"./aes":183,"cipher-base":223,"inherits":453,"safe-buffer":1593}],200:[function(require,module,exports){
+},{"./aes":147,"cipher-base":186,"inherits":317,"safe-buffer":1371}],164:[function(require,module,exports){
var DES = require('browserify-des')
var aes = require('browserify-aes/browser')
var aesModes = require('browserify-aes/modes')
@@ -30941,7 +23131,7 @@ exports.createDecipher = exports.Decipher = createDecipher
exports.createDecipheriv = exports.Decipheriv = createDecipheriv
exports.listCiphers = exports.getCiphers = getCiphers
-},{"browserify-aes/browser":185,"browserify-aes/modes":196,"browserify-des":201,"browserify-des/modes":202,"evp_bytestokey":371}],201:[function(require,module,exports){
+},{"browserify-aes/browser":149,"browserify-aes/modes":160,"browserify-des":165,"browserify-des/modes":166,"evp_bytestokey":273}],165:[function(require,module,exports){
var CipherBase = require('cipher-base')
var des = require('des.js')
var inherits = require('inherits')
@@ -30993,7 +23183,7 @@ DES.prototype._final = function () {
return Buffer.from(this._des.final())
}
-},{"cipher-base":223,"des.js":265,"inherits":453,"safe-buffer":1593}],202:[function(require,module,exports){
+},{"cipher-base":186,"des.js":222,"inherits":317,"safe-buffer":1371}],166:[function(require,module,exports){
exports['des-ecb'] = {
key: 8,
iv: 0
@@ -31019,7 +23209,7 @@ exports['des-ede'] = {
iv: 0
}
-},{}],203:[function(require,module,exports){
+},{}],167:[function(require,module,exports){
(function (Buffer){
var bn = require('bn.js');
var randomBytes = require('randombytes');
@@ -31063,10 +23253,10 @@ function getr(priv) {
}
}).call(this,require("buffer").Buffer)
-},{"bn.js":171,"buffer":217,"randombytes":1552}],204:[function(require,module,exports){
+},{"bn.js":135,"buffer":181,"randombytes":1366}],168:[function(require,module,exports){
module.exports = require('./browser/algorithms.json')
-},{"./browser/algorithms.json":205}],205:[function(require,module,exports){
+},{"./browser/algorithms.json":169}],169:[function(require,module,exports){
module.exports={
"sha224WithRSAEncryption": {
"sign": "rsa",
@@ -31220,7 +23410,7 @@ module.exports={
}
}
-},{}],206:[function(require,module,exports){
+},{}],170:[function(require,module,exports){
module.exports={
"1.3.132.0.10": "secp256k1",
"1.3.132.0.33": "p224",
@@ -31230,7 +23420,7 @@ module.exports={
"1.3.132.0.35": "p521"
}
-},{}],207:[function(require,module,exports){
+},{}],171:[function(require,module,exports){
(function (Buffer){
var createHash = require('create-hash')
var stream = require('stream')
@@ -31325,7 +23515,7 @@ module.exports = {
}
}).call(this,require("buffer").Buffer)
-},{"./algorithms.json":205,"./sign":208,"./verify":209,"buffer":217,"create-hash":232,"inherits":453,"stream":1715}],208:[function(require,module,exports){
+},{"./algorithms.json":169,"./sign":172,"./verify":173,"buffer":181,"create-hash":193,"inherits":317,"stream":1459}],172:[function(require,module,exports){
(function (Buffer){
// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var createHmac = require('create-hmac')
@@ -31474,7 +23664,7 @@ module.exports.getKey = getKey
module.exports.makeKey = makeKey
}).call(this,require("buffer").Buffer)
-},{"./curves.json":206,"bn.js":171,"browserify-rsa":203,"buffer":217,"create-hmac":234,"elliptic":282,"parse-asn1":1421}],209:[function(require,module,exports){
+},{"./curves.json":170,"bn.js":135,"browserify-rsa":167,"buffer":181,"create-hmac":195,"elliptic":236,"parse-asn1":1243}],173:[function(require,module,exports){
(function (Buffer){
// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
var BN = require('bn.js')
@@ -31561,1043 +23751,558 @@ function checkValue (b, q) {
module.exports = verify
}).call(this,require("buffer").Buffer)
-},{"./curves.json":206,"bn.js":171,"buffer":217,"elliptic":282,"parse-asn1":1421}],210:[function(require,module,exports){
-(function (process,Buffer){
-'use strict';
-/* eslint camelcase: "off" */
-
-var assert = require('assert');
-
-var Zstream = require('pako/lib/zlib/zstream');
-var zlib_deflate = require('pako/lib/zlib/deflate.js');
-var zlib_inflate = require('pako/lib/zlib/inflate.js');
-var constants = require('pako/lib/zlib/constants');
-
-for (var key in constants) {
- exports[key] = constants[key];
-}
-
-// zlib modes
-exports.NONE = 0;
-exports.DEFLATE = 1;
-exports.INFLATE = 2;
-exports.GZIP = 3;
-exports.GUNZIP = 4;
-exports.DEFLATERAW = 5;
-exports.INFLATERAW = 6;
-exports.UNZIP = 7;
-
-var GZIP_HEADER_ID1 = 0x1f;
-var GZIP_HEADER_ID2 = 0x8b;
-
-/**
- * Emulate Node's zlib C++ layer for use by the JS layer in index.js
- */
-function Zlib(mode) {
- if (typeof mode !== 'number' || mode < exports.DEFLATE || mode > exports.UNZIP) {
- throw new TypeError('Bad argument');
- }
-
- this.dictionary = null;
- this.err = 0;
- this.flush = 0;
- this.init_done = false;
- this.level = 0;
- this.memLevel = 0;
- this.mode = mode;
- this.strategy = 0;
- this.windowBits = 0;
- this.write_in_progress = false;
- this.pending_close = false;
- this.gzip_id_bytes_read = 0;
-}
-
-Zlib.prototype.close = function () {
- if (this.write_in_progress) {
- this.pending_close = true;
- return;
- }
-
- this.pending_close = false;
-
- assert(this.init_done, 'close before init');
- assert(this.mode <= exports.UNZIP);
-
- if (this.mode === exports.DEFLATE || this.mode === exports.GZIP || this.mode === exports.DEFLATERAW) {
- zlib_deflate.deflateEnd(this.strm);
- } else if (this.mode === exports.INFLATE || this.mode === exports.GUNZIP || this.mode === exports.INFLATERAW || this.mode === exports.UNZIP) {
- zlib_inflate.inflateEnd(this.strm);
- }
-
- this.mode = exports.NONE;
-
- this.dictionary = null;
-};
-
-Zlib.prototype.write = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(true, flush, input, in_off, in_len, out, out_off, out_len);
-};
-
-Zlib.prototype.writeSync = function (flush, input, in_off, in_len, out, out_off, out_len) {
- return this._write(false, flush, input, in_off, in_len, out, out_off, out_len);
-};
-
-Zlib.prototype._write = function (async, flush, input, in_off, in_len, out, out_off, out_len) {
- assert.equal(arguments.length, 8);
-
- assert(this.init_done, 'write before init');
- assert(this.mode !== exports.NONE, 'already finalized');
- assert.equal(false, this.write_in_progress, 'write already in progress');
- assert.equal(false, this.pending_close, 'close is pending');
-
- this.write_in_progress = true;
-
- assert.equal(false, flush === undefined, 'must provide flush value');
-
- this.write_in_progress = true;
-
- if (flush !== exports.Z_NO_FLUSH && flush !== exports.Z_PARTIAL_FLUSH && flush !== exports.Z_SYNC_FLUSH && flush !== exports.Z_FULL_FLUSH && flush !== exports.Z_FINISH && flush !== exports.Z_BLOCK) {
- throw new Error('Invalid flush value');
- }
-
- if (input == null) {
- input = Buffer.alloc(0);
- in_len = 0;
- in_off = 0;
- }
-
- this.strm.avail_in = in_len;
- this.strm.input = input;
- this.strm.next_in = in_off;
- this.strm.avail_out = out_len;
- this.strm.output = out;
- this.strm.next_out = out_off;
- this.flush = flush;
-
- if (!async) {
- // sync version
- this._process();
-
- if (this._checkError()) {
- return this._afterSync();
- }
- return;
- }
-
- // async version
- var self = this;
- process.nextTick(function () {
- self._process();
- self._after();
- });
-
- return this;
-};
-
-Zlib.prototype._afterSync = function () {
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
-
- this.write_in_progress = false;
-
- return [avail_in, avail_out];
-};
-
-Zlib.prototype._process = function () {
- var next_expected_header_byte = null;
-
- // If the avail_out is left at 0, then it means that it ran out
- // of room. If there was avail_out left over, then it means
- // that all of the input was consumed.
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflate(this.strm, this.flush);
- break;
- case exports.UNZIP:
- if (this.strm.avail_in > 0) {
- next_expected_header_byte = this.strm.next_in;
- }
-
- switch (this.gzip_id_bytes_read) {
- case 0:
- if (next_expected_header_byte === null) {
- break;
- }
-
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID1) {
- this.gzip_id_bytes_read = 1;
- next_expected_header_byte++;
-
- if (this.strm.avail_in === 1) {
- // The only available byte was already read.
- break;
- }
- } else {
- this.mode = exports.INFLATE;
- break;
- }
-
- // fallthrough
- case 1:
- if (next_expected_header_byte === null) {
- break;
- }
-
- if (this.strm.input[next_expected_header_byte] === GZIP_HEADER_ID2) {
- this.gzip_id_bytes_read = 2;
- this.mode = exports.GUNZIP;
- } else {
- // There is no actual difference between INFLATE and INFLATERAW
- // (after initialization).
- this.mode = exports.INFLATE;
- }
-
- break;
- default:
- throw new Error('invalid number of gzip magic number bytes read');
- }
-
- // fallthrough
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- this.err = zlib_inflate.inflate(this.strm, this.flush
-
- // If data was encoded with dictionary
- );if (this.err === exports.Z_NEED_DICT && this.dictionary) {
- // Load it
- this.err = zlib_inflate.inflateSetDictionary(this.strm, this.dictionary);
- if (this.err === exports.Z_OK) {
- // And try to decode again
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- } else if (this.err === exports.Z_DATA_ERROR) {
- // Both inflateSetDictionary() and inflate() return Z_DATA_ERROR.
- // Make it possible for After() to tell a bad dictionary from bad
- // input.
- this.err = exports.Z_NEED_DICT;
- }
- }
- while (this.strm.avail_in > 0 && this.mode === exports.GUNZIP && this.err === exports.Z_STREAM_END && this.strm.next_in[0] !== 0x00) {
- // Bytes remain in input buffer. Perhaps this is another compressed
- // member in the same archive, or just trailing garbage.
- // Trailing zero bytes are okay, though, since they are frequently
- // used for padding.
-
- this.reset();
- this.err = zlib_inflate.inflate(this.strm, this.flush);
- }
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
- }
-};
-
-Zlib.prototype._checkError = function () {
- // Acceptable error states depend on the type of zlib stream.
- switch (this.err) {
- case exports.Z_OK:
- case exports.Z_BUF_ERROR:
- if (this.strm.avail_out !== 0 && this.flush === exports.Z_FINISH) {
- this._error('unexpected end of file');
- return false;
- }
- break;
- case exports.Z_STREAM_END:
- // normal statuses, not fatal
- break;
- case exports.Z_NEED_DICT:
- if (this.dictionary == null) {
- this._error('Missing dictionary');
- } else {
- this._error('Bad dictionary');
- }
- return false;
- default:
- // something else.
- this._error('Zlib error');
- return false;
- }
-
- return true;
-};
-
-Zlib.prototype._after = function () {
- if (!this._checkError()) {
- return;
- }
-
- var avail_out = this.strm.avail_out;
- var avail_in = this.strm.avail_in;
-
- this.write_in_progress = false;
-
- // call the write() cb
- this.callback(avail_in, avail_out);
-
- if (this.pending_close) {
- this.close();
- }
-};
-
-Zlib.prototype._error = function (message) {
- if (this.strm.msg) {
- message = this.strm.msg;
- }
- this.onerror(message, this.err
-
- // no hope of rescue.
- );this.write_in_progress = false;
- if (this.pending_close) {
- this.close();
- }
-};
-
-Zlib.prototype.init = function (windowBits, level, memLevel, strategy, dictionary) {
- assert(arguments.length === 4 || arguments.length === 5, 'init(windowBits, level, memLevel, strategy, [dictionary])');
-
- assert(windowBits >= 8 && windowBits <= 15, 'invalid windowBits');
- assert(level >= -1 && level <= 9, 'invalid compression level');
-
- assert(memLevel >= 1 && memLevel <= 9, 'invalid memlevel');
-
- assert(strategy === exports.Z_FILTERED || strategy === exports.Z_HUFFMAN_ONLY || strategy === exports.Z_RLE || strategy === exports.Z_FIXED || strategy === exports.Z_DEFAULT_STRATEGY, 'invalid strategy');
-
- this._init(level, windowBits, memLevel, strategy, dictionary);
- this._setDictionary();
-};
-
-Zlib.prototype.params = function () {
- throw new Error('deflateParams Not supported');
-};
-
-Zlib.prototype.reset = function () {
- this._reset();
- this._setDictionary();
-};
-
-Zlib.prototype._init = function (level, windowBits, memLevel, strategy, dictionary) {
- this.level = level;
- this.windowBits = windowBits;
- this.memLevel = memLevel;
- this.strategy = strategy;
-
- this.flush = exports.Z_NO_FLUSH;
-
- this.err = exports.Z_OK;
-
- if (this.mode === exports.GZIP || this.mode === exports.GUNZIP) {
- this.windowBits += 16;
- }
-
- if (this.mode === exports.UNZIP) {
- this.windowBits += 32;
- }
-
- if (this.mode === exports.DEFLATERAW || this.mode === exports.INFLATERAW) {
- this.windowBits = -1 * this.windowBits;
- }
-
- this.strm = new Zstream();
-
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.GZIP:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateInit2(this.strm, this.level, exports.Z_DEFLATED, this.windowBits, this.memLevel, this.strategy);
- break;
- case exports.INFLATE:
- case exports.GUNZIP:
- case exports.INFLATERAW:
- case exports.UNZIP:
- this.err = zlib_inflate.inflateInit2(this.strm, this.windowBits);
- break;
- default:
- throw new Error('Unknown mode ' + this.mode);
- }
-
- if (this.err !== exports.Z_OK) {
- this._error('Init error');
- }
-
- this.dictionary = dictionary;
-
- this.write_in_progress = false;
- this.init_done = true;
-};
-
-Zlib.prototype._setDictionary = function () {
- if (this.dictionary == null) {
- return;
- }
-
- this.err = exports.Z_OK;
-
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- this.err = zlib_deflate.deflateSetDictionary(this.strm, this.dictionary);
- break;
- default:
- break;
- }
-
- if (this.err !== exports.Z_OK) {
- this._error('Failed to set dictionary');
- }
-};
-
-Zlib.prototype._reset = function () {
- this.err = exports.Z_OK;
-
- switch (this.mode) {
- case exports.DEFLATE:
- case exports.DEFLATERAW:
- case exports.GZIP:
- this.err = zlib_deflate.deflateReset(this.strm);
- break;
- case exports.INFLATE:
- case exports.INFLATERAW:
- case exports.GUNZIP:
- this.err = zlib_inflate.inflateReset(this.strm);
- break;
- default:
- break;
- }
-
- if (this.err !== exports.Z_OK) {
- this._error('Failed to reset stream');
- }
-};
-
-exports.Zlib = Zlib;
-}).call(this,require('_process'),require("buffer").Buffer)
-},{"_process":1438,"assert":78,"buffer":217,"pako/lib/zlib/constants":1408,"pako/lib/zlib/deflate.js":1410,"pako/lib/zlib/inflate.js":1412,"pako/lib/zlib/zstream":1416}],211:[function(require,module,exports){
-(function (process){
-'use strict';
-
-var Buffer = require('buffer').Buffer;
-var Transform = require('stream').Transform;
-var binding = require('./binding');
-var util = require('util');
-var assert = require('assert').ok;
-var kMaxLength = require('buffer').kMaxLength;
-var kRangeErrorMessage = 'Cannot create final Buffer. It would be larger ' + 'than 0x' + kMaxLength.toString(16) + ' bytes';
-
-// zlib doesn't provide these, so kludge them in following the same
-// const naming scheme zlib uses.
-binding.Z_MIN_WINDOWBITS = 8;
-binding.Z_MAX_WINDOWBITS = 15;
-binding.Z_DEFAULT_WINDOWBITS = 15;
-
-// fewer than 64 bytes per chunk is stupid.
-// technically it could work with as few as 8, but even 64 bytes
-// is absurdly low. Usually a MB or more is best.
-binding.Z_MIN_CHUNK = 64;
-binding.Z_MAX_CHUNK = Infinity;
-binding.Z_DEFAULT_CHUNK = 16 * 1024;
-
-binding.Z_MIN_MEMLEVEL = 1;
-binding.Z_MAX_MEMLEVEL = 9;
-binding.Z_DEFAULT_MEMLEVEL = 8;
-
-binding.Z_MIN_LEVEL = -1;
-binding.Z_MAX_LEVEL = 9;
-binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION;
-
-// expose all the zlib constants
-var bkeys = Object.keys(binding);
-for (var bk = 0; bk < bkeys.length; bk++) {
- var bkey = bkeys[bk];
- if (bkey.match(/^Z/)) {
- Object.defineProperty(exports, bkey, {
- enumerable: true, value: binding[bkey], writable: false
- });
- }
-}
-
-// translation table for return codes.
-var codes = {
- Z_OK: binding.Z_OK,
- Z_STREAM_END: binding.Z_STREAM_END,
- Z_NEED_DICT: binding.Z_NEED_DICT,
- Z_ERRNO: binding.Z_ERRNO,
- Z_STREAM_ERROR: binding.Z_STREAM_ERROR,
- Z_DATA_ERROR: binding.Z_DATA_ERROR,
- Z_MEM_ERROR: binding.Z_MEM_ERROR,
- Z_BUF_ERROR: binding.Z_BUF_ERROR,
- Z_VERSION_ERROR: binding.Z_VERSION_ERROR
-};
-
-var ckeys = Object.keys(codes);
-for (var ck = 0; ck < ckeys.length; ck++) {
- var ckey = ckeys[ck];
- codes[codes[ckey]] = ckey;
-}
-
-Object.defineProperty(exports, 'codes', {
- enumerable: true, value: Object.freeze(codes), writable: false
-});
-
-exports.Deflate = Deflate;
-exports.Inflate = Inflate;
-exports.Gzip = Gzip;
-exports.Gunzip = Gunzip;
-exports.DeflateRaw = DeflateRaw;
-exports.InflateRaw = InflateRaw;
-exports.Unzip = Unzip;
-
-exports.createDeflate = function (o) {
- return new Deflate(o);
-};
-
-exports.createInflate = function (o) {
- return new Inflate(o);
-};
-
-exports.createDeflateRaw = function (o) {
- return new DeflateRaw(o);
-};
-
-exports.createInflateRaw = function (o) {
- return new InflateRaw(o);
-};
-
-exports.createGzip = function (o) {
- return new Gzip(o);
-};
-
-exports.createGunzip = function (o) {
- return new Gunzip(o);
-};
-
-exports.createUnzip = function (o) {
- return new Unzip(o);
-};
-
-// Convenience methods.
-// compress/decompress a string or buffer in one step.
-exports.deflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Deflate(opts), buffer, callback);
-};
-
-exports.deflateSync = function (buffer, opts) {
- return zlibBufferSync(new Deflate(opts), buffer);
-};
-
-exports.gzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Gzip(opts), buffer, callback);
-};
-
-exports.gzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gzip(opts), buffer);
-};
-
-exports.deflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new DeflateRaw(opts), buffer, callback);
-};
-
-exports.deflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new DeflateRaw(opts), buffer);
-};
-
-exports.unzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Unzip(opts), buffer, callback);
-};
-
-exports.unzipSync = function (buffer, opts) {
- return zlibBufferSync(new Unzip(opts), buffer);
-};
-
-exports.inflate = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Inflate(opts), buffer, callback);
-};
-
-exports.inflateSync = function (buffer, opts) {
- return zlibBufferSync(new Inflate(opts), buffer);
-};
-
-exports.gunzip = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new Gunzip(opts), buffer, callback);
-};
-
-exports.gunzipSync = function (buffer, opts) {
- return zlibBufferSync(new Gunzip(opts), buffer);
-};
-
-exports.inflateRaw = function (buffer, opts, callback) {
- if (typeof opts === 'function') {
- callback = opts;
- opts = {};
- }
- return zlibBuffer(new InflateRaw(opts), buffer, callback);
-};
-
-exports.inflateRawSync = function (buffer, opts) {
- return zlibBufferSync(new InflateRaw(opts), buffer);
-};
-
-function zlibBuffer(engine, buffer, callback) {
- var buffers = [];
- var nread = 0;
-
- engine.on('error', onError);
- engine.on('end', onEnd);
-
- engine.end(buffer);
- flow();
-
- function flow() {
- var chunk;
- while (null !== (chunk = engine.read())) {
- buffers.push(chunk);
- nread += chunk.length;
- }
- engine.once('readable', flow);
- }
-
- function onError(err) {
- engine.removeListener('end', onEnd);
- engine.removeListener('readable', flow);
- callback(err);
- }
-
- function onEnd() {
- var buf;
- var err = null;
-
- if (nread >= kMaxLength) {
- err = new RangeError(kRangeErrorMessage);
- } else {
- buf = Buffer.concat(buffers, nread);
- }
-
- buffers = [];
- engine.close();
- callback(err, buf);
- }
-}
-
-function zlibBufferSync(engine, buffer) {
- if (typeof buffer === 'string') buffer = Buffer.from(buffer);
-
- if (!Buffer.isBuffer(buffer)) throw new TypeError('Not a string or buffer');
-
- var flushFlag = engine._finishFlushFlag;
-
- return engine._processChunk(buffer, flushFlag);
-}
-
-// generic zlib
-// minimal 2-byte header
-function Deflate(opts) {
- if (!(this instanceof Deflate)) return new Deflate(opts);
- Zlib.call(this, opts, binding.DEFLATE);
-}
-
-function Inflate(opts) {
- if (!(this instanceof Inflate)) return new Inflate(opts);
- Zlib.call(this, opts, binding.INFLATE);
-}
-
-// gzip - bigger header, same deflate compression
-function Gzip(opts) {
- if (!(this instanceof Gzip)) return new Gzip(opts);
- Zlib.call(this, opts, binding.GZIP);
-}
-
-function Gunzip(opts) {
- if (!(this instanceof Gunzip)) return new Gunzip(opts);
- Zlib.call(this, opts, binding.GUNZIP);
-}
-
-// raw - no header
-function DeflateRaw(opts) {
- if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts);
- Zlib.call(this, opts, binding.DEFLATERAW);
-}
-
-function InflateRaw(opts) {
- if (!(this instanceof InflateRaw)) return new InflateRaw(opts);
- Zlib.call(this, opts, binding.INFLATERAW);
-}
-
-// auto-detect header.
-function Unzip(opts) {
- if (!(this instanceof Unzip)) return new Unzip(opts);
- Zlib.call(this, opts, binding.UNZIP);
-}
-
-function isValidFlushFlag(flag) {
- return flag === binding.Z_NO_FLUSH || flag === binding.Z_PARTIAL_FLUSH || flag === binding.Z_SYNC_FLUSH || flag === binding.Z_FULL_FLUSH || flag === binding.Z_FINISH || flag === binding.Z_BLOCK;
-}
-
-// the Zlib class they all inherit from
-// This thing manages the queue of requests, and returns
-// true or false if there is anything in the queue when
-// you call the .write() method.
-
-function Zlib(opts, mode) {
- var _this = this;
-
- this._opts = opts = opts || {};
- this._chunkSize = opts.chunkSize || exports.Z_DEFAULT_CHUNK;
-
- Transform.call(this, opts);
-
- if (opts.flush && !isValidFlushFlag(opts.flush)) {
- throw new Error('Invalid flush flag: ' + opts.flush);
- }
- if (opts.finishFlush && !isValidFlushFlag(opts.finishFlush)) {
- throw new Error('Invalid flush flag: ' + opts.finishFlush);
- }
-
- this._flushFlag = opts.flush || binding.Z_NO_FLUSH;
- this._finishFlushFlag = typeof opts.finishFlush !== 'undefined' ? opts.finishFlush : binding.Z_FINISH;
-
- if (opts.chunkSize) {
- if (opts.chunkSize < exports.Z_MIN_CHUNK || opts.chunkSize > exports.Z_MAX_CHUNK) {
- throw new Error('Invalid chunk size: ' + opts.chunkSize);
- }
- }
-
- if (opts.windowBits) {
- if (opts.windowBits < exports.Z_MIN_WINDOWBITS || opts.windowBits > exports.Z_MAX_WINDOWBITS) {
- throw new Error('Invalid windowBits: ' + opts.windowBits);
- }
- }
-
- if (opts.level) {
- if (opts.level < exports.Z_MIN_LEVEL || opts.level > exports.Z_MAX_LEVEL) {
- throw new Error('Invalid compression level: ' + opts.level);
- }
- }
-
- if (opts.memLevel) {
- if (opts.memLevel < exports.Z_MIN_MEMLEVEL || opts.memLevel > exports.Z_MAX_MEMLEVEL) {
- throw new Error('Invalid memLevel: ' + opts.memLevel);
- }
- }
-
- if (opts.strategy) {
- if (opts.strategy != exports.Z_FILTERED && opts.strategy != exports.Z_HUFFMAN_ONLY && opts.strategy != exports.Z_RLE && opts.strategy != exports.Z_FIXED && opts.strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new Error('Invalid strategy: ' + opts.strategy);
- }
- }
-
- if (opts.dictionary) {
- if (!Buffer.isBuffer(opts.dictionary)) {
- throw new Error('Invalid dictionary: it should be a Buffer instance');
- }
- }
-
- this._handle = new binding.Zlib(mode);
-
- var self = this;
- this._hadError = false;
- this._handle.onerror = function (message, errno) {
- // there is no way to cleanly recover.
- // continuing only obscures problems.
- _close(self);
- self._hadError = true;
-
- var error = new Error(message);
- error.errno = errno;
- error.code = exports.codes[errno];
- self.emit('error', error);
- };
-
- var level = exports.Z_DEFAULT_COMPRESSION;
- if (typeof opts.level === 'number') level = opts.level;
-
- var strategy = exports.Z_DEFAULT_STRATEGY;
- if (typeof opts.strategy === 'number') strategy = opts.strategy;
-
- this._handle.init(opts.windowBits || exports.Z_DEFAULT_WINDOWBITS, level, opts.memLevel || exports.Z_DEFAULT_MEMLEVEL, strategy, opts.dictionary);
-
- this._buffer = Buffer.allocUnsafe(this._chunkSize);
- this._offset = 0;
- this._level = level;
- this._strategy = strategy;
-
- this.once('end', this.close);
-
- Object.defineProperty(this, '_closed', {
- get: function () {
- return !_this._handle;
- },
- configurable: true,
- enumerable: true
- });
-}
-
-util.inherits(Zlib, Transform);
-
-Zlib.prototype.params = function (level, strategy, callback) {
- if (level < exports.Z_MIN_LEVEL || level > exports.Z_MAX_LEVEL) {
- throw new RangeError('Invalid compression level: ' + level);
- }
- if (strategy != exports.Z_FILTERED && strategy != exports.Z_HUFFMAN_ONLY && strategy != exports.Z_RLE && strategy != exports.Z_FIXED && strategy != exports.Z_DEFAULT_STRATEGY) {
- throw new TypeError('Invalid strategy: ' + strategy);
- }
-
- if (this._level !== level || this._strategy !== strategy) {
- var self = this;
- this.flush(binding.Z_SYNC_FLUSH, function () {
- assert(self._handle, 'zlib binding closed');
- self._handle.params(level, strategy);
- if (!self._hadError) {
- self._level = level;
- self._strategy = strategy;
- if (callback) callback();
- }
- });
- } else {
- process.nextTick(callback);
- }
-};
-
-Zlib.prototype.reset = function () {
- assert(this._handle, 'zlib binding closed');
- return this._handle.reset();
-};
-
-// This is the _flush function called by the transform class,
-// internally, when the last chunk has been written.
-Zlib.prototype._flush = function (callback) {
- this._transform(Buffer.alloc(0), '', callback);
-};
-
-Zlib.prototype.flush = function (kind, callback) {
- var _this2 = this;
-
- var ws = this._writableState;
-
- if (typeof kind === 'function' || kind === undefined && !callback) {
- callback = kind;
- kind = binding.Z_FULL_FLUSH;
- }
-
- if (ws.ended) {
- if (callback) process.nextTick(callback);
- } else if (ws.ending) {
- if (callback) this.once('end', callback);
- } else if (ws.needDrain) {
- if (callback) {
- this.once('drain', function () {
- return _this2.flush(kind, callback);
- });
- }
- } else {
- this._flushFlag = kind;
- this.write(Buffer.alloc(0), '', callback);
- }
-};
-
-Zlib.prototype.close = function (callback) {
- _close(this, callback);
- process.nextTick(emitCloseNT, this);
-};
-
-function _close(engine, callback) {
- if (callback) process.nextTick(callback);
-
- // Caller may invoke .close after a zlib error (which will null _handle).
- if (!engine._handle) return;
-
- engine._handle.close();
- engine._handle = null;
-}
-
-function emitCloseNT(self) {
- self.emit('close');
-}
-
-Zlib.prototype._transform = function (chunk, encoding, cb) {
- var flushFlag;
- var ws = this._writableState;
- var ending = ws.ending || ws.ended;
- var last = ending && (!chunk || ws.length === chunk.length);
-
- if (chunk !== null && !Buffer.isBuffer(chunk)) return cb(new Error('invalid input'));
-
- if (!this._handle) return cb(new Error('zlib binding closed'));
-
- // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag
- // (or whatever flag was provided using opts.finishFlush).
- // If it's explicitly flushing at some other time, then we use
- // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression
- // goodness.
- if (last) flushFlag = this._finishFlushFlag;else {
- flushFlag = this._flushFlag;
- // once we've flushed the last of the queue, stop flushing and
- // go back to the normal behavior.
- if (chunk.length >= ws.length) {
- this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH;
- }
- }
-
- this._processChunk(chunk, flushFlag, cb);
-};
-
-Zlib.prototype._processChunk = function (chunk, flushFlag, cb) {
- var availInBefore = chunk && chunk.length;
- var availOutBefore = this._chunkSize - this._offset;
- var inOff = 0;
-
- var self = this;
-
- var async = typeof cb === 'function';
-
- if (!async) {
- var buffers = [];
- var nread = 0;
-
- var error;
- this.on('error', function (er) {
- error = er;
- });
-
- assert(this._handle, 'zlib binding closed');
- do {
- var res = this._handle.writeSync(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
- } while (!this._hadError && callback(res[0], res[1]));
-
- if (this._hadError) {
- throw error;
- }
-
- if (nread >= kMaxLength) {
- _close(this);
- throw new RangeError(kRangeErrorMessage);
- }
-
- var buf = Buffer.concat(buffers, nread);
- _close(this);
-
- return buf;
- }
-
- assert(this._handle, 'zlib binding closed');
- var req = this._handle.write(flushFlag, chunk, // in
- inOff, // in_off
- availInBefore, // in_len
- this._buffer, // out
- this._offset, //out_off
- availOutBefore); // out_len
-
- req.buffer = chunk;
- req.callback = callback;
-
- function callback(availInAfter, availOutAfter) {
- // When the callback is used in an async write, the callback's
- // context is the `req` object that was created. The req object
- // is === this._handle, and that's why it's important to null
- // out the values after they are done being used. `this._handle`
- // can stay in memory longer than the callback and buffer are needed.
- if (this) {
- this.buffer = null;
- this.callback = null;
- }
-
- if (self._hadError) return;
-
- var have = availOutBefore - availOutAfter;
- assert(have >= 0, 'have should not go down');
-
- if (have > 0) {
- var out = self._buffer.slice(self._offset, self._offset + have);
- self._offset += have;
- // serve some output to the consumer.
- if (async) {
- self.push(out);
- } else {
- buffers.push(out);
- nread += out.length;
- }
- }
-
- // exhausted the output buffer, or used all the input create a new one.
- if (availOutAfter === 0 || self._offset >= self._chunkSize) {
- availOutBefore = self._chunkSize;
- self._offset = 0;
- self._buffer = Buffer.allocUnsafe(self._chunkSize);
- }
-
- if (availOutAfter === 0) {
- // Not actually done. Need to reprocess.
- // Also, update the availInBefore to the availInAfter value,
- // so that if we have to hit it a third (fourth, etc.) time,
- // it'll have the correct byte counts.
- inOff += availInBefore - availInAfter;
- availInBefore = availInAfter;
-
- if (!async) return true;
-
- var newReq = self._handle.write(flushFlag, chunk, inOff, availInBefore, self._buffer, self._offset, self._chunkSize);
- newReq.callback = callback; // this same function
- newReq.buffer = chunk;
- return;
- }
-
- if (!async) return false;
-
- // finished with the chunk.
- cb();
- }
-};
-
-util.inherits(Deflate, Zlib);
-util.inherits(Inflate, Zlib);
-util.inherits(Gzip, Zlib);
-util.inherits(Gunzip, Zlib);
-util.inherits(DeflateRaw, Zlib);
-util.inherits(InflateRaw, Zlib);
-util.inherits(Unzip, Zlib);
-}).call(this,require('_process'))
-},{"./binding":210,"_process":1438,"assert":78,"buffer":217,"stream":1715,"util":1776}],212:[function(require,module,exports){
-arguments[4][182][0].apply(exports,arguments)
-},{"dup":182}],213:[function(require,module,exports){
+},{"./curves.json":170,"bn.js":135,"buffer":181,"elliptic":236,"parse-asn1":1243}],174:[function(require,module,exports){
+(function (global){
+/*! https://mths.be/punycode v1.4.1 by @mathias */
+;(function(root) {
+
+ /** Detect free variables */
+ var freeExports = typeof exports == 'object' && exports &&
+ !exports.nodeType && exports;
+ var freeModule = typeof module == 'object' && module &&
+ !module.nodeType && module;
+ var freeGlobal = typeof global == 'object' && global;
+ if (
+ freeGlobal.global === freeGlobal ||
+ freeGlobal.window === freeGlobal ||
+ freeGlobal.self === freeGlobal
+ ) {
+ root = freeGlobal;
+ }
+
+ /**
+ * The `punycode` object.
+ * @name punycode
+ * @type Object
+ */
+ var punycode,
+
+ /** Highest positive signed 32-bit float value */
+ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
+
+ /** Bootstring parameters */
+ base = 36,
+ tMin = 1,
+ tMax = 26,
+ skew = 38,
+ damp = 700,
+ initialBias = 72,
+ initialN = 128, // 0x80
+ delimiter = '-', // '\x2D'
+
+ /** Regular expressions */
+ regexPunycode = /^xn--/,
+ regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
+ regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
+
+ /** Error messages */
+ errors = {
+ 'overflow': 'Overflow: input needs wider integers to process',
+ 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
+ 'invalid-input': 'Invalid input'
+ },
+
+ /** Convenience shortcuts */
+ baseMinusTMin = base - tMin,
+ floor = Math.floor,
+ stringFromCharCode = String.fromCharCode,
+
+ /** Temporary variable */
+ key;
+
+ /*--------------------------------------------------------------------------*/
+
+ /**
+ * A generic error utility function.
+ * @private
+ * @param {String} type The error type.
+ * @returns {Error} Throws a `RangeError` with the applicable error message.
+ */
+ function error(type) {
+ throw new RangeError(errors[type]);
+ }
+
+ /**
+ * A generic `Array#map` utility function.
+ * @private
+ * @param {Array} array The array to iterate over.
+ * @param {Function} callback The function that gets called for every array
+ * item.
+ * @returns {Array} A new array of values returned by the callback function.
+ */
+ function map(array, fn) {
+ var length = array.length;
+ var result = [];
+ while (length--) {
+ result[length] = fn(array[length]);
+ }
+ return result;
+ }
+
+ /**
+ * A simple `Array#map`-like wrapper to work with domain name strings or email
+ * addresses.
+ * @private
+ * @param {String} domain The domain name or email address.
+ * @param {Function} callback The function that gets called for every
+ * character.
+ * @returns {Array} A new string of characters returned by the callback
+ * function.
+ */
+ function mapDomain(string, fn) {
+ var parts = string.split('@');
+ var result = '';
+ if (parts.length > 1) {
+ // In email addresses, only the domain name should be punycoded. Leave
+ // the local part (i.e. everything up to `@`) intact.
+ result = parts[0] + '@';
+ string = parts[1];
+ }
+ // Avoid `split(regex)` for IE8 compatibility. See #17.
+ string = string.replace(regexSeparators, '\x2E');
+ var labels = string.split('.');
+ var encoded = map(labels, fn).join('.');
+ return result + encoded;
+ }
+
+ /**
+ * Creates an array containing the numeric code points of each Unicode
+ * character in the string. While JavaScript uses UCS-2 internally,
+ * this function will convert a pair of surrogate halves (each of which
+ * UCS-2 exposes as separate characters) into a single code point,
+ * matching UTF-16.
+ * @see `punycode.ucs2.encode`
+ * @see
+ * @memberOf punycode.ucs2
+ * @name decode
+ * @param {String} string The Unicode input string (UCS-2).
+ * @returns {Array} The new array of code points.
+ */
+ function ucs2decode(string) {
+ var output = [],
+ counter = 0,
+ length = string.length,
+ value,
+ extra;
+ while (counter < length) {
+ value = string.charCodeAt(counter++);
+ if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
+ // high surrogate, and there is a next character
+ extra = string.charCodeAt(counter++);
+ if ((extra & 0xFC00) == 0xDC00) { // low surrogate
+ output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
+ } else {
+ // unmatched surrogate; only append this code unit, in case the next
+ // code unit is the high surrogate of a surrogate pair
+ output.push(value);
+ counter--;
+ }
+ } else {
+ output.push(value);
+ }
+ }
+ return output;
+ }
+
+ /**
+ * Creates a string based on an array of numeric code points.
+ * @see `punycode.ucs2.decode`
+ * @memberOf punycode.ucs2
+ * @name encode
+ * @param {Array} codePoints The array of numeric code points.
+ * @returns {String} The new Unicode string (UCS-2).
+ */
+ function ucs2encode(array) {
+ return map(array, function(value) {
+ var output = '';
+ if (value > 0xFFFF) {
+ value -= 0x10000;
+ output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
+ value = 0xDC00 | value & 0x3FF;
+ }
+ output += stringFromCharCode(value);
+ return output;
+ }).join('');
+ }
+
+ /**
+ * Converts a basic code point into a digit/integer.
+ * @see `digitToBasic()`
+ * @private
+ * @param {Number} codePoint The basic numeric code point value.
+ * @returns {Number} The numeric value of a basic code point (for use in
+ * representing integers) in the range `0` to `base - 1`, or `base` if
+ * the code point does not represent a value.
+ */
+ function basicToDigit(codePoint) {
+ if (codePoint - 48 < 10) {
+ return codePoint - 22;
+ }
+ if (codePoint - 65 < 26) {
+ return codePoint - 65;
+ }
+ if (codePoint - 97 < 26) {
+ return codePoint - 97;
+ }
+ return base;
+ }
+
+ /**
+ * Converts a digit/integer into a basic code point.
+ * @see `basicToDigit()`
+ * @private
+ * @param {Number} digit The numeric value of a basic code point.
+ * @returns {Number} The basic code point whose value (when used for
+ * representing integers) is `digit`, which needs to be in the range
+ * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
+ * used; else, the lowercase form is used. The behavior is undefined
+ * if `flag` is non-zero and `digit` has no uppercase form.
+ */
+ function digitToBasic(digit, flag) {
+ // 0..25 map to ASCII a..z or A..Z
+ // 26..35 map to ASCII 0..9
+ return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
+ }
+
+ /**
+ * Bias adaptation function as per section 3.4 of RFC 3492.
+ * https://tools.ietf.org/html/rfc3492#section-3.4
+ * @private
+ */
+ function adapt(delta, numPoints, firstTime) {
+ var k = 0;
+ delta = firstTime ? floor(delta / damp) : delta >> 1;
+ delta += floor(delta / numPoints);
+ for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
+ delta = floor(delta / baseMinusTMin);
+ }
+ return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
+ }
+
+ /**
+ * Converts a Punycode string of ASCII-only symbols to a string of Unicode
+ * symbols.
+ * @memberOf punycode
+ * @param {String} input The Punycode string of ASCII-only symbols.
+ * @returns {String} The resulting string of Unicode symbols.
+ */
+ function decode(input) {
+ // Don't use UCS-2
+ var output = [],
+ inputLength = input.length,
+ out,
+ i = 0,
+ n = initialN,
+ bias = initialBias,
+ basic,
+ j,
+ index,
+ oldi,
+ w,
+ k,
+ digit,
+ t,
+ /** Cached calculation results */
+ baseMinusT;
+
+ // Handle the basic code points: let `basic` be the number of input code
+ // points before the last delimiter, or `0` if there is none, then copy
+ // the first basic code points to the output.
+
+ basic = input.lastIndexOf(delimiter);
+ if (basic < 0) {
+ basic = 0;
+ }
+
+ for (j = 0; j < basic; ++j) {
+ // if it's not a basic code point
+ if (input.charCodeAt(j) >= 0x80) {
+ error('not-basic');
+ }
+ output.push(input.charCodeAt(j));
+ }
+
+ // Main decoding loop: start just after the last delimiter if any basic code
+ // points were copied; start at the beginning otherwise.
+
+ for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
+
+ // `index` is the index of the next character to be consumed.
+ // Decode a generalized variable-length integer into `delta`,
+ // which gets added to `i`. The overflow checking is easier
+ // if we increase `i` as we go, then subtract off its starting
+ // value at the end to obtain `delta`.
+ for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
+
+ if (index >= inputLength) {
+ error('invalid-input');
+ }
+
+ digit = basicToDigit(input.charCodeAt(index++));
+
+ if (digit >= base || digit > floor((maxInt - i) / w)) {
+ error('overflow');
+ }
+
+ i += digit * w;
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+
+ if (digit < t) {
+ break;
+ }
+
+ baseMinusT = base - t;
+ if (w > floor(maxInt / baseMinusT)) {
+ error('overflow');
+ }
+
+ w *= baseMinusT;
+
+ }
+
+ out = output.length + 1;
+ bias = adapt(i - oldi, out, oldi == 0);
+
+ // `i` was supposed to wrap around from `out` to `0`,
+ // incrementing `n` each time, so we'll fix that now:
+ if (floor(i / out) > maxInt - n) {
+ error('overflow');
+ }
+
+ n += floor(i / out);
+ i %= out;
+
+ // Insert `n` at position `i` of the output
+ output.splice(i++, 0, n);
+
+ }
+
+ return ucs2encode(output);
+ }
+
+ /**
+ * Converts a string of Unicode symbols (e.g. a domain name label) to a
+ * Punycode string of ASCII-only symbols.
+ * @memberOf punycode
+ * @param {String} input The string of Unicode symbols.
+ * @returns {String} The resulting Punycode string of ASCII-only symbols.
+ */
+ function encode(input) {
+ var n,
+ delta,
+ handledCPCount,
+ basicLength,
+ bias,
+ j,
+ m,
+ q,
+ k,
+ t,
+ currentValue,
+ output = [],
+ /** `inputLength` will hold the number of code points in `input`. */
+ inputLength,
+ /** Cached calculation results */
+ handledCPCountPlusOne,
+ baseMinusT,
+ qMinusT;
+
+ // Convert the input in UCS-2 to Unicode
+ input = ucs2decode(input);
+
+ // Cache the length
+ inputLength = input.length;
+
+ // Initialize the state
+ n = initialN;
+ delta = 0;
+ bias = initialBias;
+
+ // Handle the basic code points
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue < 0x80) {
+ output.push(stringFromCharCode(currentValue));
+ }
+ }
+
+ handledCPCount = basicLength = output.length;
+
+ // `handledCPCount` is the number of code points that have been handled;
+ // `basicLength` is the number of basic code points.
+
+ // Finish the basic string - if it is not empty - with a delimiter
+ if (basicLength) {
+ output.push(delimiter);
+ }
+
+ // Main encoding loop:
+ while (handledCPCount < inputLength) {
+
+ // All non-basic code points < n have been handled already. Find the next
+ // larger one:
+ for (m = maxInt, j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+ if (currentValue >= n && currentValue < m) {
+ m = currentValue;
+ }
+ }
+
+ // Increase `delta` enough to advance the decoder's state to ,
+ // but guard against overflow
+ handledCPCountPlusOne = handledCPCount + 1;
+ if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
+ error('overflow');
+ }
+
+ delta += (m - n) * handledCPCountPlusOne;
+ n = m;
+
+ for (j = 0; j < inputLength; ++j) {
+ currentValue = input[j];
+
+ if (currentValue < n && ++delta > maxInt) {
+ error('overflow');
+ }
+
+ if (currentValue == n) {
+ // Represent delta as a generalized variable-length integer
+ for (q = delta, k = base; /* no condition */; k += base) {
+ t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
+ if (q < t) {
+ break;
+ }
+ qMinusT = q - t;
+ baseMinusT = base - t;
+ output.push(
+ stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
+ );
+ q = floor(qMinusT / baseMinusT);
+ }
+
+ output.push(stringFromCharCode(digitToBasic(q, 0)));
+ bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
+ delta = 0;
+ ++handledCPCount;
+ }
+ }
+
+ ++delta;
+ ++n;
+
+ }
+ return output.join('');
+ }
+
+ /**
+ * Converts a Punycode string representing a domain name or an email address
+ * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
+ * it doesn't matter if you call it on a string that has already been
+ * converted to Unicode.
+ * @memberOf punycode
+ * @param {String} input The Punycoded domain name or email address to
+ * convert to Unicode.
+ * @returns {String} The Unicode representation of the given Punycode
+ * string.
+ */
+ function toUnicode(input) {
+ return mapDomain(input, function(string) {
+ return regexPunycode.test(string)
+ ? decode(string.slice(4).toLowerCase())
+ : string;
+ });
+ }
+
+ /**
+ * Converts a Unicode string representing a domain name or an email address to
+ * Punycode. Only the non-ASCII parts of the domain name will be converted,
+ * i.e. it doesn't matter if you call it with a domain that's already in
+ * ASCII.
+ * @memberOf punycode
+ * @param {String} input The domain name or email address to convert, as a
+ * Unicode string.
+ * @returns {String} The Punycode representation of the given domain name or
+ * email address.
+ */
+ function toASCII(input) {
+ return mapDomain(input, function(string) {
+ return regexNonASCII.test(string)
+ ? 'xn--' + encode(string)
+ : string;
+ });
+ }
+
+ /*--------------------------------------------------------------------------*/
+
+ /** Define the public API */
+ punycode = {
+ /**
+ * A string representing the current Punycode.js version number.
+ * @memberOf punycode
+ * @type String
+ */
+ 'version': '1.4.1',
+ /**
+ * An object of methods to convert from JavaScript's internal character
+ * representation (UCS-2) to Unicode code points, and back.
+ * @see
+ * @memberOf punycode
+ * @type Object
+ */
+ 'ucs2': {
+ 'decode': ucs2decode,
+ 'encode': ucs2encode
+ },
+ 'decode': decode,
+ 'encode': encode,
+ 'toASCII': toASCII,
+ 'toUnicode': toUnicode
+ };
+
+ /** Expose `punycode` */
+ // Some AMD build optimizers, like r.js, check for specific condition patterns
+ // like the following:
+ if (
+ typeof define == 'function' &&
+ typeof define.amd == 'object' &&
+ define.amd
+ ) {
+ define('punycode', function() {
+ return punycode;
+ });
+ } else if (freeExports && freeModule) {
+ if (module.exports == freeExports) {
+ // in Node.js, io.js, or RingoJS v0.8.0+
+ freeModule.exports = punycode;
+ } else {
+ // in Narwhal or RingoJS v0.7.0-
+ for (key in punycode) {
+ punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
+ }
+ }
+ } else {
+ // in Rhino or a web browser
+ root.punycode = punycode;
+ }
+
+}(this));
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
+},{}],175:[function(require,module,exports){
+arguments[4][52][0].apply(exports,arguments)
+},{"dup":52,"safe-buffer":176}],176:[function(require,module,exports){
+arguments[4][51][0].apply(exports,arguments)
+},{"buffer":181,"dup":51}],177:[function(require,module,exports){
var basex = require('base-x')
var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
module.exports = basex(ALPHABET)
-},{"base-x":158}],214:[function(require,module,exports){
+},{"base-x":105}],178:[function(require,module,exports){
var bufferIndexOf = require('buffer-indexof');
module.exports = function(buf,splitBuf,includeDelim){
-
+
var search = -1
, lines = []
, move = includeDelim?splitBuf.length:0
@@ -32609,7 +24314,7 @@ module.exports = function(buf,splitBuf,includeDelim){
}
lines.push(buf);
-
+
return lines;
}
@@ -32617,10 +24322,10 @@ module.exports = function(buf,splitBuf,includeDelim){
-},{"buffer-indexof":215}],215:[function(require,module,exports){
+},{"buffer-indexof":179}],179:[function(require,module,exports){
module.exports = function bufferIndexOf(buf,search,offset){
offset = offset||0
-
+
var m = 0;
var s = -1;
for(var i=offset;i */ {
module.exports = KeyTransformDatastore
-},{"pull-stream":1495}],240:[function(require,module,exports){
+},{"pull-stream":1311}],201:[function(require,module,exports){
/* @flow */
'use strict'
@@ -36689,7 +27835,7 @@ class MountDatastore /* :: */ {
module.exports = MountDatastore
-},{"./keytransform":239,"async/each":106,"interface-datastore":458,"pull-many":1476,"pull-stream":1495}],241:[function(require,module,exports){
+},{"./keytransform":200,"async/each":56,"interface-datastore":322,"pull-many":1293,"pull-stream":1311}],202:[function(require,module,exports){
/* @flow */
'use strict'
@@ -36745,7 +27891,7 @@ class NamespaceDatastore/* :: */ extends KeytransformDatastore /* :: */ {
module.exports = TieredDatastore
-},{"async/each":106,"async/whilst":153,"interface-datastore":458}],246:[function(require,module,exports){
+},{"async/each":56,"async/whilst":103,"interface-datastore":322}],207:[function(require,module,exports){
(function (Buffer){
/* @flow */
'use strict'
@@ -37437,7 +28583,7 @@ class LevelDatastore {
module.exports = LevelDatastore
}).call(this,require("buffer").Buffer)
-},{"buffer":217,"encoding-down":298,"interface-datastore":458,"leveldown":862,"levelup":872,"pull-stream":1495}],247:[function(require,module,exports){
+},{"buffer":181,"encoding-down":252,"interface-datastore":322,"leveldown":700,"levelup":713,"pull-stream":1311}],208:[function(require,module,exports){
(function (process){
/* eslint-env browser */
@@ -37705,7 +28851,7 @@ formatters.j = function (v) {
};
}).call(this,require('_process'))
-},{"./common":248,"_process":1438}],248:[function(require,module,exports){
+},{"./common":209,"_process":1258}],209:[function(require,module,exports){
/**
* This is the common logic for both the Node.js and web browser
@@ -37973,7 +29119,7 @@ function setup(env) {
module.exports = setup;
-},{"ms":250}],249:[function(require,module,exports){
+},{"ms":1136}],210:[function(require,module,exports){
'use strict';
function createError(msg, code, props) {
@@ -37997,171 +29143,7 @@ function createError(msg, code, props) {
module.exports = createError;
-},{}],250:[function(require,module,exports){
-/**
- * Helpers.
- */
-
-var s = 1000;
-var m = s * 60;
-var h = m * 60;
-var d = h * 24;
-var w = d * 7;
-var y = d * 365.25;
-
-/**
- * Parse or format the given `val`.
- *
- * Options:
- *
- * - `long` verbose formatting [false]
- *
- * @param {String|Number} val
- * @param {Object} [options]
- * @throws {Error} throw an error if val is not a non-empty string or a number
- * @return {String|Number}
- * @api public
- */
-
-module.exports = function(val, options) {
- options = options || {};
- var type = typeof val;
- if (type === 'string' && val.length > 0) {
- return parse(val);
- } else if (type === 'number' && isFinite(val)) {
- return options.long ? fmtLong(val) : fmtShort(val);
- }
- throw new Error(
- 'val is not a non-empty string or a valid number. val=' +
- JSON.stringify(val)
- );
-};
-
-/**
- * Parse the given `str` and return milliseconds.
- *
- * @param {String} str
- * @return {Number}
- * @api private
- */
-
-function parse(str) {
- str = String(str);
- if (str.length > 100) {
- return;
- }
- var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(
- str
- );
- if (!match) {
- return;
- }
- var n = parseFloat(match[1]);
- var type = (match[2] || 'ms').toLowerCase();
- switch (type) {
- case 'years':
- case 'year':
- case 'yrs':
- case 'yr':
- case 'y':
- return n * y;
- case 'weeks':
- case 'week':
- case 'w':
- return n * w;
- case 'days':
- case 'day':
- case 'd':
- return n * d;
- case 'hours':
- case 'hour':
- case 'hrs':
- case 'hr':
- case 'h':
- return n * h;
- case 'minutes':
- case 'minute':
- case 'mins':
- case 'min':
- case 'm':
- return n * m;
- case 'seconds':
- case 'second':
- case 'secs':
- case 'sec':
- case 's':
- return n * s;
- case 'milliseconds':
- case 'millisecond':
- case 'msecs':
- case 'msec':
- case 'ms':
- return n;
- default:
- return undefined;
- }
-}
-
-/**
- * Short format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtShort(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return Math.round(ms / d) + 'd';
- }
- if (msAbs >= h) {
- return Math.round(ms / h) + 'h';
- }
- if (msAbs >= m) {
- return Math.round(ms / m) + 'm';
- }
- if (msAbs >= s) {
- return Math.round(ms / s) + 's';
- }
- return ms + 'ms';
-}
-
-/**
- * Long format for `ms`.
- *
- * @param {Number} ms
- * @return {String}
- * @api private
- */
-
-function fmtLong(ms) {
- var msAbs = Math.abs(ms);
- if (msAbs >= d) {
- return plural(ms, msAbs, d, 'day');
- }
- if (msAbs >= h) {
- return plural(ms, msAbs, h, 'hour');
- }
- if (msAbs >= m) {
- return plural(ms, msAbs, m, 'minute');
- }
- if (msAbs >= s) {
- return plural(ms, msAbs, s, 'second');
- }
- return ms + ' ms';
-}
-
-/**
- * Pluralization helper.
- */
-
-function plural(ms, msAbs, n, name) {
- var isPlural = msAbs >= n * 1.5;
- return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');
-}
-
-},{}],251:[function(require,module,exports){
+},{}],211:[function(require,module,exports){
(function (Buffer){
'use strict'
@@ -38469,7 +29451,7 @@ class DatastorePubsub {
exports = module.exports = DatastorePubsub
}).call(this,require("buffer").Buffer)
-},{"./utils":252,"assert":78,"buffer":217,"debug":247,"err-code":249,"interface-datastore":458}],252:[function(require,module,exports){
+},{"./utils":212,"assert":26,"buffer":181,"debug":208,"err-code":210,"interface-datastore":322}],212:[function(require,module,exports){
'use strict'
const multibase = require('multibase')
@@ -38502,38 +29484,28 @@ module.exports.topicToKey = (topic) => {
return multibase.decode(key).toString()
}
-},{"err-code":249,"multibase":1322}],253:[function(require,module,exports){
+},{"err-code":210,"multibase":1148}],213:[function(require,module,exports){
(function (process){
+"use strict";
+
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+/* eslint-env browser */
+
/**
* This is the web browser implementation of `debug()`.
- *
- * Expose `debug()` as the module.
*/
-
-exports = module.exports = require('./debug');
exports.log = log;
exports.formatArgs = formatArgs;
exports.save = save;
exports.load = load;
exports.useColors = useColors;
-exports.storage = 'undefined' != typeof chrome
- && 'undefined' != typeof chrome.storage
- ? chrome.storage.local
- : localstorage();
-
+exports.storage = localstorage();
/**
* Colors.
*/
-exports.colors = [
- 'lightseagreen',
- 'forestgreen',
- 'goldenrod',
- 'dodgerblue',
- 'darkorchid',
- 'crimson'
-];
-
+exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'];
/**
* Currently only WebKit-based Web Inspectors, Firefox >= v31,
* and the Firebug extension (any Firefox version) are known
@@ -38541,79 +29513,65 @@ exports.colors = [
*
* TODO: add a `localStorage` variable to explicitly enable/disable colors
*/
+// eslint-disable-next-line complexity
function useColors() {
// NB: In an Electron preload script, document will be defined but not fully
// initialized. Since we know we're in Chrome, we'll just detect this case
// explicitly
- if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') {
+ if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {
return true;
- }
+ } // Internet Explorer and Edge do not support colors.
- // is webkit? http://stackoverflow.com/a/16459606/376773
+
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
+ } // Is webkit? http://stackoverflow.com/a/16459606/376773
// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632
- return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||
- // is firebug? http://stackoverflow.com/a/398120/376773
- (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||
- // is firefox >= v31?
- // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) ||
- // double check webkit in userAgent just in case we are in a worker
- (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/));
+
+
+ return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773
+ typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31?
+ // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
+ typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker
+ typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/);
}
-
-/**
- * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
- */
-
-exports.formatters.j = function(v) {
- try {
- return JSON.stringify(v);
- } catch (err) {
- return '[UnexpectedJSONParseError]: ' + err.message;
- }
-};
-
-
/**
* Colorize log arguments if enabled.
*
* @api public
*/
+
function formatArgs(args) {
- var useColors = this.useColors;
+ args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff);
- args[0] = (useColors ? '%c' : '')
- + this.namespace
- + (useColors ? ' %c' : ' ')
- + args[0]
- + (useColors ? '%c ' : ' ')
- + '+' + exports.humanize(this.diff);
-
- if (!useColors) return;
+ if (!this.useColors) {
+ return;
+ }
var c = 'color: ' + this.color;
- args.splice(1, 0, c, 'color: inherit')
-
- // the final "%c" is somewhat tricky, because there could be other
+ args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other
// arguments passed either before or after the %c, so we need to
// figure out the correct index to insert the CSS into
+
var index = 0;
var lastC = 0;
- args[0].replace(/%[a-zA-Z%]/g, function(match) {
- if ('%%' === match) return;
+ args[0].replace(/%[a-zA-Z%]/g, function (match) {
+ if (match === '%%') {
+ return;
+ }
+
index++;
- if ('%c' === match) {
- // we only are interested in the *last* %c
+
+ if (match === '%c') {
+ // We only are interested in the *last* %c
// (the user may have provided their own)
lastC = index;
}
});
-
args.splice(lastC, 0, c);
}
-
/**
* Invokes `console.log()` when available.
* No-op when `console.log` is not a "function".
@@ -38621,14 +29579,14 @@ function formatArgs(args) {
* @api public
*/
-function log() {
- // this hackery is required for IE8/9, where
- // the `console.log` function doesn't have 'apply'
- return 'object' === typeof console
- && console.log
- && Function.prototype.apply.call(console.log, console, arguments);
-}
+function log() {
+ var _console;
+
+ // This hackery is required for IE8/9, where
+ // the `console.log` function doesn't have 'apply'
+ return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments);
+}
/**
* Save `namespaces`.
*
@@ -38636,16 +29594,18 @@ function log() {
* @api private
*/
+
function save(namespaces) {
try {
- if (null == namespaces) {
- exports.storage.removeItem('debug');
+ if (namespaces) {
+ exports.storage.setItem('debug', namespaces);
} else {
- exports.storage.debug = namespaces;
+ exports.storage.removeItem('debug');
}
- } catch(e) {}
+ } catch (error) {// Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
}
-
/**
* Load `namespaces`.
*
@@ -38653,26 +29613,23 @@ function save(namespaces) {
* @api private
*/
+
function load() {
var r;
- try {
- r = exports.storage.debug;
- } catch(e) {}
+ try {
+ r = exports.storage.getItem('debug');
+ } catch (error) {} // Swallow
+ // XXX (@Qix-) should we be logging these?
// If debug isn't set in LS, and we're in Electron, try to load $DEBUG
+
+
if (!r && typeof process !== 'undefined' && 'env' in process) {
r = process.env.DEBUG;
}
return r;
}
-
-/**
- * Enable namespaces listed in `localStorage.debug` initially.
- */
-
-exports.enable(load());
-
/**
* Localstorage attempts to return the localstorage.
*
@@ -38684,314 +29641,285 @@ exports.enable(load());
* @api private
*/
+
function localstorage() {
try {
- return window.localStorage;
- } catch (e) {}
+ // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context
+ // The Browser also has localStorage in the global context.
+ return localStorage;
+ } catch (error) {// Swallow
+ // XXX (@Qix-) should we be logging these?
+ }
}
+module.exports = require('./common')(exports);
+var formatters = module.exports.formatters;
+/**
+ * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
+ */
+
+formatters.j = function (v) {
+ try {
+ return JSON.stringify(v);
+ } catch (error) {
+ return '[UnexpectedJSONParseError]: ' + error.message;
+ }
+};
+
+
}).call(this,require('_process'))
-},{"./debug":254,"_process":1438}],254:[function(require,module,exports){
+},{"./common":214,"_process":1258}],214:[function(require,module,exports){
+"use strict";
/**
* This is the common logic for both the Node.js and web browser
* implementations of `debug()`.
- *
- * Expose `debug()` as the module.
*/
+function setup(env) {
+ createDebug.debug = createDebug;
+ createDebug.default = createDebug;
+ createDebug.coerce = coerce;
+ createDebug.disable = disable;
+ createDebug.enable = enable;
+ createDebug.enabled = enabled;
+ createDebug.humanize = require('ms');
+ Object.keys(env).forEach(function (key) {
+ createDebug[key] = env[key];
+ });
+ /**
+ * Active `debug` instances.
+ */
-exports = module.exports = createDebug.debug = createDebug['default'] = createDebug;
-exports.coerce = coerce;
-exports.disable = disable;
-exports.enable = enable;
-exports.enabled = enabled;
-exports.humanize = require('ms');
+ createDebug.instances = [];
+ /**
+ * The currently active debug mode names, and names to skip.
+ */
-/**
- * The currently active debug mode names, and names to skip.
- */
+ createDebug.names = [];
+ createDebug.skips = [];
+ /**
+ * Map of special "%n" handling functions, for the debug "format" argument.
+ *
+ * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
+ */
-exports.names = [];
-exports.skips = [];
+ createDebug.formatters = {};
+ /**
+ * Selects a color for a debug namespace
+ * @param {String} namespace The namespace string for the for the debug instance to be colored
+ * @return {Number|String} An ANSI color code for the given namespace
+ * @api private
+ */
-/**
- * Map of special "%n" handling functions, for the debug "format" argument.
- *
- * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N".
- */
+ function selectColor(namespace) {
+ var hash = 0;
-exports.formatters = {};
+ for (var i = 0; i < namespace.length; i++) {
+ hash = (hash << 5) - hash + namespace.charCodeAt(i);
+ hash |= 0; // Convert to 32bit integer
+ }
-/**
- * Previous log timestamp.
- */
-
-var prevTime;
-
-/**
- * Select a color.
- * @param {String} namespace
- * @return {Number}
- * @api private
- */
-
-function selectColor(namespace) {
- var hash = 0, i;
-
- for (i in namespace) {
- hash = ((hash << 5) - hash) + namespace.charCodeAt(i);
- hash |= 0; // Convert to 32bit integer
+ return createDebug.colors[Math.abs(hash) % createDebug.colors.length];
}
- return exports.colors[Math.abs(hash) % exports.colors.length];
-}
+ createDebug.selectColor = selectColor;
+ /**
+ * Create a debugger with the given `namespace`.
+ *
+ * @param {String} namespace
+ * @return {Function}
+ * @api public
+ */
-/**
- * Create a debugger with the given `namespace`.
- *
- * @param {String} namespace
- * @return {Function}
- * @api public
- */
+ function createDebug(namespace) {
+ var prevTime;
-function createDebug(namespace) {
-
- function debug() {
- // disabled?
- if (!debug.enabled) return;
-
- var self = debug;
-
- // set `diff` timestamp
- var curr = +new Date();
- var ms = curr - (prevTime || curr);
- self.diff = ms;
- self.prev = prevTime;
- self.curr = curr;
- prevTime = curr;
-
- // turn the `arguments` into a proper Array
- var args = new Array(arguments.length);
- for (var i = 0; i < args.length; i++) {
- args[i] = arguments[i];
- }
-
- args[0] = exports.coerce(args[0]);
-
- if ('string' !== typeof args[0]) {
- // anything else let's inspect with %O
- args.unshift('%O');
- }
-
- // apply any `formatters` transformations
- var index = 0;
- args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) {
- // if we encounter an escaped % then don't increase the array index
- if (match === '%%') return match;
- index++;
- var formatter = exports.formatters[format];
- if ('function' === typeof formatter) {
- var val = args[index];
- match = formatter.call(self, val);
-
- // now we need to remove `args[index]` since it's inlined in the `format`
- args.splice(index, 1);
- index--;
+ function debug() {
+ // Disabled?
+ if (!debug.enabled) {
+ return;
}
- return match;
- });
- // apply env-specific formatting (colors, etc.)
- exports.formatArgs.call(self, args);
+ for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
- var logFn = debug.log || exports.log || console.log.bind(console);
- logFn.apply(self, args);
- }
+ var self = debug; // Set `diff` timestamp
- debug.namespace = namespace;
- debug.enabled = exports.enabled(namespace);
- debug.useColors = exports.useColors();
- debug.color = selectColor(namespace);
+ var curr = Number(new Date());
+ var ms = curr - (prevTime || curr);
+ self.diff = ms;
+ self.prev = prevTime;
+ self.curr = curr;
+ prevTime = curr;
+ args[0] = createDebug.coerce(args[0]);
- // env-specific initialization logic for debug instances
- if ('function' === typeof exports.init) {
- exports.init(debug);
- }
+ if (typeof args[0] !== 'string') {
+ // Anything else let's inspect with %O
+ args.unshift('%O');
+ } // Apply any `formatters` transformations
- return debug;
-}
-/**
- * Enables a debug mode by namespaces. This can include modes
- * separated by a colon and wildcards.
- *
- * @param {String} namespaces
- * @api public
- */
+ var index = 0;
+ args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) {
+ // If we encounter an escaped % then don't increase the array index
+ if (match === '%%') {
+ return match;
+ }
-function enable(namespaces) {
- exports.save(namespaces);
+ index++;
+ var formatter = createDebug.formatters[format];
- exports.names = [];
- exports.skips = [];
+ if (typeof formatter === 'function') {
+ var val = args[index];
+ match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format`
- var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
- var len = split.length;
+ args.splice(index, 1);
+ index--;
+ }
- for (var i = 0; i < len; i++) {
- if (!split[i]) continue; // ignore empty strings
- namespaces = split[i].replace(/\*/g, '.*?');
- if (namespaces[0] === '-') {
- exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
- } else {
- exports.names.push(new RegExp('^' + namespaces + '$'));
+ return match;
+ }); // Apply env-specific formatting (colors, etc.)
+
+ createDebug.formatArgs.call(self, args);
+ var logFn = self.log || createDebug.log;
+ logFn.apply(self, args);
}
- }
-}
-/**
- * Disable debug output.
- *
- * @api public
- */
+ debug.namespace = namespace;
+ debug.enabled = createDebug.enabled(namespace);
+ debug.useColors = createDebug.useColors();
+ debug.color = selectColor(namespace);
+ debug.destroy = destroy;
+ debug.extend = extend; // Debug.formatArgs = formatArgs;
+ // debug.rawLog = rawLog;
+ // env-specific initialization logic for debug instances
-function disable() {
- exports.enable('');
-}
-
-/**
- * Returns true if the given mode name is enabled, false otherwise.
- *
- * @param {String} name
- * @return {Boolean}
- * @api public
- */
-
-function enabled(name) {
- var i, len;
- for (i = 0, len = exports.skips.length; i < len; i++) {
- if (exports.skips[i].test(name)) {
- return false;
+ if (typeof createDebug.init === 'function') {
+ createDebug.init(debug);
}
+
+ createDebug.instances.push(debug);
+ return debug;
}
- for (i = 0, len = exports.names.length; i < len; i++) {
- if (exports.names[i].test(name)) {
+
+ function destroy() {
+ var index = createDebug.instances.indexOf(this);
+
+ if (index !== -1) {
+ createDebug.instances.splice(index, 1);
return true;
}
+
+ return false;
}
- return false;
+
+ function extend(namespace, delimiter) {
+ return createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);
+ }
+ /**
+ * Enables a debug mode by namespaces. This can include modes
+ * separated by a colon and wildcards.
+ *
+ * @param {String} namespaces
+ * @api public
+ */
+
+
+ function enable(namespaces) {
+ createDebug.save(namespaces);
+ createDebug.names = [];
+ createDebug.skips = [];
+ var i;
+ var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/);
+ var len = split.length;
+
+ for (i = 0; i < len; i++) {
+ if (!split[i]) {
+ // ignore empty strings
+ continue;
+ }
+
+ namespaces = split[i].replace(/\*/g, '.*?');
+
+ if (namespaces[0] === '-') {
+ createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
+ } else {
+ createDebug.names.push(new RegExp('^' + namespaces + '$'));
+ }
+ }
+
+ for (i = 0; i < createDebug.instances.length; i++) {
+ var instance = createDebug.instances[i];
+ instance.enabled = createDebug.enabled(instance.namespace);
+ }
+ }
+ /**
+ * Disable debug output.
+ *
+ * @api public
+ */
+
+
+ function disable() {
+ createDebug.enable('');
+ }
+ /**
+ * Returns true if the given mode name is enabled, false otherwise.
+ *
+ * @param {String} name
+ * @return {Boolean}
+ * @api public
+ */
+
+
+ function enabled(name) {
+ if (name[name.length - 1] === '*') {
+ return true;
+ }
+
+ var i;
+ var len;
+
+ for (i = 0, len = createDebug.skips.length; i < len; i++) {
+ if (createDebug.skips[i].test(name)) {
+ return false;
+ }
+ }
+
+ for (i = 0, len = createDebug.names.length; i < len; i++) {
+ if (createDebug.names[i].test(name)) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+ /**
+ * Coerce `val`.
+ *
+ * @param {Mixed} val
+ * @return {Mixed}
+ * @api private
+ */
+
+
+ function coerce(val) {
+ if (val instanceof Error) {
+ return val.stack || val.message;
+ }
+
+ return val;
+ }
+
+ createDebug.enable(createDebug.load());
+ return createDebug;
}
-/**
- * Coerce `val`.
- *
- * @param {Mixed} val
- * @return {Mixed}
- * @api private
- */
+module.exports = setup;
-function coerce(val) {
- if (val instanceof Error) return val.stack || val.message;
- return val;
-}
-},{"ms":1310}],255:[function(require,module,exports){
-'use strict';
-var token = '%[a-f0-9]{2}';
-var singleMatcher = new RegExp(token, 'gi');
-var multiMatcher = new RegExp('(' + token + ')+', 'gi');
-
-function decodeComponents(components, split) {
- try {
- // Try to decode the entire string first
- return decodeURIComponent(components.join(''));
- } catch (err) {
- // Do nothing
- }
-
- if (components.length === 1) {
- return components;
- }
-
- split = split || 1;
-
- // Split the array in 2 parts
- var left = components.slice(0, split);
- var right = components.slice(split);
-
- return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
-}
-
-function decode(input) {
- try {
- return decodeURIComponent(input);
- } catch (err) {
- var tokens = input.match(singleMatcher);
-
- for (var i = 1; i < tokens.length; i++) {
- input = decodeComponents(tokens, i).join('');
-
- tokens = input.match(singleMatcher);
- }
-
- return input;
- }
-}
-
-function customDecodeURIComponent(input) {
- // Keep track of all the replacements and prefill the map with the `BOM`
- var replaceMap = {
- '%FE%FF': '\uFFFD\uFFFD',
- '%FF%FE': '\uFFFD\uFFFD'
- };
-
- var match = multiMatcher.exec(input);
- while (match) {
- try {
- // Decode as big chunks as possible
- replaceMap[match[0]] = decodeURIComponent(match[0]);
- } catch (err) {
- var result = decode(match[0]);
-
- if (result !== match[0]) {
- replaceMap[match[0]] = result;
- }
- }
-
- match = multiMatcher.exec(input);
- }
-
- // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
- replaceMap['%C2'] = '\uFFFD';
-
- var entries = Object.keys(replaceMap);
-
- for (var i = 0; i < entries.length; i++) {
- // Replace all decoded components
- var key = entries[i];
- input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
- }
-
- return input;
-}
-
-module.exports = function (encodedURI) {
- if (typeof encodedURI !== 'string') {
- throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
- }
-
- try {
- encodedURI = encodedURI.replace(/\+/g, ' ');
-
- // Try the built in decoder first
- return decodeURIComponent(encodedURI);
- } catch (err) {
- // Fallback to a more advanced decoder
- return customDecodeURIComponent(encodedURI);
- }
-};
-
-},{}],256:[function(require,module,exports){
+},{"ms":1136}],215:[function(require,module,exports){
(function (Buffer){
/*!
* @description Recursive object extending
@@ -39145,12 +30073,12 @@ var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) {
};
}).call(this,require("buffer").Buffer)
-},{"buffer":217}],257:[function(require,module,exports){
+},{"buffer":181}],216:[function(require,module,exports){
var AbstractIterator = require('abstract-leveldown').AbstractIterator
var inherits = require('inherits')
-function DeferredIterator (options) {
- AbstractIterator.call(this, options)
+function DeferredIterator (db, options) {
+ AbstractIterator.call(this, db)
this._options = options
this._iterator = null
@@ -39184,7 +30112,7 @@ DeferredIterator.prototype.seek = function () {
module.exports = DeferredIterator
-},{"abstract-leveldown":262,"inherits":453}],258:[function(require,module,exports){
+},{"abstract-leveldown":6,"inherits":317}],217:[function(require,module,exports){
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
var inherits = require('inherits')
var DeferredIterator = require('./deferred-iterator')
@@ -39192,7 +30120,16 @@ var deferrables = 'put get del batch clear'.split(' ')
var optionalDeferrables = 'approximateSize compactRange'.split(' ')
function DeferredLevelDOWN (db) {
- AbstractLevelDOWN.call(this, '')
+ AbstractLevelDOWN.call(this, db.supports || {})
+
+ // TODO (future major): remove this fallback; db must have manifest that
+ // declares approximateSize and compactRange in additionalMethods.
+ optionalDeferrables.forEach(function (m) {
+ if (typeof db[m] === 'function' && !this.supports.additionalMethods[m]) {
+ this.supports.additionalMethods[m] = true
+ }
+ }, this)
+
this._db = db
this._operations = []
closed(this)
@@ -39238,11 +30175,9 @@ function open (self) {
return this._db[m].apply(this._db, arguments)
}
})
- optionalDeferrables.forEach(function (m) {
- if (typeof self._db[m] === 'function') {
- self[m] = function () {
- return this._db[m].apply(this._db, arguments)
- }
+ Object.keys(self.supports.additionalMethods).forEach(function (m) {
+ self[m] = function () {
+ return this._db[m].apply(this._db, arguments)
}
})
}
@@ -39253,15 +30188,13 @@ function closed (self) {
this._operations.push({ method: m, args: arguments })
}
})
- optionalDeferrables.forEach(function (m) {
- if (typeof self._db[m] === 'function') {
- self[m] = function () {
- this._operations.push({ method: m, args: arguments })
- }
+ Object.keys(self.supports.additionalMethods).forEach(function (m) {
+ self[m] = function () {
+ this._operations.push({ method: m, args: arguments })
}
})
self._iterator = function (options) {
- var it = new DeferredIterator(options)
+ var it = new DeferredIterator(self, options)
this._operations.push({ iterator: it })
return it
}
@@ -39278,326 +30211,7 @@ DeferredLevelDOWN.prototype._serializeValue = function (value) {
module.exports = DeferredLevelDOWN
module.exports.DeferredIterator = DeferredIterator
-},{"./deferred-iterator":257,"abstract-leveldown":262,"inherits":453}],259:[function(require,module,exports){
-arguments[4][3][0].apply(exports,arguments)
-},{"dup":3}],260:[function(require,module,exports){
-arguments[4][4][0].apply(exports,arguments)
-},{"_process":1438,"dup":4}],261:[function(require,module,exports){
-(function (Buffer,process){
-var xtend = require('xtend')
-var AbstractIterator = require('./abstract-iterator')
-var AbstractChainedBatch = require('./abstract-chained-batch')
-var hasOwnProperty = Object.prototype.hasOwnProperty
-var rangeOptions = 'start end gt gte lt lte'.split(' ')
-
-function AbstractLevelDOWN () {
- this.status = 'new'
-}
-
-AbstractLevelDOWN.prototype.open = function (options, callback) {
- var self = this
- var oldStatus = this.status
-
- if (typeof options === 'function') callback = options
-
- if (typeof callback !== 'function') {
- throw new Error('open() requires a callback argument')
- }
-
- if (typeof options !== 'object' || options === null) options = {}
-
- options.createIfMissing = options.createIfMissing !== false
- options.errorIfExists = !!options.errorIfExists
-
- this.status = 'opening'
- this._open(options, function (err) {
- if (err) {
- self.status = oldStatus
- return callback(err)
- }
- self.status = 'open'
- callback()
- })
-}
-
-AbstractLevelDOWN.prototype._open = function (options, callback) {
- process.nextTick(callback)
-}
-
-AbstractLevelDOWN.prototype.close = function (callback) {
- var self = this
- var oldStatus = this.status
-
- if (typeof callback !== 'function') {
- throw new Error('close() requires a callback argument')
- }
-
- this.status = 'closing'
- this._close(function (err) {
- if (err) {
- self.status = oldStatus
- return callback(err)
- }
- self.status = 'closed'
- callback()
- })
-}
-
-AbstractLevelDOWN.prototype._close = function (callback) {
- process.nextTick(callback)
-}
-
-AbstractLevelDOWN.prototype.get = function (key, options, callback) {
- if (typeof options === 'function') callback = options
-
- if (typeof callback !== 'function') {
- throw new Error('get() requires a callback argument')
- }
-
- var err = this._checkKey(key)
- if (err) return process.nextTick(callback, err)
-
- key = this._serializeKey(key)
-
- if (typeof options !== 'object' || options === null) options = {}
-
- options.asBuffer = options.asBuffer !== false
-
- this._get(key, options, callback)
-}
-
-AbstractLevelDOWN.prototype._get = function (key, options, callback) {
- process.nextTick(function () { callback(new Error('NotFound')) })
-}
-
-AbstractLevelDOWN.prototype.put = function (key, value, options, callback) {
- if (typeof options === 'function') callback = options
-
- if (typeof callback !== 'function') {
- throw new Error('put() requires a callback argument')
- }
-
- var err = this._checkKey(key) || this._checkValue(value)
- if (err) return process.nextTick(callback, err)
-
- key = this._serializeKey(key)
- value = this._serializeValue(value)
-
- if (typeof options !== 'object' || options === null) options = {}
-
- this._put(key, value, options, callback)
-}
-
-AbstractLevelDOWN.prototype._put = function (key, value, options, callback) {
- process.nextTick(callback)
-}
-
-AbstractLevelDOWN.prototype.del = function (key, options, callback) {
- if (typeof options === 'function') callback = options
-
- if (typeof callback !== 'function') {
- throw new Error('del() requires a callback argument')
- }
-
- var err = this._checkKey(key)
- if (err) return process.nextTick(callback, err)
-
- key = this._serializeKey(key)
-
- if (typeof options !== 'object' || options === null) options = {}
-
- this._del(key, options, callback)
-}
-
-AbstractLevelDOWN.prototype._del = function (key, options, callback) {
- process.nextTick(callback)
-}
-
-AbstractLevelDOWN.prototype.batch = function (array, options, callback) {
- if (!arguments.length) return this._chainedBatch()
-
- if (typeof options === 'function') callback = options
-
- if (typeof array === 'function') callback = array
-
- if (typeof callback !== 'function') {
- throw new Error('batch(array) requires a callback argument')
- }
-
- if (!Array.isArray(array)) {
- return process.nextTick(callback, new Error('batch(array) requires an array argument'))
- }
-
- if (array.length === 0) {
- return process.nextTick(callback)
- }
-
- if (typeof options !== 'object' || options === null) options = {}
-
- var serialized = new Array(array.length)
-
- for (var i = 0; i < array.length; i++) {
- if (typeof array[i] !== 'object' || array[i] === null) {
- return process.nextTick(callback, new Error('batch(array) element must be an object and not `null`'))
- }
-
- var e = xtend(array[i])
-
- if (e.type !== 'put' && e.type !== 'del') {
- return process.nextTick(callback, new Error("`type` must be 'put' or 'del'"))
- }
-
- var err = this._checkKey(e.key)
- if (err) return process.nextTick(callback, err)
-
- e.key = this._serializeKey(e.key)
-
- if (e.type === 'put') {
- var valueErr = this._checkValue(e.value)
- if (valueErr) return process.nextTick(callback, valueErr)
-
- e.value = this._serializeValue(e.value)
- }
-
- serialized[i] = e
- }
-
- this._batch(serialized, options, callback)
-}
-
-AbstractLevelDOWN.prototype._batch = function (array, options, callback) {
- process.nextTick(callback)
-}
-
-AbstractLevelDOWN.prototype.clear = function (options, callback) {
- if (typeof options === 'function') {
- callback = options
- } else if (typeof callback !== 'function') {
- throw new Error('clear() requires a callback argument')
- }
-
- options = cleanRangeOptions(this, options)
- options.reverse = !!options.reverse
- options.limit = 'limit' in options ? options.limit : -1
-
- this._clear(options, callback)
-}
-
-AbstractLevelDOWN.prototype._clear = function (options, callback) {
- // Avoid setupIteratorOptions, would serialize range options a second time.
- options.keys = true
- options.values = false
- options.keyAsBuffer = true
- options.valueAsBuffer = true
-
- var iterator = this._iterator(options)
- var emptyOptions = {}
- var self = this
-
- var next = function (err) {
- if (err) {
- return iterator.end(function () {
- callback(err)
- })
- }
-
- iterator.next(function (err, key) {
- if (err) return next(err)
- if (key === undefined) return iterator.end(callback)
-
- // This could be optimized by using a batch, but the default _clear
- // is not meant to be fast. Implementations have more room to optimize
- // if they override _clear. Note: using _del bypasses key serialization.
- self._del(key, emptyOptions, next)
- })
- }
-
- next()
-}
-
-AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) {
- options = cleanRangeOptions(this, options)
-
- options.reverse = !!options.reverse
- options.keys = options.keys !== false
- options.values = options.values !== false
- options.limit = 'limit' in options ? options.limit : -1
- options.keyAsBuffer = options.keyAsBuffer !== false
- options.valueAsBuffer = options.valueAsBuffer !== false
-
- return options
-}
-
-function cleanRangeOptions (db, options) {
- var result = {}
-
- for (var k in options) {
- if (!hasOwnProperty.call(options, k)) continue
-
- var opt = options[k]
-
- if (isRangeOption(k)) {
- // Note that we don't reject nullish and empty options here. While
- // those types are invalid as keys, they are valid as range options.
- opt = db._serializeKey(opt)
- }
-
- result[k] = opt
- }
-
- return result
-}
-
-function isRangeOption (k) {
- return rangeOptions.indexOf(k) !== -1
-}
-
-AbstractLevelDOWN.prototype.iterator = function (options) {
- if (typeof options !== 'object' || options === null) options = {}
- options = this._setupIteratorOptions(options)
- return this._iterator(options)
-}
-
-AbstractLevelDOWN.prototype._iterator = function (options) {
- return new AbstractIterator(this)
-}
-
-AbstractLevelDOWN.prototype._chainedBatch = function () {
- return new AbstractChainedBatch(this)
-}
-
-AbstractLevelDOWN.prototype._serializeKey = function (key) {
- return key
-}
-
-AbstractLevelDOWN.prototype._serializeValue = function (value) {
- return value
-}
-
-AbstractLevelDOWN.prototype._checkKey = function (key) {
- if (key === null || key === undefined) {
- return new Error('key cannot be `null` or `undefined`')
- } else if (Buffer.isBuffer(key) && key.length === 0) {
- return new Error('key cannot be an empty Buffer')
- } else if (key === '') {
- return new Error('key cannot be an empty String')
- } else if (Array.isArray(key) && key.length === 0) {
- return new Error('key cannot be an empty Array')
- }
-}
-
-AbstractLevelDOWN.prototype._checkValue = function (value) {
- if (value === null || value === undefined) {
- return new Error('value cannot be `null` or `undefined`')
- }
-}
-
-module.exports = AbstractLevelDOWN
-
-}).call(this,{"isBuffer":require("../../../is-buffer/index.js")},require('_process'))
-},{"../../../is-buffer/index.js":766,"./abstract-chained-batch":259,"./abstract-iterator":260,"_process":1438,"xtend":1860}],262:[function(require,module,exports){
-arguments[4][6][0].apply(exports,arguments)
-},{"./abstract-chained-batch":259,"./abstract-iterator":260,"./abstract-leveldown":261,"dup":6}],263:[function(require,module,exports){
+},{"./deferred-iterator":216,"abstract-leveldown":6,"inherits":317}],218:[function(require,module,exports){
'use strict';
var keys = require('object-keys');
@@ -39657,116 +30271,184 @@ defineProperties.supportsDescriptors = !!supportsDescriptors;
module.exports = defineProperties;
-},{"object-keys":1390}],264:[function(require,module,exports){
-var Stream = require('stream').Stream;
-var util = require('util');
+},{"object-keys":220}],219:[function(require,module,exports){
+'use strict';
-module.exports = DelayedStream;
-function DelayedStream() {
- this.source = null;
- this.dataSize = 0;
- this.maxDataSize = 1024 * 1024;
- this.pauseStream = true;
+var keysShim;
+if (!Object.keys) {
+ // modified from https://github.com/es-shims/es5-shim
+ var has = Object.prototype.hasOwnProperty;
+ var toStr = Object.prototype.toString;
+ var isArgs = require('./isArguments'); // eslint-disable-line global-require
+ var isEnumerable = Object.prototype.propertyIsEnumerable;
+ var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
+ var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
+ var dontEnums = [
+ 'toString',
+ 'toLocaleString',
+ 'valueOf',
+ 'hasOwnProperty',
+ 'isPrototypeOf',
+ 'propertyIsEnumerable',
+ 'constructor'
+ ];
+ var equalsConstructorPrototype = function (o) {
+ var ctor = o.constructor;
+ return ctor && ctor.prototype === o;
+ };
+ var excludedKeys = {
+ $applicationCache: true,
+ $console: true,
+ $external: true,
+ $frame: true,
+ $frameElement: true,
+ $frames: true,
+ $innerHeight: true,
+ $innerWidth: true,
+ $onmozfullscreenchange: true,
+ $onmozfullscreenerror: true,
+ $outerHeight: true,
+ $outerWidth: true,
+ $pageXOffset: true,
+ $pageYOffset: true,
+ $parent: true,
+ $scrollLeft: true,
+ $scrollTop: true,
+ $scrollX: true,
+ $scrollY: true,
+ $self: true,
+ $webkitIndexedDB: true,
+ $webkitStorageInfo: true,
+ $window: true
+ };
+ var hasAutomationEqualityBug = (function () {
+ /* global window */
+ if (typeof window === 'undefined') { return false; }
+ for (var k in window) {
+ try {
+ if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
+ try {
+ equalsConstructorPrototype(window[k]);
+ } catch (e) {
+ return true;
+ }
+ }
+ } catch (e) {
+ return true;
+ }
+ }
+ return false;
+ }());
+ var equalsConstructorPrototypeIfNotBuggy = function (o) {
+ /* global window */
+ if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
+ return equalsConstructorPrototype(o);
+ }
+ try {
+ return equalsConstructorPrototype(o);
+ } catch (e) {
+ return false;
+ }
+ };
- this._maxDataSizeExceeded = false;
- this._released = false;
- this._bufferedEvents = [];
+ keysShim = function keys(object) {
+ var isObject = object !== null && typeof object === 'object';
+ var isFunction = toStr.call(object) === '[object Function]';
+ var isArguments = isArgs(object);
+ var isString = isObject && toStr.call(object) === '[object String]';
+ var theKeys = [];
+
+ if (!isObject && !isFunction && !isArguments) {
+ throw new TypeError('Object.keys called on a non-object');
+ }
+
+ var skipProto = hasProtoEnumBug && isFunction;
+ if (isString && object.length > 0 && !has.call(object, 0)) {
+ for (var i = 0; i < object.length; ++i) {
+ theKeys.push(String(i));
+ }
+ }
+
+ if (isArguments && object.length > 0) {
+ for (var j = 0; j < object.length; ++j) {
+ theKeys.push(String(j));
+ }
+ } else {
+ for (var name in object) {
+ if (!(skipProto && name === 'prototype') && has.call(object, name)) {
+ theKeys.push(String(name));
+ }
+ }
+ }
+
+ if (hasDontEnumBug) {
+ var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
+
+ for (var k = 0; k < dontEnums.length; ++k) {
+ if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
+ theKeys.push(dontEnums[k]);
+ }
+ }
+ }
+ return theKeys;
+ };
}
-util.inherits(DelayedStream, Stream);
+module.exports = keysShim;
-DelayedStream.create = function(source, options) {
- var delayedStream = new this();
+},{"./isArguments":221}],220:[function(require,module,exports){
+'use strict';
- options = options || {};
- for (var option in options) {
- delayedStream[option] = options[option];
- }
+var slice = Array.prototype.slice;
+var isArgs = require('./isArguments');
- delayedStream.source = source;
+var origKeys = Object.keys;
+var keysShim = origKeys ? function keys(o) { return origKeys(o); } : require('./implementation');
- var realEmit = source.emit;
- source.emit = function() {
- delayedStream._handleEmit(arguments);
- return realEmit.apply(source, arguments);
- };
+var originalKeys = Object.keys;
- source.on('error', function() {});
- if (delayedStream.pauseStream) {
- source.pause();
- }
-
- return delayedStream;
+keysShim.shim = function shimObjectKeys() {
+ if (Object.keys) {
+ var keysWorksWithArguments = (function () {
+ // Safari 5.0 bug
+ var args = Object.keys(arguments);
+ return args && args.length === arguments.length;
+ }(1, 2));
+ if (!keysWorksWithArguments) {
+ Object.keys = function keys(object) { // eslint-disable-line func-name-matching
+ if (isArgs(object)) {
+ return originalKeys(slice.call(object));
+ }
+ return originalKeys(object);
+ };
+ }
+ } else {
+ Object.keys = keysShim;
+ }
+ return Object.keys || keysShim;
};
-Object.defineProperty(DelayedStream.prototype, 'readable', {
- configurable: true,
- enumerable: true,
- get: function() {
- return this.source.readable;
- }
-});
+module.exports = keysShim;
-DelayedStream.prototype.setEncoding = function() {
- return this.source.setEncoding.apply(this.source, arguments);
+},{"./implementation":219,"./isArguments":221}],221:[function(require,module,exports){
+'use strict';
+
+var toStr = Object.prototype.toString;
+
+module.exports = function isArguments(value) {
+ var str = toStr.call(value);
+ var isArgs = str === '[object Arguments]';
+ if (!isArgs) {
+ isArgs = str !== '[object Array]' &&
+ value !== null &&
+ typeof value === 'object' &&
+ typeof value.length === 'number' &&
+ value.length >= 0 &&
+ toStr.call(value.callee) === '[object Function]';
+ }
+ return isArgs;
};
-DelayedStream.prototype.resume = function() {
- if (!this._released) {
- this.release();
- }
-
- this.source.resume();
-};
-
-DelayedStream.prototype.pause = function() {
- this.source.pause();
-};
-
-DelayedStream.prototype.release = function() {
- this._released = true;
-
- this._bufferedEvents.forEach(function(args) {
- this.emit.apply(this, args);
- }.bind(this));
- this._bufferedEvents = [];
-};
-
-DelayedStream.prototype.pipe = function() {
- var r = Stream.prototype.pipe.apply(this, arguments);
- this.resume();
- return r;
-};
-
-DelayedStream.prototype._handleEmit = function(args) {
- if (this._released) {
- this.emit.apply(this, args);
- return;
- }
-
- if (args[0] === 'data') {
- this.dataSize += args[1].length;
- this._checkIfMaxDataSizeExceeded();
- }
-
- this._bufferedEvents.push(args);
-};
-
-DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() {
- if (this._maxDataSizeExceeded) {
- return;
- }
-
- if (this.dataSize <= this.maxDataSize) {
- return;
- }
-
- this._maxDataSizeExceeded = true;
- var message =
- 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'
- this.emit('error', new Error(message));
-};
-
-},{"stream":1715,"util":1776}],265:[function(require,module,exports){
+},{}],222:[function(require,module,exports){
'use strict';
exports.utils = require('./des/utils');
@@ -39775,7 +30457,7 @@ exports.DES = require('./des/des');
exports.CBC = require('./des/cbc');
exports.EDE = require('./des/ede');
-},{"./des/cbc":266,"./des/cipher":267,"./des/des":268,"./des/ede":269,"./des/utils":270}],266:[function(require,module,exports){
+},{"./des/cbc":223,"./des/cipher":224,"./des/des":225,"./des/ede":226,"./des/utils":227}],223:[function(require,module,exports){
'use strict';
var assert = require('minimalistic-assert');
@@ -39842,7 +30524,7 @@ proto._update = function _update(inp, inOff, out, outOff) {
}
};
-},{"inherits":453,"minimalistic-assert":1303}],267:[function(require,module,exports){
+},{"inherits":317,"minimalistic-assert":1129}],224:[function(require,module,exports){
'use strict';
var assert = require('minimalistic-assert');
@@ -39985,7 +30667,7 @@ Cipher.prototype._finalDecrypt = function _finalDecrypt() {
return this._unpad(out);
};
-},{"minimalistic-assert":1303}],268:[function(require,module,exports){
+},{"minimalistic-assert":1129}],225:[function(require,module,exports){
'use strict';
var assert = require('minimalistic-assert');
@@ -40130,7 +30812,7 @@ DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
utils.rip(l, r, out, off);
};
-},{"../des":265,"inherits":453,"minimalistic-assert":1303}],269:[function(require,module,exports){
+},{"../des":222,"inherits":317,"minimalistic-assert":1129}],226:[function(require,module,exports){
'use strict';
var assert = require('minimalistic-assert');
@@ -40187,7 +30869,7 @@ EDE.prototype._update = function _update(inp, inOff, out, outOff) {
EDE.prototype._pad = DES.prototype._pad;
EDE.prototype._unpad = DES.prototype._unpad;
-},{"../des":265,"inherits":453,"minimalistic-assert":1303}],270:[function(require,module,exports){
+},{"../des":222,"inherits":317,"minimalistic-assert":1129}],227:[function(require,module,exports){
'use strict';
exports.readUInt32BE = function readUInt32BE(bytes, off) {
@@ -40445,11 +31127,11 @@ exports.padSplit = function padSplit(num, size, group) {
return out.join(' ');
};
-},{}],271:[function(require,module,exports){
+},{}],228:[function(require,module,exports){
module.exports = false;
-},{}],272:[function(require,module,exports){
+},{}],229:[function(require,module,exports){
(function (Buffer){
var generatePrime = require('./lib/generatePrime')
var primes = require('./lib/primes.json')
@@ -40495,7 +31177,7 @@ exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffi
exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
}).call(this,require("buffer").Buffer)
-},{"./lib/dh":273,"./lib/generatePrime":274,"./lib/primes.json":275,"buffer":217}],273:[function(require,module,exports){
+},{"./lib/dh":230,"./lib/generatePrime":231,"./lib/primes.json":232,"buffer":181}],230:[function(require,module,exports){
(function (Buffer){
var BN = require('bn.js');
var MillerRabin = require('miller-rabin');
@@ -40663,7 +31345,7 @@ function formatReturnValue(bn, enc) {
}
}).call(this,require("buffer").Buffer)
-},{"./generatePrime":274,"bn.js":171,"buffer":217,"miller-rabin":1299,"randombytes":1552}],274:[function(require,module,exports){
+},{"./generatePrime":231,"bn.js":135,"buffer":181,"miller-rabin":1128,"randombytes":1366}],231:[function(require,module,exports){
var randomBytes = require('randombytes');
module.exports = findPrime;
findPrime.simpleSieve = simpleSieve;
@@ -40770,7 +31452,7 @@ function findPrime(bits, gen) {
}
-},{"bn.js":171,"miller-rabin":1299,"randombytes":1552}],275:[function(require,module,exports){
+},{"bn.js":135,"miller-rabin":1128,"randombytes":1366}],232:[function(require,module,exports){
module.exports={
"modp1": {
"gen": "02",
@@ -40805,11 +31487,11 @@ module.exports={
"prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
}
}
-},{}],276:[function(require,module,exports){
+},{}],233:[function(require,module,exports){
!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=function(t,n,e,i,o){for(n=n.split?n.split("."):n,i=0;i= len) ? hex : unstupid("0"+hex,len);
-}
-
-exports.ECKey = function(curve, key, isPublic)
-{
- var priv;
- var c = curve();
- var n = c.getN();
- var bytes = Math.floor(n.bitLength()/8);
-
- if(key)
- {
- if(isPublic)
- {
- var curve = c.getCurve();
-// var x = key.slice(1,bytes+1); // skip the 04 for uncompressed format
-// var y = key.slice(bytes+1);
-// this.P = new ECPointFp(curve,
-// curve.fromBigInteger(new BigInteger(x.toString("hex"), 16)),
-// curve.fromBigInteger(new BigInteger(y.toString("hex"), 16)));
- this.P = curve.decodePointHex(key.toString("hex"));
- }else{
- if(key.length != bytes) return false;
- priv = new BigInteger(key.toString("hex"), 16);
- }
- }else{
- var n1 = n.subtract(BigInteger.ONE);
- var r = new BigInteger(crypto.randomBytes(n.bitLength()));
- priv = r.mod(n1).add(BigInteger.ONE);
- this.P = c.getG().multiply(priv);
- }
- if(this.P)
- {
-// var pubhex = unstupid(this.P.getX().toBigInteger().toString(16),bytes*2)+unstupid(this.P.getY().toBigInteger().toString(16),bytes*2);
-// this.PublicKey = Buffer.from("04"+pubhex,"hex");
- this.PublicKey = Buffer.from(c.getCurve().encodeCompressedPointHex(this.P),"hex");
- }
- if(priv)
- {
- this.PrivateKey = Buffer.from(unstupid(priv.toString(16),bytes*2),"hex");
- this.deriveSharedSecret = function(key)
- {
- if(!key || !key.P) return false;
- var S = key.P.multiply(priv);
- return Buffer.from(unstupid(S.getX().toBigInteger().toString(16),bytes*2),"hex");
- }
- }
-}
-
-
-},{"./lib/ec.js":280,"./lib/sec.js":281,"crypto":236,"jsbn":825,"safer-buffer":1594}],280:[function(require,module,exports){
-// Basic Javascript Elliptic Curve implementation
-// Ported loosely from BouncyCastle's Java EC code
-// Only Fp curves implemented for now
-
-// Requires jsbn.js and jsbn2.js
-var BigInteger = require('jsbn').BigInteger
-var Barrett = BigInteger.prototype.Barrett
-
-// ----------------
-// ECFieldElementFp
-
-// constructor
-function ECFieldElementFp(q,x) {
- this.x = x;
- // TODO if(x.compareTo(q) >= 0) error
- this.q = q;
-}
-
-function feFpEquals(other) {
- if(other == this) return true;
- return (this.q.equals(other.q) && this.x.equals(other.x));
-}
-
-function feFpToBigInteger() {
- return this.x;
-}
-
-function feFpNegate() {
- return new ECFieldElementFp(this.q, this.x.negate().mod(this.q));
-}
-
-function feFpAdd(b) {
- return new ECFieldElementFp(this.q, this.x.add(b.toBigInteger()).mod(this.q));
-}
-
-function feFpSubtract(b) {
- return new ECFieldElementFp(this.q, this.x.subtract(b.toBigInteger()).mod(this.q));
-}
-
-function feFpMultiply(b) {
- return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger()).mod(this.q));
-}
-
-function feFpSquare() {
- return new ECFieldElementFp(this.q, this.x.square().mod(this.q));
-}
-
-function feFpDivide(b) {
- return new ECFieldElementFp(this.q, this.x.multiply(b.toBigInteger().modInverse(this.q)).mod(this.q));
-}
-
-ECFieldElementFp.prototype.equals = feFpEquals;
-ECFieldElementFp.prototype.toBigInteger = feFpToBigInteger;
-ECFieldElementFp.prototype.negate = feFpNegate;
-ECFieldElementFp.prototype.add = feFpAdd;
-ECFieldElementFp.prototype.subtract = feFpSubtract;
-ECFieldElementFp.prototype.multiply = feFpMultiply;
-ECFieldElementFp.prototype.square = feFpSquare;
-ECFieldElementFp.prototype.divide = feFpDivide;
-
-// ----------------
-// ECPointFp
-
-// constructor
-function ECPointFp(curve,x,y,z) {
- this.curve = curve;
- this.x = x;
- this.y = y;
- // Projective coordinates: either zinv == null or z * zinv == 1
- // z and zinv are just BigIntegers, not fieldElements
- if(z == null) {
- this.z = BigInteger.ONE;
- }
- else {
- this.z = z;
- }
- this.zinv = null;
- //TODO: compression flag
-}
-
-function pointFpGetX() {
- if(this.zinv == null) {
- this.zinv = this.z.modInverse(this.curve.q);
- }
- var r = this.x.toBigInteger().multiply(this.zinv);
- this.curve.reduce(r);
- return this.curve.fromBigInteger(r);
-}
-
-function pointFpGetY() {
- if(this.zinv == null) {
- this.zinv = this.z.modInverse(this.curve.q);
- }
- var r = this.y.toBigInteger().multiply(this.zinv);
- this.curve.reduce(r);
- return this.curve.fromBigInteger(r);
-}
-
-function pointFpEquals(other) {
- if(other == this) return true;
- if(this.isInfinity()) return other.isInfinity();
- if(other.isInfinity()) return this.isInfinity();
- var u, v;
- // u = Y2 * Z1 - Y1 * Z2
- u = other.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(other.z)).mod(this.curve.q);
- if(!u.equals(BigInteger.ZERO)) return false;
- // v = X2 * Z1 - X1 * Z2
- v = other.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(other.z)).mod(this.curve.q);
- return v.equals(BigInteger.ZERO);
-}
-
-function pointFpIsInfinity() {
- if((this.x == null) && (this.y == null)) return true;
- return this.z.equals(BigInteger.ZERO) && !this.y.toBigInteger().equals(BigInteger.ZERO);
-}
-
-function pointFpNegate() {
- return new ECPointFp(this.curve, this.x, this.y.negate(), this.z);
-}
-
-function pointFpAdd(b) {
- if(this.isInfinity()) return b;
- if(b.isInfinity()) return this;
-
- // u = Y2 * Z1 - Y1 * Z2
- var u = b.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(b.z)).mod(this.curve.q);
- // v = X2 * Z1 - X1 * Z2
- var v = b.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(b.z)).mod(this.curve.q);
-
- if(BigInteger.ZERO.equals(v)) {
- if(BigInteger.ZERO.equals(u)) {
- return this.twice(); // this == b, so double
- }
- return this.curve.getInfinity(); // this = -b, so infinity
- }
-
- var THREE = new BigInteger("3");
- var x1 = this.x.toBigInteger();
- var y1 = this.y.toBigInteger();
- var x2 = b.x.toBigInteger();
- var y2 = b.y.toBigInteger();
-
- var v2 = v.square();
- var v3 = v2.multiply(v);
- var x1v2 = x1.multiply(v2);
- var zu2 = u.square().multiply(this.z);
-
- // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
- var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.q);
- // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
- var y3 = x1v2.multiply(THREE).multiply(u).subtract(y1.multiply(v3)).subtract(zu2.multiply(u)).multiply(b.z).add(u.multiply(v3)).mod(this.curve.q);
- // z3 = v^3 * z1 * z2
- var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.q);
-
- return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
-}
-
-function pointFpTwice() {
- if(this.isInfinity()) return this;
- if(this.y.toBigInteger().signum() == 0) return this.curve.getInfinity();
-
- // TODO: optimized handling of constants
- var THREE = new BigInteger("3");
- var x1 = this.x.toBigInteger();
- var y1 = this.y.toBigInteger();
-
- var y1z1 = y1.multiply(this.z);
- var y1sqz1 = y1z1.multiply(y1).mod(this.curve.q);
- var a = this.curve.a.toBigInteger();
-
- // w = 3 * x1^2 + a * z1^2
- var w = x1.square().multiply(THREE);
- if(!BigInteger.ZERO.equals(a)) {
- w = w.add(this.z.square().multiply(a));
- }
- w = w.mod(this.curve.q);
- //this.curve.reduce(w);
- // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
- var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.q);
- // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
- var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.square().multiply(w)).mod(this.curve.q);
- // z3 = 8 * (y1 * z1)^3
- var z3 = y1z1.square().multiply(y1z1).shiftLeft(3).mod(this.curve.q);
-
- return new ECPointFp(this.curve, this.curve.fromBigInteger(x3), this.curve.fromBigInteger(y3), z3);
-}
-
-// Simple NAF (Non-Adjacent Form) multiplication algorithm
-// TODO: modularize the multiplication algorithm
-function pointFpMultiply(k) {
- if(this.isInfinity()) return this;
- if(k.signum() == 0) return this.curve.getInfinity();
-
- var e = k;
- var h = e.multiply(new BigInteger("3"));
-
- var neg = this.negate();
- var R = this;
-
- var i;
- for(i = h.bitLength() - 2; i > 0; --i) {
- R = R.twice();
-
- var hBit = h.testBit(i);
- var eBit = e.testBit(i);
-
- if (hBit != eBit) {
- R = R.add(hBit ? this : neg);
- }
- }
-
- return R;
-}
-
-// Compute this*j + x*k (simultaneous multiplication)
-function pointFpMultiplyTwo(j,x,k) {
- var i;
- if(j.bitLength() > k.bitLength())
- i = j.bitLength() - 1;
- else
- i = k.bitLength() - 1;
-
- var R = this.curve.getInfinity();
- var both = this.add(x);
- while(i >= 0) {
- R = R.twice();
- if(j.testBit(i)) {
- if(k.testBit(i)) {
- R = R.add(both);
- }
- else {
- R = R.add(this);
- }
- }
- else {
- if(k.testBit(i)) {
- R = R.add(x);
- }
- }
- --i;
- }
-
- return R;
-}
-
-ECPointFp.prototype.getX = pointFpGetX;
-ECPointFp.prototype.getY = pointFpGetY;
-ECPointFp.prototype.equals = pointFpEquals;
-ECPointFp.prototype.isInfinity = pointFpIsInfinity;
-ECPointFp.prototype.negate = pointFpNegate;
-ECPointFp.prototype.add = pointFpAdd;
-ECPointFp.prototype.twice = pointFpTwice;
-ECPointFp.prototype.multiply = pointFpMultiply;
-ECPointFp.prototype.multiplyTwo = pointFpMultiplyTwo;
-
-// ----------------
-// ECCurveFp
-
-// constructor
-function ECCurveFp(q,a,b) {
- this.q = q;
- this.a = this.fromBigInteger(a);
- this.b = this.fromBigInteger(b);
- this.infinity = new ECPointFp(this, null, null);
- this.reducer = new Barrett(this.q);
-}
-
-function curveFpGetQ() {
- return this.q;
-}
-
-function curveFpGetA() {
- return this.a;
-}
-
-function curveFpGetB() {
- return this.b;
-}
-
-function curveFpEquals(other) {
- if(other == this) return true;
- return(this.q.equals(other.q) && this.a.equals(other.a) && this.b.equals(other.b));
-}
-
-function curveFpGetInfinity() {
- return this.infinity;
-}
-
-function curveFpFromBigInteger(x) {
- return new ECFieldElementFp(this.q, x);
-}
-
-function curveReduce(x) {
- this.reducer.reduce(x);
-}
-
-// for now, work with hex strings because they're easier in JS
-function curveFpDecodePointHex(s) {
- switch(parseInt(s.substr(0,2), 16)) { // first byte
- case 0:
- return this.infinity;
- case 2:
- case 3:
- // point compression not supported yet
- return null;
- case 4:
- case 6:
- case 7:
- var len = (s.length - 2) / 2;
- var xHex = s.substr(2, len);
- var yHex = s.substr(len+2, len);
-
- return new ECPointFp(this,
- this.fromBigInteger(new BigInteger(xHex, 16)),
- this.fromBigInteger(new BigInteger(yHex, 16)));
-
- default: // unsupported
- return null;
- }
-}
-
-function curveFpEncodePointHex(p) {
- if (p.isInfinity()) return "00";
- var xHex = p.getX().toBigInteger().toString(16);
- var yHex = p.getY().toBigInteger().toString(16);
- var oLen = this.getQ().toString(16).length;
- if ((oLen % 2) != 0) oLen++;
- while (xHex.length < oLen) {
- xHex = "0" + xHex;
- }
- while (yHex.length < oLen) {
- yHex = "0" + yHex;
- }
- return "04" + xHex + yHex;
-}
-
-ECCurveFp.prototype.getQ = curveFpGetQ;
-ECCurveFp.prototype.getA = curveFpGetA;
-ECCurveFp.prototype.getB = curveFpGetB;
-ECCurveFp.prototype.equals = curveFpEquals;
-ECCurveFp.prototype.getInfinity = curveFpGetInfinity;
-ECCurveFp.prototype.fromBigInteger = curveFpFromBigInteger;
-ECCurveFp.prototype.reduce = curveReduce;
-//ECCurveFp.prototype.decodePointHex = curveFpDecodePointHex;
-ECCurveFp.prototype.encodePointHex = curveFpEncodePointHex;
-
-// from: https://github.com/kaielvin/jsbn-ec-point-compression
-ECCurveFp.prototype.decodePointHex = function(s)
-{
- var yIsEven;
- switch(parseInt(s.substr(0,2), 16)) { // first byte
- case 0:
- return this.infinity;
- case 2:
- yIsEven = false;
- case 3:
- if(yIsEven == undefined) yIsEven = true;
- var len = s.length - 2;
- var xHex = s.substr(2, len);
- var x = this.fromBigInteger(new BigInteger(xHex,16));
- var alpha = x.multiply(x.square().add(this.getA())).add(this.getB());
- var beta = alpha.sqrt();
-
- if (beta == null) throw "Invalid point compression";
-
- var betaValue = beta.toBigInteger();
- if (betaValue.testBit(0) != yIsEven)
- {
- // Use the other root
- beta = this.fromBigInteger(this.getQ().subtract(betaValue));
- }
- return new ECPointFp(this,x,beta);
- case 4:
- case 6:
- case 7:
- var len = (s.length - 2) / 2;
- var xHex = s.substr(2, len);
- var yHex = s.substr(len+2, len);
-
- return new ECPointFp(this,
- this.fromBigInteger(new BigInteger(xHex, 16)),
- this.fromBigInteger(new BigInteger(yHex, 16)));
-
- default: // unsupported
- return null;
- }
-}
-ECCurveFp.prototype.encodeCompressedPointHex = function(p)
-{
- if (p.isInfinity()) return "00";
- var xHex = p.getX().toBigInteger().toString(16);
- var oLen = this.getQ().toString(16).length;
- if ((oLen % 2) != 0) oLen++;
- while (xHex.length < oLen)
- xHex = "0" + xHex;
- var yPrefix;
- if(p.getY().toBigInteger().isEven()) yPrefix = "02";
- else yPrefix = "03";
-
- return yPrefix + xHex;
-}
-
-
-ECFieldElementFp.prototype.getR = function()
-{
- if(this.r != undefined) return this.r;
-
- this.r = null;
- var bitLength = this.q.bitLength();
- if (bitLength > 128)
- {
- var firstWord = this.q.shiftRight(bitLength - 64);
- if (firstWord.intValue() == -1)
- {
- this.r = BigInteger.ONE.shiftLeft(bitLength).subtract(this.q);
- }
- }
- return this.r;
-}
-ECFieldElementFp.prototype.modMult = function(x1,x2)
-{
- return this.modReduce(x1.multiply(x2));
-}
-ECFieldElementFp.prototype.modReduce = function(x)
-{
- if (this.getR() != null)
- {
- var qLen = q.bitLength();
- while (x.bitLength() > (qLen + 1))
- {
- var u = x.shiftRight(qLen);
- var v = x.subtract(u.shiftLeft(qLen));
- if (!this.getR().equals(BigInteger.ONE))
- {
- u = u.multiply(this.getR());
- }
- x = u.add(v);
- }
- while (x.compareTo(q) >= 0)
- {
- x = x.subtract(q);
- }
- }
- else
- {
- x = x.mod(q);
- }
- return x;
-}
-ECFieldElementFp.prototype.sqrt = function()
-{
- if (!this.q.testBit(0)) throw "unsupported";
-
- // p mod 4 == 3
- if (this.q.testBit(1))
- {
- var z = new ECFieldElementFp(this.q,this.x.modPow(this.q.shiftRight(2).add(BigInteger.ONE),this.q));
- return z.square().equals(this) ? z : null;
- }
-
- // p mod 4 == 1
- var qMinusOne = this.q.subtract(BigInteger.ONE);
-
- var legendreExponent = qMinusOne.shiftRight(1);
- if (!(this.x.modPow(legendreExponent, this.q).equals(BigInteger.ONE)))
- {
- return null;
- }
-
- var u = qMinusOne.shiftRight(2);
- var k = u.shiftLeft(1).add(BigInteger.ONE);
-
- var Q = this.x;
- var fourQ = modDouble(modDouble(Q));
-
- var U, V;
- do
- {
- var P;
- do
- {
- P = new BigInteger(this.q.bitLength(), new SecureRandom());
- }
- while (P.compareTo(this.q) >= 0
- || !(P.multiply(P).subtract(fourQ).modPow(legendreExponent, this.q).equals(qMinusOne)));
-
- var result = this.lucasSequence(P, Q, k);
- U = result[0];
- V = result[1];
-
- if (this.modMult(V, V).equals(fourQ))
- {
- // Integer division by 2, mod q
- if (V.testBit(0))
- {
- V = V.add(q);
- }
-
- V = V.shiftRight(1);
-
- return new ECFieldElementFp(q,V);
- }
- }
- while (U.equals(BigInteger.ONE) || U.equals(qMinusOne));
-
- return null;
-}
-ECFieldElementFp.prototype.lucasSequence = function(P,Q,k)
-{
- var n = k.bitLength();
- var s = k.getLowestSetBit();
-
- var Uh = BigInteger.ONE;
- var Vl = BigInteger.TWO;
- var Vh = P;
- var Ql = BigInteger.ONE;
- var Qh = BigInteger.ONE;
-
- for (var j = n - 1; j >= s + 1; --j)
- {
- Ql = this.modMult(Ql, Qh);
-
- if (k.testBit(j))
- {
- Qh = this.modMult(Ql, Q);
- Uh = this.modMult(Uh, Vh);
- Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
- Vh = this.modReduce(Vh.multiply(Vh).subtract(Qh.shiftLeft(1)));
- }
- else
- {
- Qh = Ql;
- Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
- Vh = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
- Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
- }
- }
-
- Ql = this.modMult(Ql, Qh);
- Qh = this.modMult(Ql, Q);
- Uh = this.modReduce(Uh.multiply(Vl).subtract(Ql));
- Vl = this.modReduce(Vh.multiply(Vl).subtract(P.multiply(Ql)));
- Ql = this.modMult(Ql, Qh);
-
- for (var j = 1; j <= s; ++j)
- {
- Uh = this.modMult(Uh, Vl);
- Vl = this.modReduce(Vl.multiply(Vl).subtract(Ql.shiftLeft(1)));
- Ql = this.modMult(Ql, Ql);
- }
-
- return [ Uh, Vl ];
-}
-
-var exports = {
- ECCurveFp: ECCurveFp,
- ECPointFp: ECPointFp,
- ECFieldElementFp: ECFieldElementFp
-}
-
-module.exports = exports
-
-},{"jsbn":825}],281:[function(require,module,exports){
-// Named EC curves
-
-// Requires ec.js, jsbn.js, and jsbn2.js
-var BigInteger = require('jsbn').BigInteger
-var ECCurveFp = require('./ec.js').ECCurveFp
-
-
-// ----------------
-// X9ECParameters
-
-// constructor
-function X9ECParameters(curve,g,n,h) {
- this.curve = curve;
- this.g = g;
- this.n = n;
- this.h = h;
-}
-
-function x9getCurve() {
- return this.curve;
-}
-
-function x9getG() {
- return this.g;
-}
-
-function x9getN() {
- return this.n;
-}
-
-function x9getH() {
- return this.h;
-}
-
-X9ECParameters.prototype.getCurve = x9getCurve;
-X9ECParameters.prototype.getG = x9getG;
-X9ECParameters.prototype.getN = x9getN;
-X9ECParameters.prototype.getH = x9getH;
-
-// ----------------
-// SECNamedCurves
-
-function fromHex(s) { return new BigInteger(s, 16); }
-
-function secp128r1() {
- // p = 2^128 - 2^97 - 1
- var p = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF");
- var a = fromHex("FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC");
- var b = fromHex("E87579C11079F43DD824993C2CEE5ED3");
- //byte[] S = Hex.decode("000E0D4D696E6768756151750CC03A4473D03679");
- var n = fromHex("FFFFFFFE0000000075A30D1B9038A115");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "161FF7528B899B2D0C28607CA52C5B86"
- + "CF5AC8395BAFEB13C02DA292DDED7A83");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp160k1() {
- // p = 2^160 - 2^32 - 2^14 - 2^12 - 2^9 - 2^8 - 2^7 - 2^3 - 2^2 - 1
- var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73");
- var a = BigInteger.ZERO;
- var b = fromHex("7");
- //byte[] S = null;
- var n = fromHex("0100000000000000000001B8FA16DFAB9ACA16B6B3");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB"
- + "938CF935318FDCED6BC28286531733C3F03C4FEE");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp160r1() {
- // p = 2^160 - 2^31 - 1
- var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF");
- var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC");
- var b = fromHex("1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45");
- //byte[] S = Hex.decode("1053CDE42C14D696E67687561517533BF3F83345");
- var n = fromHex("0100000000000000000001F4C8F927AED3CA752257");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "4A96B5688EF573284664698968C38BB913CBFC82"
- + "23A628553168947D59DCC912042351377AC5FB32");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp192k1() {
- // p = 2^192 - 2^32 - 2^12 - 2^8 - 2^7 - 2^6 - 2^3 - 1
- var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37");
- var a = BigInteger.ZERO;
- var b = fromHex("3");
- //byte[] S = null;
- var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D"
- + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp192r1() {
- // p = 2^192 - 2^64 - 1
- var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF");
- var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC");
- var b = fromHex("64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1");
- //byte[] S = Hex.decode("3045AE6FC8422F64ED579528D38120EAE12196D5");
- var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012"
- + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp224r1() {
- // p = 2^224 - 2^96 + 1
- var p = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001");
- var a = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE");
- var b = fromHex("B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4");
- //byte[] S = Hex.decode("BD71344799D5C7FCDC45B59FA3B9AB8F6A948BC5");
- var n = fromHex("FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21"
- + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34");
- return new X9ECParameters(curve, G, n, h);
-}
-
-function secp256r1() {
- // p = 2^224 (2^32 - 1) + 2^192 + 2^96 - 1
- var p = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF");
- var a = fromHex("FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC");
- var b = fromHex("5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B");
- //byte[] S = Hex.decode("C49D360886E704936A6678E1139D26B7819F7E90");
- var n = fromHex("FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551");
- var h = BigInteger.ONE;
- var curve = new ECCurveFp(p, a, b);
- var G = curve.decodePointHex("04"
- + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"
- + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5");
- return new X9ECParameters(curve, G, n, h);
-}
-
-// TODO: make this into a proper hashtable
-function getSECCurveByName(name) {
- if(name == "secp128r1") return secp128r1();
- if(name == "secp160k1") return secp160k1();
- if(name == "secp160r1") return secp160r1();
- if(name == "secp192k1") return secp192k1();
- if(name == "secp192r1") return secp192r1();
- if(name == "secp224r1") return secp224r1();
- if(name == "secp256r1") return secp256r1();
- return null;
-}
-
-module.exports = {
- "secp128r1":secp128r1,
- "secp160k1":secp160k1,
- "secp160r1":secp160r1,
- "secp192k1":secp192k1,
- "secp192r1":secp192r1,
- "secp224r1":secp224r1,
- "secp256r1":secp256r1
-}
-
-},{"./ec.js":280,"jsbn":825}],282:[function(require,module,exports){
+},{}],236:[function(require,module,exports){
'use strict';
var elliptic = exports;
@@ -41723,7 +31610,7 @@ elliptic.curves = require('./elliptic/curves');
elliptic.ec = require('./elliptic/ec');
elliptic.eddsa = require('./elliptic/eddsa');
-},{"../package.json":297,"./elliptic/curve":285,"./elliptic/curves":288,"./elliptic/ec":289,"./elliptic/eddsa":292,"./elliptic/utils":296,"brorand":181}],283:[function(require,module,exports){
+},{"../package.json":251,"./elliptic/curve":239,"./elliptic/curves":242,"./elliptic/ec":243,"./elliptic/eddsa":246,"./elliptic/utils":250,"brorand":145}],237:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -42099,7 +31986,7 @@ BasePoint.prototype.dblp = function dblp(k) {
return r;
};
-},{"../utils":296,"bn.js":171}],284:[function(require,module,exports){
+},{"../utils":250,"bn.js":135}],238:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -42533,7 +32420,7 @@ Point.prototype.eqXToP = function eqXToP(x) {
Point.prototype.toP = Point.prototype.normalize;
Point.prototype.mixedAdd = Point.prototype.add;
-},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],285:[function(require,module,exports){
+},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],239:[function(require,module,exports){
'use strict';
var curve = exports;
@@ -42543,7 +32430,7 @@ curve.short = require('./short');
curve.mont = require('./mont');
curve.edwards = require('./edwards');
-},{"./base":283,"./edwards":284,"./mont":286,"./short":287}],286:[function(require,module,exports){
+},{"./base":237,"./edwards":238,"./mont":240,"./short":241}],240:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -42723,7 +32610,7 @@ Point.prototype.getX = function getX() {
return this.x.fromRed();
};
-},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],287:[function(require,module,exports){
+},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],241:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -43662,7 +33549,7 @@ JPoint.prototype.isInfinity = function isInfinity() {
return this.z.cmpn(0) === 0;
};
-},{"../utils":296,"./base":283,"bn.js":171,"inherits":453}],288:[function(require,module,exports){
+},{"../utils":250,"./base":237,"bn.js":135,"inherits":317}],242:[function(require,module,exports){
'use strict';
var curves = exports;
@@ -43870,7 +33757,7 @@ defineCurve('secp256k1', {
]
});
-},{"./curve":285,"./precomputed/secp256k1":295,"./utils":296,"hash.js":424}],289:[function(require,module,exports){
+},{"./curve":239,"./precomputed/secp256k1":249,"./utils":250,"hash.js":294}],243:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -44113,7 +34000,7 @@ EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
throw new Error('Unable to find valid recovery factor');
};
-},{"../curves":288,"../utils":296,"./key":290,"./signature":291,"bn.js":171,"brorand":181,"hmac-drbg":440}],290:[function(require,module,exports){
+},{"../curves":242,"../utils":250,"./key":244,"./signature":245,"bn.js":135,"brorand":145,"hmac-drbg":310}],244:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -44233,7 +34120,7 @@ KeyPair.prototype.inspect = function inspect() {
' pub: ' + (this.pub && this.pub.inspect()) + ' >';
};
-},{"../utils":296,"bn.js":171}],291:[function(require,module,exports){
+},{"../utils":250,"bn.js":135}],245:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -44369,7 +34256,7 @@ Signature.prototype.toDER = function toDER(enc) {
return utils.encode(res, enc);
};
-},{"../utils":296,"bn.js":171}],292:[function(require,module,exports){
+},{"../utils":250,"bn.js":135}],246:[function(require,module,exports){
'use strict';
var hash = require('hash.js');
@@ -44489,7 +34376,7 @@ EDDSA.prototype.isPoint = function isPoint(val) {
return val instanceof this.pointClass;
};
-},{"../curves":288,"../utils":296,"./key":293,"./signature":294,"hash.js":424}],293:[function(require,module,exports){
+},{"../curves":242,"../utils":250,"./key":247,"./signature":248,"hash.js":294}],247:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -44586,7 +34473,7 @@ KeyPair.prototype.getPublic = function getPublic(enc) {
module.exports = KeyPair;
-},{"../utils":296}],294:[function(require,module,exports){
+},{"../utils":250}],248:[function(require,module,exports){
'use strict';
var BN = require('bn.js');
@@ -44653,7 +34540,7 @@ Signature.prototype.toHex = function toHex() {
module.exports = Signature;
-},{"../utils":296,"bn.js":171}],295:[function(require,module,exports){
+},{"../utils":250,"bn.js":135}],249:[function(require,module,exports){
module.exports = {
doubles: {
step: 4,
@@ -45435,7 +35322,7 @@ module.exports = {
}
};
-},{}],296:[function(require,module,exports){
+},{}],250:[function(require,module,exports){
'use strict';
var utils = exports;
@@ -45557,51 +35444,45 @@ function intFromLE(bytes) {
utils.intFromLE = intFromLE;
-},{"bn.js":171,"minimalistic-assert":1303,"minimalistic-crypto-utils":1304}],297:[function(require,module,exports){
+},{"bn.js":135,"minimalistic-assert":1129,"minimalistic-crypto-utils":1130}],251:[function(require,module,exports){
module.exports={
"_args": [
[
- "elliptic@^6.0.0",
- "/var/www/html/ethoFSV2/node_modules/browserify-sign"
+ "elliptic@6.5.1",
+ "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet"
]
],
- "_from": "elliptic@>=6.0.0 <7.0.0",
- "_hasShrinkwrap": false,
+ "_from": "elliptic@6.5.1",
"_id": "elliptic@6.5.1",
- "_inCache": true,
- "_installable": true,
+ "_inBundle": false,
+ "_integrity": "sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==",
"_location": "/elliptic",
- "_nodeVersion": "12.2.0",
- "_npmOperationalInternal": {
- "host": "s3://npm-registry-packages",
- "tmp": "tmp/elliptic_6.5.1_1567564470143_0.35768573259267966"
- },
- "_npmUser": {
- "email": "fedor@indutny.com",
- "name": "indutny"
- },
- "_npmVersion": "6.11.2",
"_phantomChildren": {},
"_requested": {
+ "type": "version",
+ "registry": true,
+ "raw": "elliptic@6.5.1",
"name": "elliptic",
- "raw": "elliptic@^6.0.0",
- "rawSpec": "^6.0.0",
- "scope": null,
- "spec": ">=6.0.0 <7.0.0",
- "type": "range"
+ "escapedName": "elliptic",
+ "rawSpec": "6.5.1",
+ "saveSpec": null,
+ "fetchSpec": "6.5.1"
},
"_requiredBy": [
"/browserify-sign",
- "/create-ecdh"
+ "/create-ecdh",
+ "/eth-lib",
+ "/secp256k1",
+ "/tiny-secp256k1",
+ "/web3-eth-accounts/eth-lib",
+ "/web3-utils/eth-lib"
],
"_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz",
- "_shasum": "c380f5f909bf1b9b4428d028cd18d3b0efd6b52b",
- "_shrinkwrap": null,
- "_spec": "elliptic@^6.0.0",
- "_where": "/var/www/html/ethoFSV2/node_modules/browserify-sign",
+ "_spec": "6.5.1",
+ "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet",
"author": {
- "email": "fedor@indutny.com",
- "name": "Fedor Indutny"
+ "name": "Fedor Indutny",
+ "email": "fedor@indutny.com"
},
"bugs": {
"url": "https://github.com/indutny/elliptic/issues"
@@ -45632,34 +35513,19 @@ module.exports={
"jshint": "^2.6.0",
"mocha": "^6.1.4"
},
- "directories": {},
- "dist": {
- "fileCount": 17,
- "integrity": "sha512-xvJINNLbTeWQjrl6X+7eQCrIy/YPv5XCpKW6kB5mKvtnGILoLDcySuwomfdzt0BMdLNVnuRNTuzKNHj0bva1Cg==",
- "npm-signature": "-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.4\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJdbyK2CRA9TVsSAnZWagAAZR0P/jpSTQHkhgrh51Ql5iEp\nk19ZPvn6rvDRJdjPBgZfimuE8jYbzRrqEk0O8OJvWJAgBUz7RGcWsYjXEb0v\ncapOYnS9iL7EGmrZm/zIk2wB4K4vqbY1brh1WSGtZPJOotaTebfrepkUcqrk\nr2ZDg5YryX+gMD2QjumRSb3xXHbQukPvM9cc5WF5ZRaEzgQxRwtwwqzNejs1\np1DzKTNqBWzDGyl3NRdNPO8sEfcaf8LCyCu85OEFR1B7HytR1TH2B1uX7bNb\n82pw62BtmFbafa3VmFxeYk6Yqi5dHXUqsqLIGAsJJyaRsVOyLe/BuT7dHWgX\nEh8bQP4quLm2WZFIIRSUml4QXHiviMyUHfYITg05T/ODZejseHy65LYGgTsS\nQtsu+tDv+a4h+2FWNfkeVyinkEMNetlp+vPkSKVFeNLbCRFTR9ufgZqLn2IL\nnxpLdHLt9y6HaWDSSWwUwUYnK7WRiF8zP1cNRqZWyf7IPLHyRruwpkUFk9/u\nc6J3IgBQpgXfLxxXJTqqDvENmmMGtcJRWN0wtDLWNcYhm5f2px9m5vdxIj0U\nQn+6IZMgxTPsuA4w3iyagWbl/xtuEEw2XZUB++TztGfUtMImRFNEOqI3LO6V\n9CnJKpeVDPckXgDBwHJF9w6ywriLQKyR9rG8hl+nlonSbohg2hdQdB7TTeWJ\n1/J0\r\n=uYn+\r\n-----END PGP SIGNATURE-----\r\n",
- "shasum": "c380f5f909bf1b9b4428d028cd18d3b0efd6b52b",
- "tarball": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.1.tgz",
- "unpackedSize": 118051
- },
- "gitHead": "71e4e8e2f5b8f0bdbfbe106c72cc9fbc746d3d60",
+ "files": [
+ "lib"
+ ],
"homepage": "https://github.com/indutny/elliptic",
"keywords": [
- "Cryptography",
"EC",
"Elliptic",
- "curve"
+ "curve",
+ "Cryptography"
],
"license": "MIT",
"main": "lib/elliptic.js",
- "maintainers": [
- {
- "name": "indutny",
- "email": "fedor@indutny.com"
- }
- ],
"name": "elliptic",
- "optionalDependencies": {},
- "readme": "ERROR: No README data found!",
"repository": {
"type": "git",
"url": "git+ssh://git@github.com/indutny/elliptic.git"
@@ -45675,7 +35541,7 @@ module.exports={
"version": "6.5.1"
}
-},{}],298:[function(require,module,exports){
+},{}],252:[function(require,module,exports){
'use strict'
var AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN
@@ -45684,12 +35550,35 @@ var AbstractIterator = require('abstract-leveldown').AbstractIterator
var inherits = require('inherits')
var Codec = require('level-codec')
var EncodingError = require('level-errors').EncodingError
+var rangeMethods = ['approximateSize', 'compactRange']
module.exports = DB.default = DB
function DB (db, opts) {
if (!(this instanceof DB)) return new DB(db, opts)
- AbstractLevelDOWN.call(this, '')
+
+ var manifest = db.supports || {}
+ var additionalMethods = manifest.additionalMethods || {}
+
+ AbstractLevelDOWN.call(this, manifest)
+
+ this.supports.encodings = true
+ this.supports.additionalMethods = {}
+
+ rangeMethods.forEach(function (m) {
+ // TODO (future major): remove this fallback
+ var fallback = typeof db[m] === 'function'
+
+ if (additionalMethods[m] || fallback) {
+ this.supports.additionalMethods[m] = true
+
+ this[m] = function (start, end, opts, cb) {
+ start = this.codec.encodeKey(start, opts)
+ end = this.codec.encodeKey(end, opts)
+ return this.db[m](start, end, opts, cb)
+ }
+ }
+ }, this)
opts = opts || {}
if (typeof opts.keyEncoding === 'undefined') opts.keyEncoding = 'utf8'
@@ -45701,6 +35590,8 @@ function DB (db, opts) {
inherits(DB, AbstractLevelDOWN)
+DB.prototype.type = 'encoding-down'
+
DB.prototype._serializeKey =
DB.prototype._serializeValue = function (datum) {
return datum
@@ -45760,12 +35651,6 @@ DB.prototype._clear = function (opts, callback) {
this.db.clear(opts, callback)
}
-DB.prototype.approximateSize = function (start, end, opts, cb) {
- start = this.codec.encodeKey(start, opts)
- end = this.codec.encodeKey(end, opts)
- return this.db.approximateSize(start, end, opts, cb)
-}
-
function Iterator (db, opts) {
AbstractIterator.call(this, db)
this.codec = db.codec
@@ -45836,8 +35721,7 @@ Batch.prototype._write = function (opts, cb) {
this.batch.write(opts, cb)
}
-},{"abstract-leveldown":6,"inherits":453,"level-codec":843,"level-errors":845}],299:[function(require,module,exports){
-(function (process){
+},{"abstract-leveldown":6,"inherits":317,"level-codec":677,"level-errors":679}],253:[function(require,module,exports){
var once = require('once');
var noop = function() {};
@@ -45860,7 +35744,6 @@ var eos = function(stream, opts, callback) {
var rs = stream._readableState;
var readable = opts.readable || (opts.readable !== false && stream.readable);
var writable = opts.writable || (opts.writable !== false && stream.writable);
- var cancelled = false;
var onlegacyfinish = function() {
if (!stream.writable) onfinish();
@@ -45885,13 +35768,8 @@ var eos = function(stream, opts, callback) {
};
var onclose = function() {
- process.nextTick(onclosenexttick);
- };
-
- var onclosenexttick = function() {
- if (cancelled) return;
- if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close'));
- if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close'));
+ if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close'));
+ if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close'));
};
var onrequest = function() {
@@ -45916,7 +35794,6 @@ var eos = function(stream, opts, callback) {
stream.on('close', onclose);
return function() {
- cancelled = true;
stream.removeListener('complete', onfinish);
stream.removeListener('abort', onclose);
stream.removeListener('request', onrequest);
@@ -45933,8 +35810,7 @@ var eos = function(stream, opts, callback) {
module.exports = eos;
-}).call(this,require('_process'))
-},{"_process":1438,"once":1394}],300:[function(require,module,exports){
+},{"once":1228}],254:[function(require,module,exports){
module.exports = require('./socket');
@@ -45946,7 +35822,7 @@ module.exports = require('./socket');
*/
module.exports.parser = require('engine.io-parser');
-},{"./socket":301,"engine.io-parser":312}],301:[function(require,module,exports){
+},{"./socket":255,"engine.io-parser":265}],255:[function(require,module,exports){
/**
* Module dependencies.
*/
@@ -46696,7 +36572,7 @@ Socket.prototype.filterUpgrades = function (upgrades) {
return filteredUpgrades;
};
-},{"./transport":302,"./transports/index":303,"component-emitter":227,"debug":309,"engine.io-parser":312,"indexof":452,"parseqs":1423,"parseuri":1424}],302:[function(require,module,exports){
+},{"./transport":256,"./transports/index":257,"component-emitter":189,"debug":263,"engine.io-parser":265,"indexof":316,"parseqs":1244,"parseuri":1245}],256:[function(require,module,exports){
/**
* Module dependencies.
*/
@@ -46859,7 +36735,7 @@ Transport.prototype.onClose = function () {
this.emit('close');
};
-},{"component-emitter":227,"engine.io-parser":312}],303:[function(require,module,exports){
+},{"component-emitter":189,"engine.io-parser":265}],257:[function(require,module,exports){
/**
* Module dependencies
*/
@@ -46914,7 +36790,7 @@ function polling (opts) {
}
}
-},{"./polling-jsonp":304,"./polling-xhr":305,"./websocket":307,"xmlhttprequest-ssl":308}],304:[function(require,module,exports){
+},{"./polling-jsonp":258,"./polling-xhr":259,"./websocket":261,"xmlhttprequest-ssl":262}],258:[function(require,module,exports){
(function (global){
/**
* Module requirements.
@@ -47157,7 +37033,7 @@ JSONPPolling.prototype.doWrite = function (data, fn) {
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./polling":306,"component-inherit":228}],305:[function(require,module,exports){
+},{"./polling":260,"component-inherit":190}],259:[function(require,module,exports){
/* global attachEvent */
/**
@@ -47576,7 +37452,7 @@ function unloadHandler () {
}
}
-},{"./polling":306,"component-emitter":227,"component-inherit":228,"debug":309,"xmlhttprequest-ssl":308}],306:[function(require,module,exports){
+},{"./polling":260,"component-emitter":189,"component-inherit":190,"debug":263,"xmlhttprequest-ssl":262}],260:[function(require,module,exports){
/**
* Module dependencies.
*/
@@ -47823,7 +37699,7 @@ Polling.prototype.uri = function () {
return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
};
-},{"../transport":302,"component-inherit":228,"debug":309,"engine.io-parser":312,"parseqs":1423,"xmlhttprequest-ssl":308,"yeast":1862}],307:[function(require,module,exports){
+},{"../transport":256,"component-inherit":190,"debug":263,"engine.io-parser":265,"parseqs":1244,"xmlhttprequest-ssl":262,"yeast":1529}],261:[function(require,module,exports){
(function (Buffer){
/**
* Module dependencies.
@@ -48122,7 +37998,7 @@ WS.prototype.check = function () {
};
}).call(this,require("buffer").Buffer)
-},{"../transport":302,"buffer":217,"component-inherit":228,"debug":309,"engine.io-parser":312,"parseqs":1423,"ws":182,"yeast":1862}],308:[function(require,module,exports){
+},{"../transport":256,"buffer":181,"component-inherit":190,"debug":263,"engine.io-parser":265,"parseqs":1244,"ws":146,"yeast":1529}],262:[function(require,module,exports){
// browser shim for xmlhttprequest module
var hasCORS = require('has-cors');
@@ -48161,13 +38037,11 @@ module.exports = function (opts) {
}
};
-},{"has-cors":421}],309:[function(require,module,exports){
-arguments[4][247][0].apply(exports,arguments)
-},{"./common":310,"_process":1438,"dup":247}],310:[function(require,module,exports){
-arguments[4][248][0].apply(exports,arguments)
-},{"dup":248,"ms":311}],311:[function(require,module,exports){
-arguments[4][250][0].apply(exports,arguments)
-},{"dup":250}],312:[function(require,module,exports){
+},{"has-cors":292}],263:[function(require,module,exports){
+arguments[4][208][0].apply(exports,arguments)
+},{"./common":264,"_process":1258,"dup":208}],264:[function(require,module,exports){
+arguments[4][209][0].apply(exports,arguments)
+},{"dup":209,"ms":1136}],265:[function(require,module,exports){
/**
* Module dependencies.
*/
@@ -48774,7 +38648,7 @@ exports.decodePayloadAsBinary = function (data, binaryType, callback) {
});
};
-},{"./keys":313,"./utf8":314,"after":7,"arraybuffer.slice":55,"base64-arraybuffer":161,"blob":170,"has-binary2":419}],313:[function(require,module,exports){
+},{"./keys":266,"./utf8":267,"after":8,"arraybuffer.slice":10,"base64-arraybuffer":108,"blob":134,"has-binary2":290}],266:[function(require,module,exports){
/**
* Gets the keys for an object.
@@ -48795,7 +38669,7 @@ module.exports = Object.keys || function keys (obj){
return arr;
};
-},{}],314:[function(require,module,exports){
+},{}],267:[function(require,module,exports){
/*! https://mths.be/utf8js v2.1.2 by @mathias */
var stringFromCharCode = String.fromCharCode;
@@ -49007,7 +38881,7 @@ module.exports = {
decode: utf8decode
};
-},{}],315:[function(require,module,exports){
+},{}],268:[function(require,module,exports){
'use strict';
function createError(err, code, props) {
@@ -49034,7 +38908,7 @@ function createError(err, code, props) {
module.exports = createError;
-},{}],316:[function(require,module,exports){
+},{}],269:[function(require,module,exports){
var prr = require('prr')
function init (type, message, cause) {
@@ -49093,7 +38967,7 @@ module.exports = function (errno) {
}
}
-},{"prr":1455}],317:[function(require,module,exports){
+},{"prr":1275}],270:[function(require,module,exports){
var all = module.exports.all = [
{
errno: -2,
@@ -49408,8857 +39282,7 @@ all.forEach(function (error) {
module.exports.custom = require('./custom')(module.exports)
module.exports.create = module.exports.custom.createError
-},{"./custom":316}],318:[function(require,module,exports){
-'use strict';
-
-/* globals
- Atomics,
- SharedArrayBuffer,
-*/
-
-var undefined; // eslint-disable-line no-shadow-restricted-names
-
-var ThrowTypeError = Object.getOwnPropertyDescriptor
- ? (function () { return Object.getOwnPropertyDescriptor(arguments, 'callee').get; }())
- : function () { throw new TypeError(); };
-
-var hasSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol';
-
-var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
-
-var generator; // = function * () {};
-var generatorFunction = generator ? getProto(generator) : undefined;
-var asyncFn; // async function() {};
-var asyncFunction = asyncFn ? asyncFn.constructor : undefined;
-var asyncGen; // async function * () {};
-var asyncGenFunction = asyncGen ? getProto(asyncGen) : undefined;
-var asyncGenIterator = asyncGen ? asyncGen() : undefined;
-
-var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array);
-
-var INTRINSICS = {
- '$ %Array%': Array,
- '$ %ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer,
- '$ %ArrayBufferPrototype%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer.prototype,
- '$ %ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined,
- '$ %ArrayPrototype%': Array.prototype,
- '$ %ArrayProto_entries%': Array.prototype.entries,
- '$ %ArrayProto_forEach%': Array.prototype.forEach,
- '$ %ArrayProto_keys%': Array.prototype.keys,
- '$ %ArrayProto_values%': Array.prototype.values,
- '$ %AsyncFromSyncIteratorPrototype%': undefined,
- '$ %AsyncFunction%': asyncFunction,
- '$ %AsyncFunctionPrototype%': asyncFunction ? asyncFunction.prototype : undefined,
- '$ %AsyncGenerator%': asyncGen ? getProto(asyncGenIterator) : undefined,
- '$ %AsyncGeneratorFunction%': asyncGenFunction,
- '$ %AsyncGeneratorPrototype%': asyncGenFunction ? asyncGenFunction.prototype : undefined,
- '$ %AsyncIteratorPrototype%': asyncGenIterator && hasSymbols && Symbol.asyncIterator ? asyncGenIterator[Symbol.asyncIterator]() : undefined,
- '$ %Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics,
- '$ %Boolean%': Boolean,
- '$ %BooleanPrototype%': Boolean.prototype,
- '$ %DataView%': typeof DataView === 'undefined' ? undefined : DataView,
- '$ %DataViewPrototype%': typeof DataView === 'undefined' ? undefined : DataView.prototype,
- '$ %Date%': Date,
- '$ %DatePrototype%': Date.prototype,
- '$ %decodeURI%': decodeURI,
- '$ %decodeURIComponent%': decodeURIComponent,
- '$ %encodeURI%': encodeURI,
- '$ %encodeURIComponent%': encodeURIComponent,
- '$ %Error%': Error,
- '$ %ErrorPrototype%': Error.prototype,
- '$ %eval%': eval, // eslint-disable-line no-eval
- '$ %EvalError%': EvalError,
- '$ %EvalErrorPrototype%': EvalError.prototype,
- '$ %Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array,
- '$ %Float32ArrayPrototype%': typeof Float32Array === 'undefined' ? undefined : Float32Array.prototype,
- '$ %Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array,
- '$ %Float64ArrayPrototype%': typeof Float64Array === 'undefined' ? undefined : Float64Array.prototype,
- '$ %Function%': Function,
- '$ %FunctionPrototype%': Function.prototype,
- '$ %Generator%': generator ? getProto(generator()) : undefined,
- '$ %GeneratorFunction%': generatorFunction,
- '$ %GeneratorPrototype%': generatorFunction ? generatorFunction.prototype : undefined,
- '$ %Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array,
- '$ %Int8ArrayPrototype%': typeof Int8Array === 'undefined' ? undefined : Int8Array.prototype,
- '$ %Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array,
- '$ %Int16ArrayPrototype%': typeof Int16Array === 'undefined' ? undefined : Int8Array.prototype,
- '$ %Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array,
- '$ %Int32ArrayPrototype%': typeof Int32Array === 'undefined' ? undefined : Int32Array.prototype,
- '$ %isFinite%': isFinite,
- '$ %isNaN%': isNaN,
- '$ %IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined,
- '$ %JSON%': JSON,
- '$ %JSONParse%': JSON.parse,
- '$ %Map%': typeof Map === 'undefined' ? undefined : Map,
- '$ %MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()),
- '$ %MapPrototype%': typeof Map === 'undefined' ? undefined : Map.prototype,
- '$ %Math%': Math,
- '$ %Number%': Number,
- '$ %NumberPrototype%': Number.prototype,
- '$ %Object%': Object,
- '$ %ObjectPrototype%': Object.prototype,
- '$ %ObjProto_toString%': Object.prototype.toString,
- '$ %ObjProto_valueOf%': Object.prototype.valueOf,
- '$ %parseFloat%': parseFloat,
- '$ %parseInt%': parseInt,
- '$ %Promise%': typeof Promise === 'undefined' ? undefined : Promise,
- '$ %PromisePrototype%': typeof Promise === 'undefined' ? undefined : Promise.prototype,
- '$ %PromiseProto_then%': typeof Promise === 'undefined' ? undefined : Promise.prototype.then,
- '$ %Promise_all%': typeof Promise === 'undefined' ? undefined : Promise.all,
- '$ %Promise_reject%': typeof Promise === 'undefined' ? undefined : Promise.reject,
- '$ %Promise_resolve%': typeof Promise === 'undefined' ? undefined : Promise.resolve,
- '$ %Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy,
- '$ %RangeError%': RangeError,
- '$ %RangeErrorPrototype%': RangeError.prototype,
- '$ %ReferenceError%': ReferenceError,
- '$ %ReferenceErrorPrototype%': ReferenceError.prototype,
- '$ %Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect,
- '$ %RegExp%': RegExp,
- '$ %RegExpPrototype%': RegExp.prototype,
- '$ %Set%': typeof Set === 'undefined' ? undefined : Set,
- '$ %SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()),
- '$ %SetPrototype%': typeof Set === 'undefined' ? undefined : Set.prototype,
- '$ %SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer,
- '$ %SharedArrayBufferPrototype%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer.prototype,
- '$ %String%': String,
- '$ %StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined,
- '$ %StringPrototype%': String.prototype,
- '$ %Symbol%': hasSymbols ? Symbol : undefined,
- '$ %SymbolPrototype%': hasSymbols ? Symbol.prototype : undefined,
- '$ %SyntaxError%': SyntaxError,
- '$ %SyntaxErrorPrototype%': SyntaxError.prototype,
- '$ %ThrowTypeError%': ThrowTypeError,
- '$ %TypedArray%': TypedArray,
- '$ %TypedArrayPrototype%': TypedArray ? TypedArray.prototype : undefined,
- '$ %TypeError%': TypeError,
- '$ %TypeErrorPrototype%': TypeError.prototype,
- '$ %Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array,
- '$ %Uint8ArrayPrototype%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array.prototype,
- '$ %Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray,
- '$ %Uint8ClampedArrayPrototype%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray.prototype,
- '$ %Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array,
- '$ %Uint16ArrayPrototype%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array.prototype,
- '$ %Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array,
- '$ %Uint32ArrayPrototype%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array.prototype,
- '$ %URIError%': URIError,
- '$ %URIErrorPrototype%': URIError.prototype,
- '$ %WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap,
- '$ %WeakMapPrototype%': typeof WeakMap === 'undefined' ? undefined : WeakMap.prototype,
- '$ %WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet,
- '$ %WeakSetPrototype%': typeof WeakSet === 'undefined' ? undefined : WeakSet.prototype
-};
-
-module.exports = function GetIntrinsic(name, allowMissing) {
- if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
- throw new TypeError('"allowMissing" argument must be a boolean');
- }
-
- var key = '$ ' + name;
- if (!(key in INTRINSICS)) {
- throw new SyntaxError('intrinsic ' + name + ' does not exist!');
- }
-
- // istanbul ignore if // hopefully this is impossible to test :-)
- if (typeof INTRINSICS[key] === 'undefined' && !allowMissing) {
- throw new TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
- }
- return INTRINSICS[key];
-};
-
-},{}],319:[function(require,module,exports){
-'use strict';
-
-var GetIntrinsic = require('./GetIntrinsic');
-
-var $Object = GetIntrinsic('%Object%');
-var $TypeError = GetIntrinsic('%TypeError%');
-var $String = GetIntrinsic('%String%');
-var $Number = GetIntrinsic('%Number%');
-
-var assertRecord = require('./helpers/assertRecord');
-var isPropertyDescriptor = require('./helpers/isPropertyDescriptor');
-var $isNaN = require('./helpers/isNaN');
-var $isFinite = require('./helpers/isFinite');
-
-var sign = require('./helpers/sign');
-var mod = require('./helpers/mod');
-
-var IsCallable = require('is-callable');
-var toPrimitive = require('es-to-primitive/es5');
-
-var has = require('has');
-
-var callBind = require('./helpers/callBind');
-var strSlice = callBind($String.prototype.slice);
-
-var isPrefixOf = function isPrefixOf(prefix, string) {
- if (prefix === string) {
- return true;
- }
- if (prefix.length > string.length) {
- return false;
- }
- return strSlice(string, 0, prefix.length) === prefix;
-};
-
-// https://es5.github.io/#x9
-var ES5 = {
- ToPrimitive: toPrimitive,
-
- ToBoolean: function ToBoolean(value) {
- return !!value;
- },
- ToNumber: function ToNumber(value) {
- return +value; // eslint-disable-line no-implicit-coercion
- },
- ToInteger: function ToInteger(value) {
- var number = this.ToNumber(value);
- if ($isNaN(number)) { return 0; }
- if (number === 0 || !$isFinite(number)) { return number; }
- return sign(number) * Math.floor(Math.abs(number));
- },
- ToInt32: function ToInt32(x) {
- return this.ToNumber(x) >> 0;
- },
- ToUint32: function ToUint32(x) {
- return this.ToNumber(x) >>> 0;
- },
- ToUint16: function ToUint16(value) {
- var number = this.ToNumber(value);
- if ($isNaN(number) || number === 0 || !$isFinite(number)) { return 0; }
- var posInt = sign(number) * Math.floor(Math.abs(number));
- return mod(posInt, 0x10000);
- },
- ToString: function ToString(value) {
- return $String(value);
- },
- ToObject: function ToObject(value) {
- this.CheckObjectCoercible(value);
- return $Object(value);
- },
- CheckObjectCoercible: function CheckObjectCoercible(value, optMessage) {
- /* jshint eqnull:true */
- if (value == null) {
- throw new $TypeError(optMessage || 'Cannot call method on ' + value);
- }
- return value;
- },
- IsCallable: IsCallable,
- SameValue: function SameValue(x, y) {
- if (x === y) { // 0 === -0, but they are not identical.
- if (x === 0) { return 1 / x === 1 / y; }
- return true;
- }
- return $isNaN(x) && $isNaN(y);
- },
-
- // https://www.ecma-international.org/ecma-262/5.1/#sec-8
- Type: function Type(x) {
- if (x === null) {
- return 'Null';
- }
- if (typeof x === 'undefined') {
- return 'Undefined';
- }
- if (typeof x === 'function' || typeof x === 'object') {
- return 'Object';
- }
- if (typeof x === 'number') {
- return 'Number';
- }
- if (typeof x === 'boolean') {
- return 'Boolean';
- }
- if (typeof x === 'string') {
- return 'String';
- }
- },
-
- // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
- IsPropertyDescriptor: function IsPropertyDescriptor(Desc) {
- return isPropertyDescriptor(this, Desc);
- },
-
- // https://ecma-international.org/ecma-262/5.1/#sec-8.10.1
- IsAccessorDescriptor: function IsAccessorDescriptor(Desc) {
- if (typeof Desc === 'undefined') {
- return false;
- }
-
- assertRecord(this, 'Property Descriptor', 'Desc', Desc);
-
- if (!has(Desc, '[[Get]]') && !has(Desc, '[[Set]]')) {
- return false;
- }
-
- return true;
- },
-
- // https://ecma-international.org/ecma-262/5.1/#sec-8.10.2
- IsDataDescriptor: function IsDataDescriptor(Desc) {
- if (typeof Desc === 'undefined') {
- return false;
- }
-
- assertRecord(this, 'Property Descriptor', 'Desc', Desc);
-
- if (!has(Desc, '[[Value]]') && !has(Desc, '[[Writable]]')) {
- return false;
- }
-
- return true;
- },
-
- // https://ecma-international.org/ecma-262/5.1/#sec-8.10.3
- IsGenericDescriptor: function IsGenericDescriptor(Desc) {
- if (typeof Desc === 'undefined') {
- return false;
- }
-
- assertRecord(this, 'Property Descriptor', 'Desc', Desc);
-
- if (!this.IsAccessorDescriptor(Desc) && !this.IsDataDescriptor(Desc)) {
- return true;
- }
-
- return false;
- },
-
- // https://ecma-international.org/ecma-262/5.1/#sec-8.10.4
- FromPropertyDescriptor: function FromPropertyDescriptor(Desc) {
- if (typeof Desc === 'undefined') {
- return Desc;
- }
-
- assertRecord(this, 'Property Descriptor', 'Desc', Desc);
-
- if (this.IsDataDescriptor(Desc)) {
- return {
- value: Desc['[[Value]]'],
- writable: !!Desc['[[Writable]]'],
- enumerable: !!Desc['[[Enumerable]]'],
- configurable: !!Desc['[[Configurable]]']
- };
- } else if (this.IsAccessorDescriptor(Desc)) {
- return {
- get: Desc['[[Get]]'],
- set: Desc['[[Set]]'],
- enumerable: !!Desc['[[Enumerable]]'],
- configurable: !!Desc['[[Configurable]]']
- };
- } else {
- throw new $TypeError('FromPropertyDescriptor must be called with a fully populated Property Descriptor');
- }
- },
-
- // https://ecma-international.org/ecma-262/5.1/#sec-8.10.5
- ToPropertyDescriptor: function ToPropertyDescriptor(Obj) {
- if (this.Type(Obj) !== 'Object') {
- throw new $TypeError('ToPropertyDescriptor requires an object');
- }
-
- var desc = {};
- if (has(Obj, 'enumerable')) {
- desc['[[Enumerable]]'] = this.ToBoolean(Obj.enumerable);
- }
- if (has(Obj, 'configurable')) {
- desc['[[Configurable]]'] = this.ToBoolean(Obj.configurable);
- }
- if (has(Obj, 'value')) {
- desc['[[Value]]'] = Obj.value;
- }
- if (has(Obj, 'writable')) {
- desc['[[Writable]]'] = this.ToBoolean(Obj.writable);
- }
- if (has(Obj, 'get')) {
- var getter = Obj.get;
- if (typeof getter !== 'undefined' && !this.IsCallable(getter)) {
- throw new TypeError('getter must be a function');
- }
- desc['[[Get]]'] = getter;
- }
- if (has(Obj, 'set')) {
- var setter = Obj.set;
- if (typeof setter !== 'undefined' && !this.IsCallable(setter)) {
- throw new $TypeError('setter must be a function');
- }
- desc['[[Set]]'] = setter;
- }
-
- if ((has(desc, '[[Get]]') || has(desc, '[[Set]]')) && (has(desc, '[[Value]]') || has(desc, '[[Writable]]'))) {
- throw new $TypeError('Invalid property descriptor. Cannot both specify accessors and a value or writable attribute');
- }
- return desc;
- },
-
- // https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
- 'Abstract Equality Comparison': function AbstractEqualityComparison(x, y) {
- var xType = this.Type(x);
- var yType = this.Type(y);
- if (xType === yType) {
- return x === y; // ES6+ specified this shortcut anyways.
- }
- if (x == null && y == null) {
- return true;
- }
- if (xType === 'Number' && yType === 'String') {
- return this['Abstract Equality Comparison'](x, this.ToNumber(y));
- }
- if (xType === 'String' && yType === 'Number') {
- return this['Abstract Equality Comparison'](this.ToNumber(x), y);
- }
- if (xType === 'Boolean') {
- return this['Abstract Equality Comparison'](this.ToNumber(x), y);
- }
- if (yType === 'Boolean') {
- return this['Abstract Equality Comparison'](x, this.ToNumber(y));
- }
- if ((xType === 'String' || xType === 'Number') && yType === 'Object') {
- return this['Abstract Equality Comparison'](x, this.ToPrimitive(y));
- }
- if (xType === 'Object' && (yType === 'String' || yType === 'Number')) {
- return this['Abstract Equality Comparison'](this.ToPrimitive(x), y);
- }
- return false;
- },
-
- // https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6
- 'Strict Equality Comparison': function StrictEqualityComparison(x, y) {
- var xType = this.Type(x);
- var yType = this.Type(y);
- if (xType !== yType) {
- return false;
- }
- if (xType === 'Undefined' || xType === 'Null') {
- return true;
- }
- return x === y; // shortcut for steps 4-7
- },
-
- // https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.5
- // eslint-disable-next-line max-statements
- 'Abstract Relational Comparison': function AbstractRelationalComparison(x, y, LeftFirst) {
- if (this.Type(LeftFirst) !== 'Boolean') {
- throw new $TypeError('Assertion failed: LeftFirst argument must be a Boolean');
- }
- var px;
- var py;
- if (LeftFirst) {
- px = this.ToPrimitive(x, $Number);
- py = this.ToPrimitive(y, $Number);
- } else {
- py = this.ToPrimitive(y, $Number);
- px = this.ToPrimitive(x, $Number);
- }
- var bothStrings = this.Type(px) === 'String' && this.Type(py) === 'String';
- if (!bothStrings) {
- var nx = this.ToNumber(px);
- var ny = this.ToNumber(py);
- if ($isNaN(nx) || $isNaN(ny)) {
- return undefined;
- }
- if ($isFinite(nx) && $isFinite(ny) && nx === ny) {
- return false;
- }
- if (nx === 0 && ny === 0) {
- return false;
- }
- if (nx === Infinity) {
- return false;
- }
- if (ny === Infinity) {
- return true;
- }
- if (ny === -Infinity) {
- return false;
- }
- if (nx === -Infinity) {
- return true;
- }
- return nx < ny; // by now, these are both nonzero, finite, and not equal
- }
- if (isPrefixOf(py, px)) {
- return false;
- }
- if (isPrefixOf(px, py)) {
- return true;
- }
- return px < py; // both strings, neither a prefix of the other. shortcut for steps c-f
- }
-};
-
-module.exports = ES5;
-
-},{"./GetIntrinsic":318,"./helpers/assertRecord":320,"./helpers/callBind":321,"./helpers/isFinite":322,"./helpers/isNaN":323,"./helpers/isPropertyDescriptor":324,"./helpers/mod":325,"./helpers/sign":326,"es-to-primitive/es5":327,"has":422,"is-callable":767}],320:[function(require,module,exports){
-'use strict';
-
-var GetIntrinsic = require('../GetIntrinsic');
-
-var $TypeError = GetIntrinsic('%TypeError%');
-var $SyntaxError = GetIntrinsic('%SyntaxError%');
-
-var has = require('has');
-
-var predicates = {
- // https://ecma-international.org/ecma-262/6.0/#sec-property-descriptor-specification-type
- 'Property Descriptor': function isPropertyDescriptor(ES, Desc) {
- if (ES.Type(Desc) !== 'Object') {
- return false;
- }
- var allowed = {
- '[[Configurable]]': true,
- '[[Enumerable]]': true,
- '[[Get]]': true,
- '[[Set]]': true,
- '[[Value]]': true,
- '[[Writable]]': true
- };
-
- for (var key in Desc) { // eslint-disable-line
- if (has(Desc, key) && !allowed[key]) {
- return false;
- }
- }
-
- var isData = has(Desc, '[[Value]]');
- var IsAccessor = has(Desc, '[[Get]]') || has(Desc, '[[Set]]');
- if (isData && IsAccessor) {
- throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
- }
- return true;
- }
-};
-
-module.exports = function assertRecord(ES, recordType, argumentName, value) {
- var predicate = predicates[recordType];
- if (typeof predicate !== 'function') {
- throw new $SyntaxError('unknown record type: ' + recordType);
- }
- if (!predicate(ES, value)) {
- throw new $TypeError(argumentName + ' must be a ' + recordType);
- }
-};
-
-},{"../GetIntrinsic":318,"has":422}],321:[function(require,module,exports){
-'use strict';
-
-var bind = require('function-bind');
-
-var GetIntrinsic = require('../GetIntrinsic');
-
-var $Function = GetIntrinsic('%Function%');
-var $apply = $Function.apply;
-var $call = $Function.call;
-
-module.exports = function callBind() {
- return bind.apply($call, arguments);
-};
-
-module.exports.apply = function applyBind() {
- return bind.apply($apply, arguments);
-};
-
-},{"../GetIntrinsic":318,"function-bind":386}],322:[function(require,module,exports){
-'use strict';
-
-var $isNaN = Number.isNaN || function (a) { return a !== a; };
-
-module.exports = Number.isFinite || function (x) { return typeof x === 'number' && !$isNaN(x) && x !== Infinity && x !== -Infinity; };
-
-},{}],323:[function(require,module,exports){
-'use strict';
-
-module.exports = Number.isNaN || function isNaN(a) {
- return a !== a;
-};
-
-},{}],324:[function(require,module,exports){
-'use strict';
-
-var GetIntrinsic = require('../GetIntrinsic');
-
-var has = require('has');
-var $TypeError = GetIntrinsic('%TypeError%');
-
-module.exports = function IsPropertyDescriptor(ES, Desc) {
- if (ES.Type(Desc) !== 'Object') {
- return false;
- }
- var allowed = {
- '[[Configurable]]': true,
- '[[Enumerable]]': true,
- '[[Get]]': true,
- '[[Set]]': true,
- '[[Value]]': true,
- '[[Writable]]': true
- };
-
- for (var key in Desc) { // eslint-disable-line
- if (has(Desc, key) && !allowed[key]) {
- return false;
- }
- }
-
- if (ES.IsDataDescriptor(Desc) && ES.IsAccessorDescriptor(Desc)) {
- throw new $TypeError('Property Descriptors may not be both accessor and data descriptors');
- }
- return true;
-};
-
-},{"../GetIntrinsic":318,"has":422}],325:[function(require,module,exports){
-'use strict';
-
-module.exports = function mod(number, modulo) {
- var remain = number % modulo;
- return Math.floor(remain >= 0 ? remain : remain + modulo);
-};
-
-},{}],326:[function(require,module,exports){
-'use strict';
-
-module.exports = function sign(number) {
- return number >= 0 ? 1 : -1;
-};
-
-},{}],327:[function(require,module,exports){
-'use strict';
-
-var toStr = Object.prototype.toString;
-
-var isPrimitive = require('./helpers/isPrimitive');
-
-var isCallable = require('is-callable');
-
-// http://ecma-international.org/ecma-262/5.1/#sec-8.12.8
-var ES5internalSlots = {
- '[[DefaultValue]]': function (O) {
- var actualHint;
- if (arguments.length > 1) {
- actualHint = arguments[1];
- } else {
- actualHint = toStr.call(O) === '[object Date]' ? String : Number;
- }
-
- if (actualHint === String || actualHint === Number) {
- var methods = actualHint === String ? ['toString', 'valueOf'] : ['valueOf', 'toString'];
- var value, i;
- for (i = 0; i < methods.length; ++i) {
- if (isCallable(O[methods[i]])) {
- value = O[methods[i]]();
- if (isPrimitive(value)) {
- return value;
- }
- }
- }
- throw new TypeError('No default value');
- }
- throw new TypeError('invalid [[DefaultValue]] hint supplied');
- }
-};
-
-// http://ecma-international.org/ecma-262/5.1/#sec-9.1
-module.exports = function ToPrimitive(input) {
- if (isPrimitive(input)) {
- return input;
- }
- if (arguments.length > 1) {
- return ES5internalSlots['[[DefaultValue]]'](input, arguments[1]);
- }
- return ES5internalSlots['[[DefaultValue]]'](input);
-};
-
-},{"./helpers/isPrimitive":328,"is-callable":767}],328:[function(require,module,exports){
-module.exports = function isPrimitive(value) {
- return value === null || (typeof value !== 'function' && typeof value !== 'object');
-};
-
-},{}],329:[function(require,module,exports){
-module.exports = (function () {
- if (this) return this;
-
- // Unexpected strict mode (may happen if e.g. bundled into ESM module), be nice
-
- // Thanks @mathiasbynens -> https://mathiasbynens.be/notes/globalthis
- // In all ES5+ engines global object inherits from Object.prototype
- // (if you approached one that doesn't please report)
- Object.defineProperty(Object.prototype, "__global__", {
- get: function () { return this; },
- configurable: true
- });
- try { return __global__; }
- finally { delete Object.prototype.__global__; }
-})();
-
-},{}],330:[function(require,module,exports){
-(function (Buffer){
-var sha3 = require('js-sha3').keccak_256
-var uts46 = require('idna-uts46-hx')
-
-function namehash (inputName) {
- // Reject empty names:
- var node = ''
- for (var i = 0; i < 32; i++) {
- node += '00'
- }
-
- name = normalize(inputName)
-
- if (name) {
- var labels = name.split('.')
-
- for(var i = labels.length - 1; i >= 0; i--) {
- var labelSha = sha3(labels[i])
- node = sha3(new Buffer(node + labelSha, 'hex'))
- }
- }
-
- return '0x' + node
-}
-
-function normalize(name) {
- return name ? uts46.toUnicode(name, {useStd3ASCII: true, transitional: false}) : name
-}
-
-exports.hash = namehash
-exports.normalize = normalize
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":217,"idna-uts46-hx":450,"js-sha3":331}],331:[function(require,module,exports){
-(function (process,global){
-/**
- * [js-sha3]{@link https://github.com/emn178/js-sha3}
- *
- * @version 0.5.7
- * @author Chen, Yi-Cyuan [emn178@gmail.com]
- * @copyright Chen, Yi-Cyuan 2015-2016
- * @license MIT
- */
-/*jslint bitwise: true */
-(function () {
- 'use strict';
-
- var root = typeof window === 'object' ? window : {};
- var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
- if (NODE_JS) {
- root = global;
- }
- var COMMON_JS = !root.JS_SHA3_NO_COMMON_JS && typeof module === 'object' && module.exports;
- var HEX_CHARS = '0123456789abcdef'.split('');
- var SHAKE_PADDING = [31, 7936, 2031616, 520093696];
- var KECCAK_PADDING = [1, 256, 65536, 16777216];
- var PADDING = [6, 1536, 393216, 100663296];
- var SHIFT = [0, 8, 16, 24];
- var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649,
- 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0,
- 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771,
- 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648,
- 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
- var BITS = [224, 256, 384, 512];
- var SHAKE_BITS = [128, 256];
- var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array'];
-
- var createOutputMethod = function (bits, padding, outputType) {
- return function (message) {
- return new Keccak(bits, padding, bits).update(message)[outputType]();
- };
- };
-
- var createShakeOutputMethod = function (bits, padding, outputType) {
- return function (message, outputBits) {
- return new Keccak(bits, padding, outputBits).update(message)[outputType]();
- };
- };
-
- var createMethod = function (bits, padding) {
- var method = createOutputMethod(bits, padding, 'hex');
- method.create = function () {
- return new Keccak(bits, padding, bits);
- };
- method.update = function (message) {
- return method.create().update(message);
- };
- for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
- var type = OUTPUT_TYPES[i];
- method[type] = createOutputMethod(bits, padding, type);
- }
- return method;
- };
-
- var createShakeMethod = function (bits, padding) {
- var method = createShakeOutputMethod(bits, padding, 'hex');
- method.create = function (outputBits) {
- return new Keccak(bits, padding, outputBits);
- };
- method.update = function (message, outputBits) {
- return method.create(outputBits).update(message);
- };
- for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
- var type = OUTPUT_TYPES[i];
- method[type] = createShakeOutputMethod(bits, padding, type);
- }
- return method;
- };
-
- var algorithms = [
- {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod},
- {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod},
- {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod}
- ];
-
- var methods = {}, methodNames = [];
-
- for (var i = 0; i < algorithms.length; ++i) {
- var algorithm = algorithms[i];
- var bits = algorithm.bits;
- for (var j = 0; j < bits.length; ++j) {
- var methodName = algorithm.name +'_' + bits[j];
- methodNames.push(methodName);
- methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding);
- }
- }
-
- function Keccak(bits, padding, outputBits) {
- this.blocks = [];
- this.s = [];
- this.padding = padding;
- this.outputBits = outputBits;
- this.reset = true;
- this.block = 0;
- this.start = 0;
- this.blockCount = (1600 - (bits << 1)) >> 5;
- this.byteCount = this.blockCount << 2;
- this.outputBlocks = outputBits >> 5;
- this.extraBytes = (outputBits & 31) >> 3;
-
- for (var i = 0; i < 50; ++i) {
- this.s[i] = 0;
- }
- }
-
- Keccak.prototype.update = function (message) {
- var notString = typeof message !== 'string';
- if (notString && message.constructor === ArrayBuffer) {
- message = new Uint8Array(message);
- }
- var length = message.length, blocks = this.blocks, byteCount = this.byteCount,
- blockCount = this.blockCount, index = 0, s = this.s, i, code;
-
- while (index < length) {
- if (this.reset) {
- this.reset = false;
- blocks[0] = this.block;
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- if (notString) {
- for (i = this.start; index < length && i < byteCount; ++index) {
- blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
- }
- } else {
- for (i = this.start; index < length && i < byteCount; ++index) {
- code = message.charCodeAt(index);
- if (code < 0x80) {
- blocks[i >> 2] |= code << SHIFT[i++ & 3];
- } else if (code < 0x800) {
- blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- } else if (code < 0xd800 || code >= 0xe000) {
- blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- } else {
- code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
- blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
- }
- }
- }
- this.lastByteIndex = i;
- if (i >= byteCount) {
- this.start = i - byteCount;
- this.block = blocks[blockCount];
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
- this.reset = true;
- } else {
- this.start = i;
- }
- }
- return this;
- };
-
- Keccak.prototype.finalize = function () {
- var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s;
- blocks[i >> 2] |= this.padding[i & 3];
- if (this.lastByteIndex === this.byteCount) {
- blocks[0] = blocks[blockCount];
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- blocks[blockCount - 1] |= 0x80000000;
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
- };
-
- Keccak.prototype.toString = Keccak.prototype.hex = function () {
- this.finalize();
-
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var hex = '', block;
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- block = s[i];
- hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F] +
- HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F] +
- HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F] +
- HEX_CHARS[(block >> 28) & 0x0F] + HEX_CHARS[(block >> 24) & 0x0F];
- }
- if (j % blockCount === 0) {
- f(s);
- i = 0;
- }
- }
- if (extraBytes) {
- block = s[i];
- if (extraBytes > 0) {
- hex += HEX_CHARS[(block >> 4) & 0x0F] + HEX_CHARS[block & 0x0F];
- }
- if (extraBytes > 1) {
- hex += HEX_CHARS[(block >> 12) & 0x0F] + HEX_CHARS[(block >> 8) & 0x0F];
- }
- if (extraBytes > 2) {
- hex += HEX_CHARS[(block >> 20) & 0x0F] + HEX_CHARS[(block >> 16) & 0x0F];
- }
- }
- return hex;
- };
-
- Keccak.prototype.arrayBuffer = function () {
- this.finalize();
-
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var bytes = this.outputBits >> 3;
- var buffer;
- if (extraBytes) {
- buffer = new ArrayBuffer((outputBlocks + 1) << 2);
- } else {
- buffer = new ArrayBuffer(bytes);
- }
- var array = new Uint32Array(buffer);
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- array[j] = s[i];
- }
- if (j % blockCount === 0) {
- f(s);
- }
- }
- if (extraBytes) {
- array[i] = s[i];
- buffer = buffer.slice(0, bytes);
- }
- return buffer;
- };
-
- Keccak.prototype.buffer = Keccak.prototype.arrayBuffer;
-
- Keccak.prototype.digest = Keccak.prototype.array = function () {
- this.finalize();
-
- var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks,
- extraBytes = this.extraBytes, i = 0, j = 0;
- var array = [], offset, block;
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- offset = j << 2;
- block = s[i];
- array[offset] = block & 0xFF;
- array[offset + 1] = (block >> 8) & 0xFF;
- array[offset + 2] = (block >> 16) & 0xFF;
- array[offset + 3] = (block >> 24) & 0xFF;
- }
- if (j % blockCount === 0) {
- f(s);
- }
- }
- if (extraBytes) {
- offset = j << 2;
- block = s[i];
- if (extraBytes > 0) {
- array[offset] = block & 0xFF;
- }
- if (extraBytes > 1) {
- array[offset + 1] = (block >> 8) & 0xFF;
- }
- if (extraBytes > 2) {
- array[offset + 2] = (block >> 16) & 0xFF;
- }
- }
- return array;
- };
-
- var f = function (s) {
- var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9,
- b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17,
- b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33,
- b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
- for (n = 0; n < 48; n += 2) {
- c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
- c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
- c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
- c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
- c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
- c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
- c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
- c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
- c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
- c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
-
- h = c8 ^ ((c2 << 1) | (c3 >>> 31));
- l = c9 ^ ((c3 << 1) | (c2 >>> 31));
- s[0] ^= h;
- s[1] ^= l;
- s[10] ^= h;
- s[11] ^= l;
- s[20] ^= h;
- s[21] ^= l;
- s[30] ^= h;
- s[31] ^= l;
- s[40] ^= h;
- s[41] ^= l;
- h = c0 ^ ((c4 << 1) | (c5 >>> 31));
- l = c1 ^ ((c5 << 1) | (c4 >>> 31));
- s[2] ^= h;
- s[3] ^= l;
- s[12] ^= h;
- s[13] ^= l;
- s[22] ^= h;
- s[23] ^= l;
- s[32] ^= h;
- s[33] ^= l;
- s[42] ^= h;
- s[43] ^= l;
- h = c2 ^ ((c6 << 1) | (c7 >>> 31));
- l = c3 ^ ((c7 << 1) | (c6 >>> 31));
- s[4] ^= h;
- s[5] ^= l;
- s[14] ^= h;
- s[15] ^= l;
- s[24] ^= h;
- s[25] ^= l;
- s[34] ^= h;
- s[35] ^= l;
- s[44] ^= h;
- s[45] ^= l;
- h = c4 ^ ((c8 << 1) | (c9 >>> 31));
- l = c5 ^ ((c9 << 1) | (c8 >>> 31));
- s[6] ^= h;
- s[7] ^= l;
- s[16] ^= h;
- s[17] ^= l;
- s[26] ^= h;
- s[27] ^= l;
- s[36] ^= h;
- s[37] ^= l;
- s[46] ^= h;
- s[47] ^= l;
- h = c6 ^ ((c0 << 1) | (c1 >>> 31));
- l = c7 ^ ((c1 << 1) | (c0 >>> 31));
- s[8] ^= h;
- s[9] ^= l;
- s[18] ^= h;
- s[19] ^= l;
- s[28] ^= h;
- s[29] ^= l;
- s[38] ^= h;
- s[39] ^= l;
- s[48] ^= h;
- s[49] ^= l;
-
- b0 = s[0];
- b1 = s[1];
- b32 = (s[11] << 4) | (s[10] >>> 28);
- b33 = (s[10] << 4) | (s[11] >>> 28);
- b14 = (s[20] << 3) | (s[21] >>> 29);
- b15 = (s[21] << 3) | (s[20] >>> 29);
- b46 = (s[31] << 9) | (s[30] >>> 23);
- b47 = (s[30] << 9) | (s[31] >>> 23);
- b28 = (s[40] << 18) | (s[41] >>> 14);
- b29 = (s[41] << 18) | (s[40] >>> 14);
- b20 = (s[2] << 1) | (s[3] >>> 31);
- b21 = (s[3] << 1) | (s[2] >>> 31);
- b2 = (s[13] << 12) | (s[12] >>> 20);
- b3 = (s[12] << 12) | (s[13] >>> 20);
- b34 = (s[22] << 10) | (s[23] >>> 22);
- b35 = (s[23] << 10) | (s[22] >>> 22);
- b16 = (s[33] << 13) | (s[32] >>> 19);
- b17 = (s[32] << 13) | (s[33] >>> 19);
- b48 = (s[42] << 2) | (s[43] >>> 30);
- b49 = (s[43] << 2) | (s[42] >>> 30);
- b40 = (s[5] << 30) | (s[4] >>> 2);
- b41 = (s[4] << 30) | (s[5] >>> 2);
- b22 = (s[14] << 6) | (s[15] >>> 26);
- b23 = (s[15] << 6) | (s[14] >>> 26);
- b4 = (s[25] << 11) | (s[24] >>> 21);
- b5 = (s[24] << 11) | (s[25] >>> 21);
- b36 = (s[34] << 15) | (s[35] >>> 17);
- b37 = (s[35] << 15) | (s[34] >>> 17);
- b18 = (s[45] << 29) | (s[44] >>> 3);
- b19 = (s[44] << 29) | (s[45] >>> 3);
- b10 = (s[6] << 28) | (s[7] >>> 4);
- b11 = (s[7] << 28) | (s[6] >>> 4);
- b42 = (s[17] << 23) | (s[16] >>> 9);
- b43 = (s[16] << 23) | (s[17] >>> 9);
- b24 = (s[26] << 25) | (s[27] >>> 7);
- b25 = (s[27] << 25) | (s[26] >>> 7);
- b6 = (s[36] << 21) | (s[37] >>> 11);
- b7 = (s[37] << 21) | (s[36] >>> 11);
- b38 = (s[47] << 24) | (s[46] >>> 8);
- b39 = (s[46] << 24) | (s[47] >>> 8);
- b30 = (s[8] << 27) | (s[9] >>> 5);
- b31 = (s[9] << 27) | (s[8] >>> 5);
- b12 = (s[18] << 20) | (s[19] >>> 12);
- b13 = (s[19] << 20) | (s[18] >>> 12);
- b44 = (s[29] << 7) | (s[28] >>> 25);
- b45 = (s[28] << 7) | (s[29] >>> 25);
- b26 = (s[38] << 8) | (s[39] >>> 24);
- b27 = (s[39] << 8) | (s[38] >>> 24);
- b8 = (s[48] << 14) | (s[49] >>> 18);
- b9 = (s[49] << 14) | (s[48] >>> 18);
-
- s[0] = b0 ^ (~b2 & b4);
- s[1] = b1 ^ (~b3 & b5);
- s[10] = b10 ^ (~b12 & b14);
- s[11] = b11 ^ (~b13 & b15);
- s[20] = b20 ^ (~b22 & b24);
- s[21] = b21 ^ (~b23 & b25);
- s[30] = b30 ^ (~b32 & b34);
- s[31] = b31 ^ (~b33 & b35);
- s[40] = b40 ^ (~b42 & b44);
- s[41] = b41 ^ (~b43 & b45);
- s[2] = b2 ^ (~b4 & b6);
- s[3] = b3 ^ (~b5 & b7);
- s[12] = b12 ^ (~b14 & b16);
- s[13] = b13 ^ (~b15 & b17);
- s[22] = b22 ^ (~b24 & b26);
- s[23] = b23 ^ (~b25 & b27);
- s[32] = b32 ^ (~b34 & b36);
- s[33] = b33 ^ (~b35 & b37);
- s[42] = b42 ^ (~b44 & b46);
- s[43] = b43 ^ (~b45 & b47);
- s[4] = b4 ^ (~b6 & b8);
- s[5] = b5 ^ (~b7 & b9);
- s[14] = b14 ^ (~b16 & b18);
- s[15] = b15 ^ (~b17 & b19);
- s[24] = b24 ^ (~b26 & b28);
- s[25] = b25 ^ (~b27 & b29);
- s[34] = b34 ^ (~b36 & b38);
- s[35] = b35 ^ (~b37 & b39);
- s[44] = b44 ^ (~b46 & b48);
- s[45] = b45 ^ (~b47 & b49);
- s[6] = b6 ^ (~b8 & b0);
- s[7] = b7 ^ (~b9 & b1);
- s[16] = b16 ^ (~b18 & b10);
- s[17] = b17 ^ (~b19 & b11);
- s[26] = b26 ^ (~b28 & b20);
- s[27] = b27 ^ (~b29 & b21);
- s[36] = b36 ^ (~b38 & b30);
- s[37] = b37 ^ (~b39 & b31);
- s[46] = b46 ^ (~b48 & b40);
- s[47] = b47 ^ (~b49 & b41);
- s[8] = b8 ^ (~b0 & b2);
- s[9] = b9 ^ (~b1 & b3);
- s[18] = b18 ^ (~b10 & b12);
- s[19] = b19 ^ (~b11 & b13);
- s[28] = b28 ^ (~b20 & b22);
- s[29] = b29 ^ (~b21 & b23);
- s[38] = b38 ^ (~b30 & b32);
- s[39] = b39 ^ (~b31 & b33);
- s[48] = b48 ^ (~b40 & b42);
- s[49] = b49 ^ (~b41 & b43);
-
- s[0] ^= RC[n];
- s[1] ^= RC[n + 1];
- }
- };
-
- if (COMMON_JS) {
- module.exports = methods;
- } else {
- for (var i = 0; i < methodNames.length; ++i) {
- root[methodNames[i]] = methods[methodNames[i]];
- }
- }
-})();
-
-}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"_process":1438}],332:[function(require,module,exports){
-var generate = function generate(num, fn) {
- var a = [];
- for (var i = 0; i < num; ++i) {
- a.push(fn(i));
- }return a;
-};
-
-var replicate = function replicate(num, val) {
- return generate(num, function () {
- return val;
- });
-};
-
-var concat = function concat(a, b) {
- return a.concat(b);
-};
-
-var flatten = function flatten(a) {
- var r = [];
- for (var j = 0, J = a.length; j < J; ++j) {
- for (var i = 0, I = a[j].length; i < I; ++i) {
- r.push(a[j][i]);
- }
- }return r;
-};
-
-var chunksOf = function chunksOf(n, a) {
- var b = [];
- for (var i = 0, l = a.length; i < l; i += n) {
- b.push(a.slice(i, i + n));
- }return b;
-};
-
-module.exports = {
- generate: generate,
- replicate: replicate,
- concat: concat,
- flatten: flatten,
- chunksOf: chunksOf
-};
-},{}],333:[function(require,module,exports){
-var A = require("./array.js");
-
-var at = function at(bytes, index) {
- return parseInt(bytes.slice(index * 2 + 2, index * 2 + 4), 16);
-};
-
-var random = function random(bytes) {
- var rnd = void 0;
- if (typeof window !== "undefined" && window.crypto && window.crypto.getRandomValues) rnd = window.crypto.getRandomValues(new Uint8Array(bytes));else if (typeof require !== "undefined") rnd = require("c" + "rypto").randomBytes(bytes);else throw "Safe random numbers not available.";
- var hex = "0x";
- for (var i = 0; i < bytes; ++i) {
- hex += ("00" + rnd[i].toString(16)).slice(-2);
- }return hex;
-};
-
-var length = function length(a) {
- return (a.length - 2) / 2;
-};
-
-var flatten = function flatten(a) {
- return "0x" + a.reduce(function (r, s) {
- return r + s.slice(2);
- }, "");
-};
-
-var slice = function slice(i, j, bs) {
- return "0x" + bs.slice(i * 2 + 2, j * 2 + 2);
-};
-
-var reverse = function reverse(hex) {
- var rev = "0x";
- for (var i = 0, l = length(hex); i < l; ++i) {
- rev += hex.slice((l - i) * 2, (l - i + 1) * 2);
- }
- return rev;
-};
-
-var pad = function pad(l, hex) {
- return hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2));
-};
-
-var padRight = function padRight(l, hex) {
- return hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0");
-};
-
-var toArray = function toArray(hex) {
- var arr = [];
- for (var i = 2, l = hex.length; i < l; i += 2) {
- arr.push(parseInt(hex.slice(i, i + 2), 16));
- }return arr;
-};
-
-var fromArray = function fromArray(arr) {
- var hex = "0x";
- for (var i = 0, l = arr.length; i < l; ++i) {
- var b = arr[i];
- hex += (b < 16 ? "0" : "") + b.toString(16);
- }
- return hex;
-};
-
-var toUint8Array = function toUint8Array(hex) {
- return new Uint8Array(toArray(hex));
-};
-
-var fromUint8Array = function fromUint8Array(arr) {
- return fromArray([].slice.call(arr, 0));
-};
-
-var fromNumber = function fromNumber(num) {
- var hex = num.toString(16);
- return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex;
-};
-
-var toNumber = function toNumber(hex) {
- return parseInt(hex.slice(2), 16);
-};
-
-var concat = function concat(a, b) {
- return a.concat(b.slice(2));
-};
-
-var fromNat = function fromNat(bn) {
- return bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2);
-};
-
-var toNat = function toNat(bn) {
- return bn[2] === "0" ? "0x" + bn.slice(3) : bn;
-};
-
-var fromAscii = function fromAscii(ascii) {
- var hex = "0x";
- for (var i = 0; i < ascii.length; ++i) {
- hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2);
- }return hex;
-};
-
-var toAscii = function toAscii(hex) {
- var ascii = "";
- for (var i = 2; i < hex.length; i += 2) {
- ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16));
- }return ascii;
-};
-
-// From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330
-var fromString = function fromString(s) {
- var makeByte = function makeByte(uint8) {
- var b = uint8.toString(16);
- return b.length < 2 ? "0" + b : b;
- };
- var bytes = "0x";
- for (var ci = 0; ci != s.length; ci++) {
- var c = s.charCodeAt(ci);
- if (c < 128) {
- bytes += makeByte(c);
- continue;
- }
- if (c < 2048) {
- bytes += makeByte(c >> 6 | 192);
- } else {
- if (c > 0xd7ff && c < 0xdc00) {
- if (++ci == s.length) return null;
- var c2 = s.charCodeAt(ci);
- if (c2 < 0xdc00 || c2 > 0xdfff) return null;
- c = 0x10000 + ((c & 0x03ff) << 10) + (c2 & 0x03ff);
- bytes += makeByte(c >> 18 | 240);
- bytes += makeByte(c >> 12 & 63 | 128);
- } else {
- // c <= 0xffff
- bytes += makeByte(c >> 12 | 224);
- }
- bytes += makeByte(c >> 6 & 63 | 128);
- }
- bytes += makeByte(c & 63 | 128);
- }
- return bytes;
-};
-
-var toString = function toString(bytes) {
- var s = '';
- var i = 0;
- var l = length(bytes);
- while (i < l) {
- var c = at(bytes, i++);
- if (c > 127) {
- if (c > 191 && c < 224) {
- if (i >= l) return null;
- c = (c & 31) << 6 | at(bytes, i) & 63;
- } else if (c > 223 && c < 240) {
- if (i + 1 >= l) return null;
- c = (c & 15) << 12 | (at(bytes, i) & 63) << 6 | at(bytes, ++i) & 63;
- } else if (c > 239 && c < 248) {
- if (i + 2 >= l) return null;
- c = (c & 7) << 18 | (at(bytes, i) & 63) << 12 | (at(bytes, ++i) & 63) << 6 | at(bytes, ++i) & 63;
- } else return null;
- ++i;
- }
- if (c <= 0xffff) s += String.fromCharCode(c);else if (c <= 0x10ffff) {
- c -= 0x10000;
- s += String.fromCharCode(c >> 10 | 0xd800);
- s += String.fromCharCode(c & 0x3FF | 0xdc00);
- } else return null;
- }
- return s;
-};
-
-module.exports = {
- random: random,
- length: length,
- concat: concat,
- flatten: flatten,
- slice: slice,
- reverse: reverse,
- pad: pad,
- padRight: padRight,
- fromAscii: fromAscii,
- toAscii: toAscii,
- fromString: fromString,
- toString: toString,
- fromNumber: fromNumber,
- toNumber: toNumber,
- fromNat: fromNat,
- toNat: toNat,
- fromArray: fromArray,
- toArray: toArray,
- fromUint8Array: fromUint8Array,
- toUint8Array: toUint8Array
-};
-},{"./array.js":332}],334:[function(require,module,exports){
-// This was ported from https://github.com/emn178/js-sha3, with some minor
-// modifications and pruning. It is licensed under MIT:
-//
-// Copyright 2015-2016 Chen, Yi-Cyuan
-//
-// Permission is hereby granted, free of charge, to any person obtaining
-// a copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to
-// permit persons to whom the Software is furnished to do so, subject to
-// the following conditions:
-//
-// The above copyright notice and this permission notice shall be
-// included in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
-// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
-// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
-// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-var HEX_CHARS = '0123456789abcdef'.split('');
-var KECCAK_PADDING = [1, 256, 65536, 16777216];
-var SHIFT = [0, 8, 16, 24];
-var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648];
-
-var Keccak = function Keccak(bits) {
- return {
- blocks: [],
- reset: true,
- block: 0,
- start: 0,
- blockCount: 1600 - (bits << 1) >> 5,
- outputBlocks: bits >> 5,
- s: function (s) {
- return [].concat(s, s, s, s, s);
- }([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
- };
-};
-
-var update = function update(state, message) {
- var length = message.length,
- blocks = state.blocks,
- byteCount = state.blockCount << 2,
- blockCount = state.blockCount,
- outputBlocks = state.outputBlocks,
- s = state.s,
- index = 0,
- i,
- code;
-
- // update
- while (index < length) {
- if (state.reset) {
- state.reset = false;
- blocks[0] = state.block;
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- if (typeof message !== "string") {
- for (i = state.start; index < length && i < byteCount; ++index) {
- blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
- }
- } else {
- for (i = state.start; index < length && i < byteCount; ++index) {
- code = message.charCodeAt(index);
- if (code < 0x80) {
- blocks[i >> 2] |= code << SHIFT[i++ & 3];
- } else if (code < 0x800) {
- blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
- } else if (code < 0xd800 || code >= 0xe000) {
- blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
- } else {
- code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
- blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
- blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
- }
- }
- }
- state.lastByteIndex = i;
- if (i >= byteCount) {
- state.start = i - byteCount;
- state.block = blocks[blockCount];
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
- state.reset = true;
- } else {
- state.start = i;
- }
- }
-
- // finalize
- i = state.lastByteIndex;
- blocks[i >> 2] |= KECCAK_PADDING[i & 3];
- if (state.lastByteIndex === byteCount) {
- blocks[0] = blocks[blockCount];
- for (i = 1; i < blockCount + 1; ++i) {
- blocks[i] = 0;
- }
- }
- blocks[blockCount - 1] |= 0x80000000;
- for (i = 0; i < blockCount; ++i) {
- s[i] ^= blocks[i];
- }
- f(s);
-
- // toString
- var hex = '',
- i = 0,
- j = 0,
- block;
- while (j < outputBlocks) {
- for (i = 0; i < blockCount && j < outputBlocks; ++i, ++j) {
- block = s[i];
- hex += HEX_CHARS[block >> 4 & 0x0F] + HEX_CHARS[block & 0x0F] + HEX_CHARS[block >> 12 & 0x0F] + HEX_CHARS[block >> 8 & 0x0F] + HEX_CHARS[block >> 20 & 0x0F] + HEX_CHARS[block >> 16 & 0x0F] + HEX_CHARS[block >> 28 & 0x0F] + HEX_CHARS[block >> 24 & 0x0F];
- }
- if (j % blockCount === 0) {
- f(s);
- i = 0;
- }
- }
- return "0x" + hex;
-};
-
-var f = function f(s) {
- var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49;
-
- for (n = 0; n < 48; n += 2) {
- c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40];
- c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41];
- c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42];
- c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43];
- c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44];
- c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45];
- c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46];
- c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47];
- c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48];
- c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49];
-
- h = c8 ^ (c2 << 1 | c3 >>> 31);
- l = c9 ^ (c3 << 1 | c2 >>> 31);
- s[0] ^= h;
- s[1] ^= l;
- s[10] ^= h;
- s[11] ^= l;
- s[20] ^= h;
- s[21] ^= l;
- s[30] ^= h;
- s[31] ^= l;
- s[40] ^= h;
- s[41] ^= l;
- h = c0 ^ (c4 << 1 | c5 >>> 31);
- l = c1 ^ (c5 << 1 | c4 >>> 31);
- s[2] ^= h;
- s[3] ^= l;
- s[12] ^= h;
- s[13] ^= l;
- s[22] ^= h;
- s[23] ^= l;
- s[32] ^= h;
- s[33] ^= l;
- s[42] ^= h;
- s[43] ^= l;
- h = c2 ^ (c6 << 1 | c7 >>> 31);
- l = c3 ^ (c7 << 1 | c6 >>> 31);
- s[4] ^= h;
- s[5] ^= l;
- s[14] ^= h;
- s[15] ^= l;
- s[24] ^= h;
- s[25] ^= l;
- s[34] ^= h;
- s[35] ^= l;
- s[44] ^= h;
- s[45] ^= l;
- h = c4 ^ (c8 << 1 | c9 >>> 31);
- l = c5 ^ (c9 << 1 | c8 >>> 31);
- s[6] ^= h;
- s[7] ^= l;
- s[16] ^= h;
- s[17] ^= l;
- s[26] ^= h;
- s[27] ^= l;
- s[36] ^= h;
- s[37] ^= l;
- s[46] ^= h;
- s[47] ^= l;
- h = c6 ^ (c0 << 1 | c1 >>> 31);
- l = c7 ^ (c1 << 1 | c0 >>> 31);
- s[8] ^= h;
- s[9] ^= l;
- s[18] ^= h;
- s[19] ^= l;
- s[28] ^= h;
- s[29] ^= l;
- s[38] ^= h;
- s[39] ^= l;
- s[48] ^= h;
- s[49] ^= l;
-
- b0 = s[0];
- b1 = s[1];
- b32 = s[11] << 4 | s[10] >>> 28;
- b33 = s[10] << 4 | s[11] >>> 28;
- b14 = s[20] << 3 | s[21] >>> 29;
- b15 = s[21] << 3 | s[20] >>> 29;
- b46 = s[31] << 9 | s[30] >>> 23;
- b47 = s[30] << 9 | s[31] >>> 23;
- b28 = s[40] << 18 | s[41] >>> 14;
- b29 = s[41] << 18 | s[40] >>> 14;
- b20 = s[2] << 1 | s[3] >>> 31;
- b21 = s[3] << 1 | s[2] >>> 31;
- b2 = s[13] << 12 | s[12] >>> 20;
- b3 = s[12] << 12 | s[13] >>> 20;
- b34 = s[22] << 10 | s[23] >>> 22;
- b35 = s[23] << 10 | s[22] >>> 22;
- b16 = s[33] << 13 | s[32] >>> 19;
- b17 = s[32] << 13 | s[33] >>> 19;
- b48 = s[42] << 2 | s[43] >>> 30;
- b49 = s[43] << 2 | s[42] >>> 30;
- b40 = s[5] << 30 | s[4] >>> 2;
- b41 = s[4] << 30 | s[5] >>> 2;
- b22 = s[14] << 6 | s[15] >>> 26;
- b23 = s[15] << 6 | s[14] >>> 26;
- b4 = s[25] << 11 | s[24] >>> 21;
- b5 = s[24] << 11 | s[25] >>> 21;
- b36 = s[34] << 15 | s[35] >>> 17;
- b37 = s[35] << 15 | s[34] >>> 17;
- b18 = s[45] << 29 | s[44] >>> 3;
- b19 = s[44] << 29 | s[45] >>> 3;
- b10 = s[6] << 28 | s[7] >>> 4;
- b11 = s[7] << 28 | s[6] >>> 4;
- b42 = s[17] << 23 | s[16] >>> 9;
- b43 = s[16] << 23 | s[17] >>> 9;
- b24 = s[26] << 25 | s[27] >>> 7;
- b25 = s[27] << 25 | s[26] >>> 7;
- b6 = s[36] << 21 | s[37] >>> 11;
- b7 = s[37] << 21 | s[36] >>> 11;
- b38 = s[47] << 24 | s[46] >>> 8;
- b39 = s[46] << 24 | s[47] >>> 8;
- b30 = s[8] << 27 | s[9] >>> 5;
- b31 = s[9] << 27 | s[8] >>> 5;
- b12 = s[18] << 20 | s[19] >>> 12;
- b13 = s[19] << 20 | s[18] >>> 12;
- b44 = s[29] << 7 | s[28] >>> 25;
- b45 = s[28] << 7 | s[29] >>> 25;
- b26 = s[38] << 8 | s[39] >>> 24;
- b27 = s[39] << 8 | s[38] >>> 24;
- b8 = s[48] << 14 | s[49] >>> 18;
- b9 = s[49] << 14 | s[48] >>> 18;
-
- s[0] = b0 ^ ~b2 & b4;
- s[1] = b1 ^ ~b3 & b5;
- s[10] = b10 ^ ~b12 & b14;
- s[11] = b11 ^ ~b13 & b15;
- s[20] = b20 ^ ~b22 & b24;
- s[21] = b21 ^ ~b23 & b25;
- s[30] = b30 ^ ~b32 & b34;
- s[31] = b31 ^ ~b33 & b35;
- s[40] = b40 ^ ~b42 & b44;
- s[41] = b41 ^ ~b43 & b45;
- s[2] = b2 ^ ~b4 & b6;
- s[3] = b3 ^ ~b5 & b7;
- s[12] = b12 ^ ~b14 & b16;
- s[13] = b13 ^ ~b15 & b17;
- s[22] = b22 ^ ~b24 & b26;
- s[23] = b23 ^ ~b25 & b27;
- s[32] = b32 ^ ~b34 & b36;
- s[33] = b33 ^ ~b35 & b37;
- s[42] = b42 ^ ~b44 & b46;
- s[43] = b43 ^ ~b45 & b47;
- s[4] = b4 ^ ~b6 & b8;
- s[5] = b5 ^ ~b7 & b9;
- s[14] = b14 ^ ~b16 & b18;
- s[15] = b15 ^ ~b17 & b19;
- s[24] = b24 ^ ~b26 & b28;
- s[25] = b25 ^ ~b27 & b29;
- s[34] = b34 ^ ~b36 & b38;
- s[35] = b35 ^ ~b37 & b39;
- s[44] = b44 ^ ~b46 & b48;
- s[45] = b45 ^ ~b47 & b49;
- s[6] = b6 ^ ~b8 & b0;
- s[7] = b7 ^ ~b9 & b1;
- s[16] = b16 ^ ~b18 & b10;
- s[17] = b17 ^ ~b19 & b11;
- s[26] = b26 ^ ~b28 & b20;
- s[27] = b27 ^ ~b29 & b21;
- s[36] = b36 ^ ~b38 & b30;
- s[37] = b37 ^ ~b39 & b31;
- s[46] = b46 ^ ~b48 & b40;
- s[47] = b47 ^ ~b49 & b41;
- s[8] = b8 ^ ~b0 & b2;
- s[9] = b9 ^ ~b1 & b3;
- s[18] = b18 ^ ~b10 & b12;
- s[19] = b19 ^ ~b11 & b13;
- s[28] = b28 ^ ~b20 & b22;
- s[29] = b29 ^ ~b21 & b23;
- s[38] = b38 ^ ~b30 & b32;
- s[39] = b39 ^ ~b31 & b33;
- s[48] = b48 ^ ~b40 & b42;
- s[49] = b49 ^ ~b41 & b43;
-
- s[0] ^= RC[n];
- s[1] ^= RC[n + 1];
- }
-};
-
-var keccak = function keccak(bits) {
- return function (str) {
- var msg;
- if (str.slice(0, 2) === "0x") {
- msg = [];
- for (var i = 2, l = str.length; i < l; i += 2) {
- msg.push(parseInt(str.slice(i, i + 2), 16));
- }
- } else {
- msg = str;
- }
- return update(Keccak(bits, bits), msg);
- };
-};
-
-module.exports = {
- keccak256: keccak(256),
- keccak512: keccak(512),
- keccak256s: keccak(256),
- keccak512s: keccak(512)
-};
-},{}],335:[function(require,module,exports){
-const keccak256 = require('keccak256')
-
-function toChecksumAddress (address, chainId = null) {
- if (typeof address !== 'string') {
- return ''
- }
-
- if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) { throw new Error(`Given address "${address}" is not a valid Ethereum address.`) }
-
- const stripAddress = stripHexPrefix(address).toLowerCase()
- const prefix = chainId != null ? chainId.toString() + '0x' : ''
- const keccakHash = keccak256(prefix + stripAddress)
- .toString('hex')
- .replace(/^0x/i, '')
- let checksumAddress = '0x'
-
- for (let i = 0; i < stripAddress.length; i++) { checksumAddress += parseInt(keccakHash[i], 16) >= 8 ? stripAddress[i].toUpperCase() : stripAddress[i] }
-
- return checksumAddress
-}
-
-function checkAddressChecksum (address, chainId = null) {
- const stripAddress = stripHexPrefix(address).toLowerCase()
- const prefix = chainId != null ? chainId.toString() + '0x' : ''
- const keccakHash = keccak256(prefix + stripAddress)
- .toString('hex')
- .replace(/^0x/i, '')
-
- for (let i = 0; i < stripAddress.length; i++) {
- let output = parseInt(keccakHash[i], 16) >= 8 ? stripAddress[i].toUpperCase() : stripAddress[i]
- if (stripHexPrefix(address)[i] !== output) {
- return false
- }
- }
- return true
-};
-
-function stripHexPrefix (string) {
- return string.slice(0, 2) === '0x' ? string.slice(2) : string
-};
-
-module.exports = {
- toChecksumAddress,
- checkAddressChecksum
-}
-
-},{"keccak256":839}],336:[function(require,module,exports){
-(function (Buffer){
-const privateKeyToPublicKey = require('ethereum-private-key-to-public-key')
-const publicKeyToAddress = require('ethereum-public-key-to-address')
-
-function privateKeyToAddress (privateKey) {
- if (!Buffer.isBuffer(privateKey)) {
- if (typeof privateKey !== 'string') {
- throw new Error('Expected Buffer or string as argument')
- }
-
- privateKey = privateKey.slice(0, 2) === '0x' ? privateKey.slice(2) : privateKey
- privateKey = Buffer.from(privateKey, 'hex')
- }
-
- return publicKeyToAddress(privateKeyToPublicKey(privateKey))
-}
-
-module.exports = privateKeyToAddress
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":217,"ethereum-private-key-to-public-key":337,"ethereum-public-key-to-address":338}],337:[function(require,module,exports){
-(function (Buffer){
-const { publicKeyCreate } = require('secp256k1')
-
-function privateKeyToPublicKey (privateKey) {
- if (!Buffer.isBuffer(privateKey)) {
- if (typeof privateKey !== 'string') {
- throw new Error('Expected Buffer or string as argument')
- }
-
- privateKey = privateKey.slice(0, 2) === '0x' ? privateKey.slice(2) : privateKey
- privateKey = Buffer.from(privateKey, 'hex')
- }
-
- return publicKeyCreate(privateKey, false)
-}
-
-module.exports = privateKeyToPublicKey
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":217,"secp256k1":1600}],338:[function(require,module,exports){
-(function (Buffer){
-const { publicKeyConvert } = require('secp256k1')
-const keccak256 = require('keccak256')
-const { toChecksumAddress } = require('ethereum-checksum-address')
-
-function publicKeyToAddress (publicKey) {
- if (!Buffer.isBuffer(publicKey)) {
- if (typeof publicKey !== 'string') {
- throw new Error('Expected Buffer or string as argument')
- }
-
- publicKey = publicKey.slice(0, 2) === '0x' ? publicKey.slice(2) : publicKey
- publicKey = Buffer.from(publicKey, 'hex')
- }
-
- publicKey = publicKeyConvert(publicKey, false).slice(1)
- return toChecksumAddress(keccak256(publicKey).slice(-20).toString('hex'))
-}
-
-module.exports = publicKeyToAddress
-
-}).call(this,require("buffer").Buffer)
-},{"buffer":217,"ethereum-checksum-address":335,"keccak256":839,"secp256k1":1600}],339:[function(require,module,exports){
-module.exports={
- "name": "goerli",
- "chainId": 5,
- "networkId": 5,
- "comment": "Cross-client PoA test network",
- "url": "https://github.com/goerli/testnet",
- "genesis": {
- "hash": "0xbf7e331f7f7c1dd2e05159666b3bf8bc7a8a3a9eb1d518969eab529dd9b88c1a",
- "timestamp": "0x5c51a607",
- "gasLimit": 10485760,
- "difficulty": 1,
- "nonce": "0x0000000000000000",
- "extraData": "0x22466c6578692069732061207468696e6722202d204166726900000000000000e0a2bd4258d2768837baa26a28fe71dc079f84c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
- "stateRoot": "0x5d6cded585e73c4e322c30c2f782a336316f17dd85a4863b9d838d2d4b8b3008"
- },
- "hardforks": [
- {
- "name": "chainstart",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "homestead",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "dao",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "tangerineWhistle",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "spuriousDragon",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "byzantium",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "constantinople",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "petersburg",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "istanbul",
- "block": null,
- "consensus": "poa",
- "finality": null
- }
- ],
- "bootstrapNodes": [
- {
- "ip": "51.141.78.53",
- "port": 30303,
- "id": "011f758e6552d105183b1761c5e2dea0111bc20fd5f6422bc7f91e0fabbec9a6595caf6239b37feb773dddd3f87240d99d859431891e4a642cf2a0a9e6cbb98a",
- "location": "",
- "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt"
- },
- {
- "ip": "13.93.54.137",
- "port": 30303,
- "id": "176b9417f511d05b6b2cf3e34b756cf0a7096b3094572a8f6ef4cdcb9d1f9d00683bf0f83347eebdf3b81c3521c2332086d9592802230bf528eaf606a1d9677b",
- "location": "",
- "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt"
- },
- {
- "ip": "94.237.54.114",
- "port": 30313,
- "id": "46add44b9f13965f7b9875ac6b85f016f341012d84f975377573800a863526f4da19ae2c620ec73d11591fa9510e992ecc03ad0751f53cc02f7c7ed6d55c7291",
- "location": "",
- "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt"
- },
- {
- "ip": "52.64.155.147",
- "port": 30303,
- "id": "c1f8b7c2ac4453271fa07d8e9ecf9a2e8285aa0bd0c07df0131f47153306b0736fd3db8924e7a9bf0bed6b1d8d4f87362a71b033dc7c64547728d953e43e59b2",
- "location": "",
- "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt"
- },
- {
- "ip": "213.186.16.82",
- "port": 30303,
- "id": "f4a9c6ee28586009fb5a96c8af13a58ed6d8315a9eee4772212c1d4d9cebe5a8b8a78ea4434f318726317d04a3f531a1ef0420cf9752605a562cfe858c46e263",
- "location": "",
- "comment": "Source: https://github.com/goerli/testnet/blob/master/bootnodes.txt"
- }
- ]
-}
-
-},{}],340:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.chains = {
- names: {
- '1': 'mainnet',
- '3': 'ropsten',
- '4': 'rinkeby',
- '42': 'kovan',
- '6284': 'goerli',
- },
- mainnet: require('./mainnet.json'),
- ropsten: require('./ropsten.json'),
- rinkeby: require('./rinkeby.json'),
- kovan: require('./kovan.json'),
- goerli: require('./goerli.json'),
-};
-
-},{"./goerli.json":339,"./kovan.json":341,"./mainnet.json":342,"./rinkeby.json":343,"./ropsten.json":344}],341:[function(require,module,exports){
-module.exports={
- "name": "kovan",
- "chainId": 42,
- "networkId": 42,
- "comment": "Parity PoA test network",
- "url": "https://kovan-testnet.github.io/website/",
- "genesis": {
- "hash": "0xa3c565fc15c7478862d50ccd6561e3c06b24cc509bf388941c25ea985ce32cb9",
- "timestamp": null,
- "gasLimit": 6000000,
- "difficulty": 131072,
- "nonce": "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
- "extraData": "0x",
- "stateRoot": "0x2480155b48a1cea17d67dbfdfaafe821c1d19cdd478c5358e8ec56dec24502b2"
- },
- "hardforks": [],
- "bootstrapNodes": [
- {
- "ip": "40.71.221.215",
- "port": 30303,
- "id": "56abaf065581a5985b8c5f4f88bd202526482761ba10be9bfdcd14846dd01f652ec33fde0f8c0fd1db19b59a4c04465681fcef50e11380ca88d25996191c52de",
- "location": "",
- "comment": "Parity Bootnode"
- },
- {
- "ip": "52.166.117.77",
- "port": 30303,
- "id": "d07827483dc47b368eaf88454fb04b41b7452cf454e194e2bd4c14f98a3278fed5d819dbecd0d010407fc7688d941ee1e58d4f9c6354d3da3be92f55c17d7ce3",
- "location": "",
- "comment": "Parity Bootnode"
- },
- {
- "ip": "52.165.239.18",
- "port": 30303,
- "id": "8fa162563a8e5a05eef3e1cd5abc5828c71344f7277bb788a395cce4a0e30baf2b34b92fe0b2dbbba2313ee40236bae2aab3c9811941b9f5a7e8e90aaa27ecba",
- "location": "",
- "comment": "Parity Bootnode"
- },
- {
- "ip": "52.243.47.56",
- "port": 30303,
- "id": "7e2e7f00784f516939f94e22bdc6cf96153603ca2b5df1c7cc0f90a38e7a2f218ffb1c05b156835e8b49086d11fdd1b3e2965be16baa55204167aa9bf536a4d9",
- "location": "",
- "comment": "Parity Bootnode"
- },
- {
- "ip": "40.68.248.100",
- "port": 30303,
- "id": "0518a3d35d4a7b3e8c433e7ffd2355d84a1304ceb5ef349787b556197f0c87fad09daed760635b97d52179d645d3e6d16a37d2cc0a9945c2ddf585684beb39ac",
- "location": "",
- "comment": "Parity Bootnode"
- }
- ]
-}
-
-},{}],342:[function(require,module,exports){
-module.exports={
- "name": "mainnet",
- "chainId": 1,
- "networkId": 1,
- "comment": "The Ethereum main chain",
- "url": "https://ethstats.net/",
- "genesis": {
- "hash": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3",
- "timestamp": null,
- "gasLimit": 5000,
- "difficulty": 17179869184,
- "nonce": "0x0000000000000042",
- "extraData": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa",
- "stateRoot": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544"
- },
- "hardforks": [
- {
- "name": "chainstart",
- "block": 0,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "homestead",
- "block": 1150000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "dao",
- "block": 1920000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "tangerineWhistle",
- "block": 2463000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "spuriousDragon",
- "block": 2675000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "byzantium",
- "block": 4370000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "constantinople",
- "block": 7280000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "petersburg",
- "block": 7280000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "istanbul",
- "block": null,
- "consensus": "pow",
- "finality": null
- }
- ],
- "bootstrapNodes": [
- {
- "ip": "13.93.211.84",
- "port": 30303,
- "id": "3f1d12044546b76342d59d4a05532c14b85aa669704bfe1f864fe079415aa2c02d743e03218e57a33fb94523adb54032871a6c51b2cc5514cb7c7e35b3ed0a99",
- "location": "US-WEST",
- "comment": "Go Bootnode"
- },
- {
- "ip": "191.235.84.50",
- "port": 30303,
- "id": "78de8a0916848093c73790ead81d1928bec737d565119932b98c6b100d944b7a95e94f847f689fc723399d2e31129d182f7ef3863f2b4c820abbf3ab2722344d",
- "location": "BR",
- "comment": "Go Bootnode"
- },
- {
- "ip": "13.75.154.138",
- "port": 30303,
- "id": "158f8aab45f6d19c6cbf4a089c2670541a8da11978a2f90dbf6a502a4a3bab80d288afdbeb7ec0ef6d92de563767f3b1ea9e8e334ca711e9f8e2df5a0385e8e6",
- "location": "AU",
- "comment": "Go Bootnode"
- },
- {
- "ip": "52.74.57.123",
- "port": 30303,
- "id": "1118980bf48b0a3640bdba04e0fe78b1add18e1cd99bf22d53daac1fd9972ad650df52176e7c7d89d1114cfef2bc23a2959aa54998a46afcf7d91809f0855082",
- "location": "SG",
- "comment": "Go Bootnode"
- }
- ]
-}
-
-},{}],343:[function(require,module,exports){
-module.exports={
- "name": "rinkeby",
- "chainId": 4,
- "networkId": 4,
- "comment": "PoA test network",
- "url": "https://www.rinkeby.io",
- "genesis": {
- "hash": "0x6341fd3daf94b748c72ced5a5b26028f2474f5f00d824504e4fa37a75767e177",
- "timestamp": "0x58ee40ba",
- "gasLimit": 4700000,
- "difficulty": 1,
- "nonce": "0x0000000000000000",
- "extraData": "0x52657370656374206d7920617574686f7269746168207e452e436172746d616e42eb768f2244c8811c63729a21a3569731535f067ffc57839b00206d1ad20c69a1981b489f772031b279182d99e65703f0076e4812653aab85fca0f00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
- "stateRoot": "0x53580584816f617295ea26c0e17641e0120cab2f0a8ffb53a866fd53aa8e8c2d"
- },
- "hardforks": [
- {
- "name": "chainstart",
- "block": 0,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "homestead",
- "block": 1,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "dao",
- "block": null,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "tangerineWhistle",
- "block": 2,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "spuriousDragon",
- "block": 3,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "byzantium",
- "block": 1035301,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "constantinople",
- "block": null,
- "consensus": "poa",
- "finality": null
- },
- {
- "name": "istanbul",
- "block": null,
- "consensus": "poa",
- "finality": null
- }
- ],
- "bootstrapNodes": [
- {
- "ip": "52.169.42.101",
- "port": 30303,
- "id": "a24ac7c5484ef4ed0c5eb2d36620ba4e4aa13b8c84684e1b4aab0cebea2ae45cb4d375b77eab56516d34bfbd3c1a833fc51296ff084b770b94fb9028c4d25ccf",
- "location": "IE",
- "comment": ""
- },
- {
- "ip": "52.3.158.184",
- "port": 30303,
- "id": "343149e4feefa15d882d9fe4ac7d88f885bd05ebb735e547f12e12080a9fa07c8014ca6fd7f373123488102fe5e34111f8509cf0b7de3f5b44339c9f25e87cb8",
- "location": "",
- "comment": "INFURA"
- }
- ]
-}
-
-},{}],344:[function(require,module,exports){
-module.exports={
- "name": "ropsten",
- "chainId": 3,
- "networkId": 3,
- "comment": "PoW test network",
- "url": "https://github.com/ethereum/ropsten",
- "genesis": {
- "hash": "0x41941023680923e0fe4d74a34bdac8141f2540e3ae90623718e47d66d1ca4a2d",
- "timestamp": null,
- "gasLimit": 16777216,
- "difficulty": 1048576,
- "nonce": "0x0000000000000042",
- "extraData": "0x3535353535353535353535353535353535353535353535353535353535353535",
- "stateRoot": "0x217b0bbcfb72e2d57e28f33cb361b9983513177755dc3f33ce3e7022ed62b77b"
- },
- "hardforks": [
- {
- "name": "chainstart",
- "block": 0,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "homestead",
- "block": 0,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "dao",
- "block": null,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "tangerineWhistle",
- "block": 0,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "spuriousDragon",
- "block": 10,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "byzantium",
- "block": 1700000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "constantinople",
- "block": 4230000,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "petersburg",
- "block": 4939394,
- "consensus": "pow",
- "finality": null
- },
- {
- "name": "istanbul",
- "block": null,
- "consensus": "pow",
- "finality": null
- }
- ],
- "bootstrapNodes": [
- {
- "ip": "52.176.7.10",
- "port": "30303",
- "id": "30b7ab30a01c124a6cceca36863ece12c4f5fa68e3ba9b0b51407ccc002eeed3b3102d20a88f1c1d3c3154e2449317b8ef95090e77b312d5cc39354f86d5d606",
- "network": "Ropsten",
- "chainId": 3,
- "location": "US",
- "comment": "US-Azure geth"
- },
- {
- "ip": "52.176.100.77",
- "port": "30303",
- "id": "865a63255b3bb68023b6bffd5095118fcc13e79dcf014fe4e47e065c350c7cc72af2e53eff895f11ba1bbb6a2b33271c1116ee870f266618eadfc2e78aa7349c",
- "network": "Ropsten",
- "chainId": 3,
- "location": "US",
- "comment": "US-Azure parity"
- },
- {
- "ip": "52.232.243.152",
- "port": "30303",
- "id": "6332792c4a00e3e4ee0926ed89e0d27ef985424d97b6a45bf0f23e51f0dcb5e66b875777506458aea7af6f9e4ffb69f43f3778ee73c81ed9d34c51c4b16b0b0f",
- "network": "Ropsten",
- "chainId": 3,
- "location": "US",
- "comment": "Parity"
- },
- {
- "ip": "192.81.208.223",
- "port": "30303",
- "id": "94c15d1b9e2fe7ce56e458b9a3b672ef11894ddedd0c6f247e0f1d3487f52b66208fb4aeb8179fce6e3a749ea93ed147c37976d67af557508d199d9594c35f09",
- "network": "Ropsten",
- "chainId": 3,
- "location": "US",
- "comment": "@gpip"
- }
- ]
-}
-
-},{}],345:[function(require,module,exports){
-module.exports={
- "name": "byzantium",
- "comment": "Hardfork with new precompiles, instructions and other protocol changes",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-609",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {
- "modexpGquaddivisor": {
- "v": 20,
- "d": "Gquaddivisor from modexp precompile for gas calculation"
- },
- "ecAdd": {
- "v": 500,
- "d": "Gas costs for curve addition precompile"
- },
- "ecMul": {
- "v": 40000,
- "d": "Gas costs for curve multiplication precompile"
- },
- "ecPairing": {
- "v": 100000,
- "d": "Base gas costs for curve pairing precompile"
- },
- "ecPairingWord": {
- "v": 80000,
- "d": "Gas costs regarding curve pairing precompile input length"
- }
- },
- "vm": {},
- "pow": {
- "minerReward": {
- "v": "3000000000000000000",
- "d": "the amount a miner get rewarded for mining a block"
- }
- },
- "casper": {},
- "sharding": {}
-}
-
-},{}],346:[function(require,module,exports){
-module.exports={
- "name": "chainstart",
- "comment": "Start of the Ethereum main chain",
- "eip": {
- "url": "",
- "status": ""
- },
- "status": "",
- "gasConfig": {
- "minGasLimit": {
- "v": 5000,
- "d": "Minimum the gas limit may ever be"
- },
- "gasLimitBoundDivisor": {
- "v": 1024,
- "d": "The bound divisor of the gas limit, used in update calculations"
- }
- },
- "gasPrices": {
- "base": {
- "v": 2,
- "d": "Gas base cost, used e.g. for ChainID opcode (Istanbul)"
- },
- "tierStep": {
- "v": [0, 2, 3, 5, 8, 10, 20],
- "d": "Once per operation, for a selection of them"
- },
- "exp": {
- "v": 10,
- "d": "Once per EXP instuction"
- },
- "expByte": {
- "v": 10,
- "d": "Times ceil(log256(exponent)) for the EXP instruction"
- },
- "sha3": {
- "v": 30,
- "d": "Once per SHA3 operation"
- },
- "sha3Word": {
- "v": 6,
- "d": "Once per word of the SHA3 operation's data"
- },
- "sload": {
- "v": 50,
- "d": "Once per SLOAD operation"
- },
- "sstoreSet": {
- "v": 20000,
- "d": "Once per SSTORE operation if the zeroness changes from zero"
- },
- "sstoreReset": {
- "v": 5000,
- "d": "Once per SSTORE operation if the zeroness does not change from zero"
- },
- "sstoreRefund": {
- "v": 15000,
- "d": "Once per SSTORE operation if the zeroness changes to zero"
- },
- "jumpdest": {
- "v": 1,
- "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero"
- },
- "log": {
- "v": 375,
- "d": "Per LOG* operation"
- },
- "logData": {
- "v": 8,
- "d": "Per byte in a LOG* operation's data"
- },
- "logTopic": {
- "v": 375,
- "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas"
- },
- "create": {
- "v": 32000,
- "d": "Once per CREATE operation & contract-creation transaction"
- },
- "call": {
- "v": 40,
- "d": "Once per CALL operation & message call transaction"
- },
- "callStipend": {
- "v": 2300,
- "d": "Free gas given at beginning of call"
- },
- "callValueTransfer": {
- "v": 9000,
- "d": "Paid for CALL when the value transfor is non-zero"
- },
- "callNewAccount": {
- "v": 25000,
- "d": "Paid for CALL when the destination address didn't exist prior"
- },
- "selfdestructRefund": {
- "v": 24000,
- "d": "Refunded following a selfdestruct operation"
- },
- "memory": {
- "v": 3,
- "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL"
- },
- "quadCoeffDiv": {
- "v": 512,
- "d": "Divisor for the quadratic particle of the memory cost equation"
- },
- "createData": {
- "v": 200,
- "d": ""
- },
- "tx": {
- "v": 21000,
- "d": "Per transaction. NOTE: Not payable on data of calls between transactions"
- },
- "txCreation": {
- "v": 32000,
- "d": "The cost of creating a contract via tx"
- },
- "txDataZero": {
- "v": 4,
- "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions"
- },
- "txDataNonZero": {
- "v": 68,
- "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions"
- },
- "copy": {
- "v": 3,
- "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added"
- },
- "ecRecover": {
- "v": 3000,
- "d": ""
- },
- "sha256": {
- "v": 60,
- "d": ""
- },
- "sha256Word": {
- "v": 12,
- "d": ""
- },
- "ripemd160": {
- "v": 600,
- "d": ""
- },
- "ripemd160Word": {
- "v": 120,
- "d": ""
- },
- "identity": {
- "v": 15,
- "d": ""
- },
- "identityWord": {
- "v": 3,
- "d": ""
- }
- },
- "vm": {
- "stackLimit": {
- "v": 1024,
- "d": "Maximum size of VM stack allowed"
- },
- "callCreateDepth": {
- "v": 1024,
- "d": "Maximum depth of call/create stack"
- },
- "maxExtraDataSize": {
- "v": 32,
- "d": "Maximum size extra data may be after Genesis"
- }
- },
- "pow": {
- "minimumDifficulty": {
- "v": 131072,
- "d": "The minimum that the difficulty may ever be"
- },
- "difficultyBoundDivisor": {
- "v": 2048,
- "d": "The bound divisor of the difficulty, used in the update calculations"
- },
- "durationLimit": {
- "v": 13,
- "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not"
- },
- "epochDuration": {
- "v": 30000,
- "d": "Duration between proof-of-work epochs"
- },
- "timebombPeriod": {
- "v": 100000,
- "d": "Exponential difficulty timebomb period"
- },
- "minerReward": {
- "v": "5000000000000000000",
- "d": "the amount a miner get rewarded for mining a block"
- }
- },
- "casper": {},
- "sharding": {}
-}
-
-},{}],347:[function(require,module,exports){
-module.exports={
- "name": "constantinople",
- "comment": "Postponed hardfork including EIP-1283 (SSTORE gas metering changes)",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-1013",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {
- "netSstoreNoopGas": {
- "v": 200,
- "d": "Once per SSTORE operation if the value doesn't change"
- },
- "netSstoreInitGas": {
- "v": 20000,
- "d": "Once per SSTORE operation from clean zero"
- },
- "netSstoreCleanGas": {
- "v": 5000,
- "d": "Once per SSTORE operation from clean non-zero"
- },
- "netSstoreDirtyGas": {
- "v": 200,
- "d": "Once per SSTORE operation from dirty"
- },
- "netSstoreClearRefund": {
- "v": 15000,
- "d": "Once per SSTORE operation for clearing an originally existing storage slot"
- },
- "netSstoreResetRefund": {
- "v": 4800,
- "d": "Once per SSTORE operation for resetting to the original non-zero value"
- },
- "netSstoreResetClearRefund": {
- "v": 19800,
- "d": "Once per SSTORE operation for resetting to the original zero value"
- }
- },
- "vm": {},
- "pow": {
- "minerReward": {
- "v": "2000000000000000000",
- "d": "The amount a miner gets rewarded for mining a block"
- }
- },
- "casper": {},
- "sharding": {}
-}
-
-},{}],348:[function(require,module,exports){
-module.exports={
- "name": "dao",
- "comment": "DAO rescue hardfork",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-779",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {},
- "vm": {},
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],349:[function(require,module,exports){
-module.exports={
- "name": "homestead",
- "comment": "Homestead hardfork with protocol and network changes",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-606",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {},
- "vm": {},
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],350:[function(require,module,exports){
-"use strict";
-Object.defineProperty(exports, "__esModule", { value: true });
-exports.hardforks = [
- ['chainstart', require('./chainstart.json')],
- ['homestead', require('./homestead.json')],
- ['dao', require('./dao.json')],
- ['tangerineWhistle', require('./tangerineWhistle.json')],
- ['spuriousDragon', require('./spuriousDragon.json')],
- ['byzantium', require('./byzantium.json')],
- ['constantinople', require('./constantinople.json')],
- ['petersburg', require('./petersburg.json')],
- ['istanbul', require('./istanbul.json')],
-];
-
-},{"./byzantium.json":345,"./chainstart.json":346,"./constantinople.json":347,"./dao.json":348,"./homestead.json":349,"./istanbul.json":351,"./petersburg.json":352,"./spuriousDragon.json":353,"./tangerineWhistle.json":354}],351:[function(require,module,exports){
-module.exports={
- "name": "istanbul",
- "comment": "HF targeted for October 2019 following the Constantinople/Petersburg HF",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-1679",
- "status": "Draft"
- },
- "gasConfig": {},
- "gasPrices": {
- "blake2Round": {
- "v": 1,
- "d": "Gas cost per round for the Blake2 F precompile"
- },
- "ecAdd": {
- "v": 150,
- "d": "Gas costs for curve addition precompile"
- },
- "ecMul": {
- "v": 6000,
- "d": "Gas costs for curve multiplication precompile"
- },
- "ecPairing": {
- "v": 45000,
- "d": "Base gas costs for curve pairing precompile"
- },
- "ecPairingWord": {
- "v": 34000,
- "d": "Gas costs regarding curve pairing precompile input length"
- },
- "txDataNonZero": {
- "v": 16,
- "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions"
- },
- "sstoreSentryGasEIP2200": {
- "v": 2300,
- "d": "Minimum gas required to be present for an SSTORE call, not consumed"
- },
- "sstoreNoopGasEIP2200": {
- "v": 800,
- "d": "Once per SSTORE operation if the value doesn't change"
- },
- "sstoreDirtyGasEIP2200": {
- "v": 800,
- "d": "Once per SSTORE operation if a dirty value is changed"
- },
- "sstoreInitGasEIP2200": {
- "v": 20000,
- "d": "Once per SSTORE operation from clean zero to non-zero"
- },
- "sstoreInitRefundEIP2200": {
- "v": 19200,
- "d": "Once per SSTORE operation for resetting to the original zero value"
- },
- "sstoreCleanGasEIP2200": {
- "v": 5000,
- "d": "Once per SSTORE operation from clean non-zero to something else"
- },
- "sstoreCleanRefundEIP2200": {
- "v": 4200,
- "d": "Once per SSTORE operation for resetting to the original non-zero value"
- },
- "sstoreClearRefundEIP2200": {
- "v": 15000,
- "d": "Once per SSTORE operation for clearing an originally existing storage slot"
- }
- },
- "vm": {},
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],352:[function(require,module,exports){
-module.exports={
- "name": "petersburg",
- "comment": "Aka constantinopleFix, removes EIP-1283, activate together with or after constantinople",
- "eip": {
- "url": "https://github.com/ethereum/EIPs/pull/1716",
- "status": "Draft"
- },
- "gasConfig": {},
- "gasPrices": {
- "netSstoreNoopGas": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreInitGas": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreCleanGas": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreDirtyGas": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreClearRefund": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreResetRefund": {
- "v": null,
- "d": "Removed along EIP-1283"
- },
- "netSstoreResetClearRefund": {
- "v": null,
- "d": "Removed along EIP-1283"
- }
- },
- "vm": {},
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],353:[function(require,module,exports){
-module.exports={
- "name": "spuriousDragon",
- "comment": "HF with EIPs for simple replay attack protection, EXP cost increase, state trie clearing, contract code size limit",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-607",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {
- "expByte": {
- "v": 50,
- "d": "Times ceil(log256(exponent)) for the EXP instruction"
- }
- },
- "vm": {
- "maxCodeSize": {
- "v": 24576,
- "d": "Maximum length of contract code"
- }
- },
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],354:[function(require,module,exports){
-module.exports={
- "name": "tangerineWhistle",
- "comment": "Hardfork with gas cost changes for IO-heavy operations",
- "eip": {
- "url": "https://eips.ethereum.org/EIPS/eip-608",
- "status": "Final"
- },
- "gasConfig": {},
- "gasPrices": {
- "sload": {
- "v": 200,
- "d": "Once per SLOAD operation"
- },
- "call": {
- "v": 700,
- "d": "Once per CALL operation & message call transaction"
- }
- },
- "vm": {},
- "pow": {},
- "casper": {},
- "sharding": {}
-}
-
-},{}],355:[function(require,module,exports){
-"use strict";
-var __assign = (this && this.__assign) || function () {
- __assign = Object.assign || function(t) {
- for (var s, i = 1, n = arguments.length; i < n; i++) {
- s = arguments[i];
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
- t[p] = s[p];
- }
- return t;
- };
- return __assign.apply(this, arguments);
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-var chains_1 = require("./chains");
-var hardforks_1 = require("./hardforks");
-/**
- * Common class to access chain and hardfork parameters
- */
-var Common = /** @class */ (function () {
- /**
- * @constructor
- * @param chain String ('mainnet') or Number (1) chain
- * @param hardfork String identifier ('byzantium') for hardfork (optional)
- * @param supportedHardforks Limit parameter returns to the given hardforks (optional)
- */
- function Common(chain, hardfork, supportedHardforks) {
- this._chainParams = this.setChain(chain);
- this._hardfork = null;
- this._supportedHardforks = supportedHardforks === undefined ? [] : supportedHardforks;
- if (hardfork) {
- this.setHardfork(hardfork);
- }
- }
- /**
- * Creates a Common object for a custom chain, based on a standard one. It uses all the [[Chain]]
- * params from [[baseChain]] except the ones overridden in [[customChainParams]].
- *
- * @param baseChain The name (`mainnet`) or id (`1`) of a standard chain used to base the custom
- * chain params on.
- * @param customChainParams The custom parameters of the chain.
- * @param hardfork String identifier ('byzantium') for hardfork (optional)
- * @param supportedHardforks Limit parameter returns to the given hardforks (optional)
- */
- Common.forCustomChain = function (baseChain, customChainParams, hardfork, supportedHardforks) {
- var standardChainParams = Common._getChainParams(baseChain);
- return new Common(__assign({}, standardChainParams, customChainParams), hardfork, supportedHardforks);
- };
- Common._getChainParams = function (chain) {
- if (typeof chain === 'number') {
- if (chains_1.chains['names'][chain]) {
- return chains_1.chains[chains_1.chains['names'][chain]];
- }
- throw new Error("Chain with ID " + chain + " not supported");
- }
- if (chains_1.chains[chain]) {
- return chains_1.chains[chain];
- }
- throw new Error("Chain with name " + chain + " not supported");
- };
- /**
- * Sets the chain
- * @param chain String ('mainnet') or Number (1) chain
- * representation. Or, a Dictionary of chain parameters for a private network.
- * @returns The dictionary with parameters set as chain
- */
- Common.prototype.setChain = function (chain) {
- if (typeof chain === 'number' || typeof chain === 'string') {
- this._chainParams = Common._getChainParams(chain);
- }
- else if (typeof chain === 'object') {
- var required = ['networkId', 'genesis', 'hardforks', 'bootstrapNodes'];
- for (var _i = 0, required_1 = required; _i < required_1.length; _i++) {
- var param = required_1[_i];
- if (chain[param] === undefined) {
- throw new Error("Missing required chain parameter: " + param);
- }
- }
- this._chainParams = chain;
- }
- else {
- throw new Error('Wrong input format');
- }
- return this._chainParams;
- };
- /**
- * Sets the hardfork to get params for
- * @param hardfork String identifier ('byzantium')
- */
- Common.prototype.setHardfork = function (hardfork) {
- if (!this._isSupportedHardfork(hardfork)) {
- throw new Error("Hardfork " + hardfork + " not set as supported in supportedHardforks");
- }
- var changed = false;
- for (var _i = 0, hardforkChanges_1 = hardforks_1.hardforks; _i < hardforkChanges_1.length; _i++) {
- var hfChanges = hardforkChanges_1[_i];
- if (hfChanges[0] === hardfork) {
- this._hardfork = hardfork;
- changed = true;
- }
- }
- if (!changed) {
- throw new Error("Hardfork with name " + hardfork + " not supported");
- }
- };
- /**
- * Internal helper function to choose between hardfork set and hardfork provided as param
- * @param hardfork Hardfork given to function as a parameter
- * @returns Hardfork chosen to be used
- */
- Common.prototype._chooseHardfork = function (hardfork, onlySupported) {
- onlySupported = onlySupported === undefined ? true : onlySupported;
- if (!hardfork) {
- if (!this._hardfork) {
- throw new Error('Method called with neither a hardfork set nor provided by param');
- }
- else {
- hardfork = this._hardfork;
- }
- }
- else if (onlySupported && !this._isSupportedHardfork(hardfork)) {
- throw new Error("Hardfork " + hardfork + " not set as supported in supportedHardforks");
- }
- return hardfork;
- };
- /**
- * Internal helper function, returns the params for the given hardfork for the chain set
- * @param hardfork Hardfork name
- * @returns Dictionary with hardfork params
- */
- Common.prototype._getHardfork = function (hardfork) {
- var hfs = this.hardforks();
- for (var _i = 0, hfs_1 = hfs; _i < hfs_1.length; _i++) {
- var hf = hfs_1[_i];
- if (hf['name'] === hardfork)
- return hf;
- }
- throw new Error("Hardfork " + hardfork + " not defined for chain " + this.chainName());
- };
- /**
- * Internal helper function to check if a hardfork is set to be supported by the library
- * @param hardfork Hardfork name
- * @returns True if hardfork is supported
- */
- Common.prototype._isSupportedHardfork = function (hardfork) {
- if (this._supportedHardforks.length > 0) {
- for (var _i = 0, _a = this._supportedHardforks; _i < _a.length; _i++) {
- var supportedHf = _a[_i];
- if (hardfork === supportedHf)
- return true;
- }
- }
- else {
- return true;
- }
- return false;
- };
- /**
- * Returns the parameter corresponding to a hardfork
- * @param topic Parameter topic ('gasConfig', 'gasPrices', 'vm', 'pow', 'casper', 'sharding')
- * @param name Parameter name (e.g. 'minGasLimit' for 'gasConfig' topic)
- * @param hardfork Hardfork name, optional if hardfork set
- */
- Common.prototype.param = function (topic, name, hardfork) {
- hardfork = this._chooseHardfork(hardfork);
- var value;
- for (var _i = 0, hardforkChanges_2 = hardforks_1.hardforks; _i < hardforkChanges_2.length; _i++) {
- var hfChanges = hardforkChanges_2[_i];
- if (!hfChanges[1][topic]) {
- throw new Error("Topic " + topic + " not defined");
- }
- if (hfChanges[1][topic][name] !== undefined) {
- value = hfChanges[1][topic][name].v;
- }
- if (hfChanges[0] === hardfork)
- break;
- }
- if (value === undefined) {
- throw new Error(topic + " value for " + name + " not found");
- }
- return value;
- };
- /**
- * Returns a parameter for the hardfork active on block number
- * @param topic Parameter topic
- * @param name Parameter name
- * @param blockNumber Block number
- */
- Common.prototype.paramByBlock = function (topic, name, blockNumber) {
- var activeHfs = this.activeHardforks(blockNumber);
- var hardfork = activeHfs[activeHfs.length - 1]['name'];
- return this.param(topic, name, hardfork);
- };
- /**
- * Checks if set or provided hardfork is active on block number
- * @param hardfork Hardfork name or null (for HF set)
- * @param blockNumber
- * @param opts Hardfork options (onlyActive unused)
- * @returns True if HF is active on block number
- */
- Common.prototype.hardforkIsActiveOnBlock = function (hardfork, blockNumber, opts) {
- opts = opts !== undefined ? opts : {};
- var onlySupported = opts.onlySupported === undefined ? false : opts.onlySupported;
- hardfork = this._chooseHardfork(hardfork, onlySupported);
- var hfBlock = this.hardforkBlock(hardfork);
- if (hfBlock !== null && blockNumber >= hfBlock)
- return true;
- return false;
- };
- /**
- * Alias to hardforkIsActiveOnBlock when hardfork is set
- * @param blockNumber
- * @param opts Hardfork options (onlyActive unused)
- * @returns True if HF is active on block number
- */
- Common.prototype.activeOnBlock = function (blockNumber, opts) {
- return this.hardforkIsActiveOnBlock(null, blockNumber, opts);
- };
- /**
- * Sequence based check if given or set HF1 is greater than or equal HF2
- * @param hardfork1 Hardfork name or null (if set)
- * @param hardfork2 Hardfork name
- * @param opts Hardfork options
- * @returns True if HF1 gte HF2
- */
- Common.prototype.hardforkGteHardfork = function (hardfork1, hardfork2, opts) {
- opts = opts !== undefined ? opts : {};
- var onlyActive = opts.onlyActive === undefined ? false : opts.onlyActive;
- hardfork1 = this._chooseHardfork(hardfork1, opts.onlySupported);
- var hardforks;
- if (onlyActive) {
- hardforks = this.activeHardforks(null, opts);
- }
- else {
- hardforks = this.hardforks();
- }
- var posHf1 = -1, posHf2 = -1;
- var index = 0;
- for (var _i = 0, hardforks_2 = hardforks; _i < hardforks_2.length; _i++) {
- var hf = hardforks_2[_i];
- if (hf['name'] === hardfork1)
- posHf1 = index;
- if (hf['name'] === hardfork2)
- posHf2 = index;
- index += 1;
- }
- return posHf1 >= posHf2;
- };
- /**
- * Alias to hardforkGteHardfork when hardfork is set
- * @param hardfork Hardfork name
- * @param opts Hardfork options
- * @returns True if hardfork set is greater than hardfork provided
- */
- Common.prototype.gteHardfork = function (hardfork, opts) {
- return this.hardforkGteHardfork(null, hardfork, opts);
- };
- /**
- * Checks if given or set hardfork is active on the chain
- * @param hardfork Hardfork name, optional if HF set
- * @param opts Hardfork options (onlyActive unused)
- * @returns True if hardfork is active on the chain
- */
- Common.prototype.hardforkIsActiveOnChain = function (hardfork, opts) {
- opts = opts !== undefined ? opts : {};
- var onlySupported = opts.onlySupported === undefined ? false : opts.onlySupported;
- hardfork = this._chooseHardfork(hardfork, onlySupported);
- for (var _i = 0, _a = this.hardforks(); _i < _a.length; _i++) {
- var hf = _a[_i];
- if (hf['name'] === hardfork && hf['block'] !== null)
- return true;
- }
- return false;
- };
- /**
- * Returns the active hardfork switches for the current chain
- * @param blockNumber up to block if provided, otherwise for the whole chain
- * @param opts Hardfork options (onlyActive unused)
- * @return Array with hardfork arrays
- */
- Common.prototype.activeHardforks = function (blockNumber, opts) {
- opts = opts !== undefined ? opts : {};
- var activeHardforks = [];
- var hfs = this.hardforks();
- for (var _i = 0, hfs_2 = hfs; _i < hfs_2.length; _i++) {
- var hf = hfs_2[_i];
- if (hf['block'] === null)
- continue;
- if (blockNumber !== undefined && blockNumber !== null && blockNumber < hf['block'])
- break;
- if (opts.onlySupported && !this._isSupportedHardfork(hf['name']))
- continue;
- activeHardforks.push(hf);
- }
- return activeHardforks;
- };
- /**
- * Returns the latest active hardfork name for chain or block or throws if unavailable
- * @param blockNumber up to block if provided, otherwise for the whole chain
- * @param opts Hardfork options (onlyActive unused)
- * @return Hardfork name
- */
- Common.prototype.activeHardfork = function (blockNumber, opts) {
- opts = opts !== undefined ? opts : {};
- var activeHardforks = this.activeHardforks(blockNumber, opts);
- if (activeHardforks.length > 0) {
- return activeHardforks[activeHardforks.length - 1]['name'];
- }
- else {
- throw new Error("No (supported) active hardfork found");
- }
- };
- /**
- * Returns the hardfork change block for hardfork provided or set
- * @param hardfork Hardfork name, optional if HF set
- * @returns Block number
- */
- Common.prototype.hardforkBlock = function (hardfork) {
- hardfork = this._chooseHardfork(hardfork, false);
- return this._getHardfork(hardfork)['block'];
- };
- /**
- * True if block number provided is the hardfork (given or set) change block of the current chain
- * @param blockNumber Number of the block to check
- * @param hardfork Hardfork name, optional if HF set
- * @returns True if blockNumber is HF block
- */
- Common.prototype.isHardforkBlock = function (blockNumber, hardfork) {
- hardfork = this._chooseHardfork(hardfork, false);
- if (this.hardforkBlock(hardfork) === blockNumber) {
- return true;
- }
- else {
- return false;
- }
- };
- /**
- * Provide the consensus type for the hardfork set or provided as param
- * @param hardfork Hardfork name, optional if hardfork set
- * @returns Consensus type (e.g. 'pow', 'poa')
- */
- Common.prototype.consensus = function (hardfork) {
- hardfork = this._chooseHardfork(hardfork);
- return this._getHardfork(hardfork)['consensus'];
- };
- /**
- * Provide the finality type for the hardfork set or provided as param
- * @param {String} hardfork Hardfork name, optional if hardfork set
- * @returns {String} Finality type (e.g. 'pos', null of no finality)
- */
- Common.prototype.finality = function (hardfork) {
- hardfork = this._chooseHardfork(hardfork);
- return this._getHardfork(hardfork)['finality'];
- };
- /**
- * Returns the Genesis parameters of current chain
- * @returns Genesis dictionary
- */
- Common.prototype.genesis = function () {
- return this._chainParams['genesis'];
- };
- /**
- * Returns the hardforks for current chain
- * @returns {Array} Array with arrays of hardforks
- */
- Common.prototype.hardforks = function () {
- return this._chainParams['hardforks'];
- };
- /**
- * Returns bootstrap nodes for the current chain
- * @returns {Dictionary} Dict with bootstrap nodes
- */
- Common.prototype.bootstrapNodes = function () {
- return this._chainParams['bootstrapNodes'];
- };
- /**
- * Returns the hardfork set
- * @returns Hardfork name
- */
- Common.prototype.hardfork = function () {
- return this._hardfork;
- };
- /**
- * Returns the Id of current chain
- * @returns chain Id
- */
- Common.prototype.chainId = function () {
- return this._chainParams['chainId'];
- };
- /**
- * Returns the name of current chain
- * @returns chain name (lower case)
- */
- Common.prototype.chainName = function () {
- return chains_1.chains['names'][this.chainId()] || this._chainParams['name'];
- };
- /**
- * Returns the Id of current network
- * @returns network Id
- */
- Common.prototype.networkId = function () {
- return this._chainParams['networkId'];
- };
- return Common;
-}());
-exports.default = Common;
-
-},{"./chains":340,"./hardforks":350}],356:[function(require,module,exports){
-arguments[4][331][0].apply(exports,arguments)
-},{"_process":1438,"dup":331}],357:[function(require,module,exports){
-'use strict';
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-// See: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI
-var address_1 = require("./address");
-var bignumber_1 = require("./bignumber");
-var bytes_1 = require("./bytes");
-var utf8_1 = require("./utf8");
-var properties_1 = require("./properties");
-var errors = __importStar(require("./errors"));
-var paramTypeBytes = new RegExp(/^bytes([0-9]*)$/);
-var paramTypeNumber = new RegExp(/^(u?int)([0-9]*)$/);
-var paramTypeArray = new RegExp(/^(.*)\[([0-9]*)\]$/);
-exports.defaultCoerceFunc = function (type, value) {
- var match = type.match(paramTypeNumber);
- if (match && parseInt(match[2]) <= 48) {
- return value.toNumber();
- }
- return value;
-};
-///////////////////////////////////
-// Parsing for Solidity Signatures
-var regexParen = new RegExp("^([^)(]*)\\((.*)\\)([^)(]*)$");
-var regexIdentifier = new RegExp("^[A-Za-z_][A-Za-z0-9_]*$");
-function verifyType(type) {
- // These need to be transformed to their full description
- if (type.match(/^uint($|[^1-9])/)) {
- type = 'uint256' + type.substring(4);
- }
- else if (type.match(/^int($|[^1-9])/)) {
- type = 'int256' + type.substring(3);
- }
- return type;
-}
-function parseParam(param, allowIndexed) {
- function throwError(i) {
- throw new Error('unexpected character "' + param[i] + '" at position ' + i + ' in "' + param + '"');
- }
- var parent = { type: '', name: '', state: { allowType: true } };
- var node = parent;
- for (var i = 0; i < param.length; i++) {
- var c = param[i];
- switch (c) {
- case '(':
- if (!node.state.allowParams) {
- throwError(i);
- }
- node.state.allowType = false;
- node.type = verifyType(node.type);
- node.components = [{ type: '', name: '', parent: node, state: { allowType: true } }];
- node = node.components[0];
- break;
- case ')':
- delete node.state;
- if (allowIndexed && node.name === 'indexed') {
- node.indexed = true;
- node.name = '';
- }
- node.type = verifyType(node.type);
- var child = node;
- node = node.parent;
- if (!node) {
- throwError(i);
- }
- delete child.parent;
- node.state.allowParams = false;
- node.state.allowName = true;
- node.state.allowArray = true;
- break;
- case ',':
- delete node.state;
- if (allowIndexed && node.name === 'indexed') {
- node.indexed = true;
- node.name = '';
- }
- node.type = verifyType(node.type);
- var sibling = { type: '', name: '', parent: node.parent, state: { allowType: true } };
- node.parent.components.push(sibling);
- delete node.parent;
- node = sibling;
- break;
- // Hit a space...
- case ' ':
- // If reading type, the type is done and may read a param or name
- if (node.state.allowType) {
- if (node.type !== '') {
- node.type = verifyType(node.type);
- delete node.state.allowType;
- node.state.allowName = true;
- node.state.allowParams = true;
- }
- }
- // If reading name, the name is done
- if (node.state.allowName) {
- if (node.name !== '') {
- if (allowIndexed && node.name === 'indexed') {
- node.indexed = true;
- node.name = '';
- }
- else {
- node.state.allowName = false;
- }
- }
- }
- break;
- case '[':
- if (!node.state.allowArray) {
- throwError(i);
- }
- node.type += c;
- node.state.allowArray = false;
- node.state.allowName = false;
- node.state.readArray = true;
- break;
- case ']':
- if (!node.state.readArray) {
- throwError(i);
- }
- node.type += c;
- node.state.readArray = false;
- node.state.allowArray = true;
- node.state.allowName = true;
- break;
- default:
- if (node.state.allowType) {
- node.type += c;
- node.state.allowParams = true;
- node.state.allowArray = true;
- }
- else if (node.state.allowName) {
- node.name += c;
- delete node.state.allowArray;
- }
- else if (node.state.readArray) {
- node.type += c;
- }
- else {
- throwError(i);
- }
- }
- }
- if (node.parent) {
- throw new Error("unexpected eof");
- }
- delete parent.state;
- if (allowIndexed && node.name === 'indexed') {
- node.indexed = true;
- node.name = '';
- }
- parent.type = verifyType(parent.type);
- return parent;
-}
-// @TODO: Better return type
-function parseSignatureEvent(fragment) {
- var abi = {
- anonymous: false,
- inputs: [],
- name: '',
- type: 'event'
- };
- var match = fragment.match(regexParen);
- if (!match) {
- throw new Error('invalid event: ' + fragment);
- }
- abi.name = match[1].trim();
- splitNesting(match[2]).forEach(function (param) {
- param = parseParam(param, true);
- param.indexed = !!param.indexed;
- abi.inputs.push(param);
- });
- match[3].split(' ').forEach(function (modifier) {
- switch (modifier) {
- case 'anonymous':
- abi.anonymous = true;
- break;
- case '':
- break;
- default:
- console.log('unknown modifier: ' + modifier);
- }
- });
- if (abi.name && !abi.name.match(regexIdentifier)) {
- throw new Error('invalid identifier: "' + abi.name + '"');
- }
- return abi;
-}
-function parseSignatureFunction(fragment) {
- var abi = {
- constant: false,
- inputs: [],
- name: '',
- outputs: [],
- payable: false,
- stateMutability: null,
- type: 'function'
- };
- var comps = fragment.split(' returns ');
- var left = comps[0].match(regexParen);
- if (!left) {
- throw new Error('invalid signature');
- }
- abi.name = left[1].trim();
- if (!abi.name.match(regexIdentifier)) {
- throw new Error('invalid identifier: "' + left[1] + '"');
- }
- splitNesting(left[2]).forEach(function (param) {
- abi.inputs.push(parseParam(param));
- });
- left[3].split(' ').forEach(function (modifier) {
- switch (modifier) {
- case 'constant':
- abi.constant = true;
- break;
- case 'payable':
- abi.payable = true;
- break;
- case 'pure':
- abi.constant = true;
- abi.stateMutability = 'pure';
- break;
- case 'view':
- abi.constant = true;
- abi.stateMutability = 'view';
- break;
- case '':
- break;
- default:
- console.log('unknown modifier: ' + modifier);
- }
- });
- // We have outputs
- if (comps.length > 1) {
- var right = comps[1].match(regexParen);
- if (right[1].trim() != '' || right[3].trim() != '') {
- throw new Error('unexpected tokens');
- }
- splitNesting(right[2]).forEach(function (param) {
- abi.outputs.push(parseParam(param));
- });
- }
- return abi;
-}
-function parseParamType(type) {
- return parseParam(type, true);
-}
-exports.parseParamType = parseParamType;
-// @TODO: Allow a second boolean to expose names
-function formatParamType(paramType) {
- return getParamCoder(exports.defaultCoerceFunc, paramType).type;
-}
-exports.formatParamType = formatParamType;
-// @TODO: Allow a second boolean to expose names and modifiers
-function formatSignature(fragment) {
- return fragment.name + '(' + fragment.inputs.map(function (i) { return formatParamType(i); }).join(',') + ')';
-}
-exports.formatSignature = formatSignature;
-function parseSignature(fragment) {
- if (typeof (fragment) === 'string') {
- // Make sure the "returns" is surrounded by a space and all whitespace is exactly one space
- fragment = fragment.replace(/\(/g, ' (').replace(/\)/g, ') ').replace(/\s+/g, ' ');
- fragment = fragment.trim();
- if (fragment.substring(0, 6) === 'event ') {
- return parseSignatureEvent(fragment.substring(6).trim());
- }
- else {
- if (fragment.substring(0, 9) === 'function ') {
- fragment = fragment.substring(9);
- }
- return parseSignatureFunction(fragment.trim());
- }
- }
- throw new Error('unknown signature');
-}
-exports.parseSignature = parseSignature;
-var Coder = /** @class */ (function () {
- function Coder(coerceFunc, name, type, localName, dynamic) {
- this.coerceFunc = coerceFunc;
- this.name = name;
- this.type = type;
- this.localName = localName;
- this.dynamic = dynamic;
- }
- return Coder;
-}());
-// Clones the functionality of an existing Coder, but without a localName
-var CoderAnonymous = /** @class */ (function (_super) {
- __extends(CoderAnonymous, _super);
- function CoderAnonymous(coder) {
- var _this = _super.call(this, coder.coerceFunc, coder.name, coder.type, undefined, coder.dynamic) || this;
- properties_1.defineReadOnly(_this, 'coder', coder);
- return _this;
- }
- CoderAnonymous.prototype.encode = function (value) { return this.coder.encode(value); };
- CoderAnonymous.prototype.decode = function (data, offset) { return this.coder.decode(data, offset); };
- return CoderAnonymous;
-}(Coder));
-var CoderNull = /** @class */ (function (_super) {
- __extends(CoderNull, _super);
- function CoderNull(coerceFunc, localName) {
- return _super.call(this, coerceFunc, 'null', '', localName, false) || this;
- }
- CoderNull.prototype.encode = function (value) {
- return bytes_1.arrayify([]);
- };
- CoderNull.prototype.decode = function (data, offset) {
- if (offset > data.length) {
- throw new Error('invalid null');
- }
- return {
- consumed: 0,
- value: this.coerceFunc('null', undefined)
- };
- };
- return CoderNull;
-}(Coder));
-var CoderNumber = /** @class */ (function (_super) {
- __extends(CoderNumber, _super);
- function CoderNumber(coerceFunc, size, signed, localName) {
- var _this = this;
- var name = ((signed ? 'int' : 'uint') + (size * 8));
- _this = _super.call(this, coerceFunc, name, name, localName, false) || this;
- _this.size = size;
- _this.signed = signed;
- return _this;
- }
- CoderNumber.prototype.encode = function (value) {
- try {
- var v = bignumber_1.bigNumberify(value);
- v = v.toTwos(this.size * 8).maskn(this.size * 8);
- //value = value.toTwos(size * 8).maskn(size * 8);
- if (this.signed) {
- v = v.fromTwos(this.size * 8).toTwos(256);
- }
- return bytes_1.padZeros(bytes_1.arrayify(v), 32);
- }
- catch (error) {
- errors.throwError('invalid number value', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: this.name,
- value: value
- });
- }
- return null;
- };
- CoderNumber.prototype.decode = function (data, offset) {
- if (data.length < offset + 32) {
- errors.throwError('insufficient data for ' + this.name + ' type', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: this.name,
- value: bytes_1.hexlify(data.slice(offset, offset + 32))
- });
- }
- var junkLength = 32 - this.size;
- var value = bignumber_1.bigNumberify(data.slice(offset + junkLength, offset + 32));
- if (this.signed) {
- value = value.fromTwos(this.size * 8);
- }
- else {
- value = value.maskn(this.size * 8);
- }
- return {
- consumed: 32,
- value: this.coerceFunc(this.name, value),
- };
- };
- return CoderNumber;
-}(Coder));
-var uint256Coder = new CoderNumber(function (type, value) { return value; }, 32, false, 'none');
-var CoderBoolean = /** @class */ (function (_super) {
- __extends(CoderBoolean, _super);
- function CoderBoolean(coerceFunc, localName) {
- return _super.call(this, coerceFunc, 'bool', 'bool', localName, false) || this;
- }
- CoderBoolean.prototype.encode = function (value) {
- return uint256Coder.encode(!!value ? 1 : 0);
- };
- CoderBoolean.prototype.decode = function (data, offset) {
- try {
- var result = uint256Coder.decode(data, offset);
- }
- catch (error) {
- if (error.reason === 'insufficient data for uint256 type') {
- errors.throwError('insufficient data for boolean type', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'boolean',
- value: error.value
- });
- }
- throw error;
- }
- return {
- consumed: result.consumed,
- value: this.coerceFunc('bool', !result.value.isZero())
- };
- };
- return CoderBoolean;
-}(Coder));
-var CoderFixedBytes = /** @class */ (function (_super) {
- __extends(CoderFixedBytes, _super);
- function CoderFixedBytes(coerceFunc, length, localName) {
- var _this = this;
- var name = ('bytes' + length);
- _this = _super.call(this, coerceFunc, name, name, localName, false) || this;
- _this.length = length;
- return _this;
- }
- CoderFixedBytes.prototype.encode = function (value) {
- var result = new Uint8Array(32);
- try {
- var data = bytes_1.arrayify(value);
- if (data.length > 32) {
- throw new Error();
- }
- result.set(data);
- }
- catch (error) {
- errors.throwError('invalid ' + this.name + ' value', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: this.name,
- value: (error.value || value)
- });
- }
- return result;
- };
- CoderFixedBytes.prototype.decode = function (data, offset) {
- if (data.length < offset + 32) {
- errors.throwError('insufficient data for ' + name + ' type', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: this.name,
- value: bytes_1.hexlify(data.slice(offset, offset + 32))
- });
- }
- return {
- consumed: 32,
- value: this.coerceFunc(this.name, bytes_1.hexlify(data.slice(offset, offset + this.length)))
- };
- };
- return CoderFixedBytes;
-}(Coder));
-var CoderAddress = /** @class */ (function (_super) {
- __extends(CoderAddress, _super);
- function CoderAddress(coerceFunc, localName) {
- return _super.call(this, coerceFunc, 'address', 'address', localName, false) || this;
- }
- CoderAddress.prototype.encode = function (value) {
- var result = new Uint8Array(32);
- try {
- result.set(bytes_1.arrayify(address_1.getAddress(value)), 12);
- }
- catch (error) {
- errors.throwError('invalid address', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'address',
- value: value
- });
- }
- return result;
- };
- CoderAddress.prototype.decode = function (data, offset) {
- if (data.length < offset + 32) {
- errors.throwError('insufficuent data for address type', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'address',
- value: bytes_1.hexlify(data.slice(offset, offset + 32))
- });
- }
- return {
- consumed: 32,
- value: this.coerceFunc('address', address_1.getAddress(bytes_1.hexlify(data.slice(offset + 12, offset + 32))))
- };
- };
- return CoderAddress;
-}(Coder));
-function _encodeDynamicBytes(value) {
- var dataLength = 32 * Math.ceil(value.length / 32);
- var padding = new Uint8Array(dataLength - value.length);
- return bytes_1.concat([
- uint256Coder.encode(value.length),
- value,
- padding
- ]);
-}
-function _decodeDynamicBytes(data, offset, localName) {
- if (data.length < offset + 32) {
- errors.throwError('insufficient data for dynamicBytes length', errors.INVALID_ARGUMENT, {
- arg: localName,
- coderType: 'dynamicBytes',
- value: bytes_1.hexlify(data.slice(offset, offset + 32))
- });
- }
- var length = uint256Coder.decode(data, offset).value;
- try {
- length = length.toNumber();
- }
- catch (error) {
- errors.throwError('dynamic bytes count too large', errors.INVALID_ARGUMENT, {
- arg: localName,
- coderType: 'dynamicBytes',
- value: length.toString()
- });
- }
- if (data.length < offset + 32 + length) {
- errors.throwError('insufficient data for dynamicBytes type', errors.INVALID_ARGUMENT, {
- arg: localName,
- coderType: 'dynamicBytes',
- value: bytes_1.hexlify(data.slice(offset, offset + 32 + length))
- });
- }
- return {
- consumed: 32 + 32 * Math.ceil(length / 32),
- value: data.slice(offset + 32, offset + 32 + length),
- };
-}
-var CoderDynamicBytes = /** @class */ (function (_super) {
- __extends(CoderDynamicBytes, _super);
- function CoderDynamicBytes(coerceFunc, localName) {
- return _super.call(this, coerceFunc, 'bytes', 'bytes', localName, true) || this;
- }
- CoderDynamicBytes.prototype.encode = function (value) {
- try {
- return _encodeDynamicBytes(bytes_1.arrayify(value));
- }
- catch (error) {
- errors.throwError('invalid bytes value', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'bytes',
- value: error.value
- });
- }
- return null;
- };
- CoderDynamicBytes.prototype.decode = function (data, offset) {
- var result = _decodeDynamicBytes(data, offset, this.localName);
- result.value = this.coerceFunc('bytes', bytes_1.hexlify(result.value));
- return result;
- };
- return CoderDynamicBytes;
-}(Coder));
-var CoderString = /** @class */ (function (_super) {
- __extends(CoderString, _super);
- function CoderString(coerceFunc, localName) {
- return _super.call(this, coerceFunc, 'string', 'string', localName, true) || this;
- }
- CoderString.prototype.encode = function (value) {
- if (typeof (value) !== 'string') {
- errors.throwError('invalid string value', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'string',
- value: value
- });
- }
- return _encodeDynamicBytes(utf8_1.toUtf8Bytes(value));
- };
- CoderString.prototype.decode = function (data, offset) {
- var result = _decodeDynamicBytes(data, offset, this.localName);
- result.value = this.coerceFunc('string', utf8_1.toUtf8String(result.value));
- return result;
- };
- return CoderString;
-}(Coder));
-function alignSize(size) {
- return 32 * Math.ceil(size / 32);
-}
-function pack(coders, values) {
- if (Array.isArray(values)) {
- // do nothing
- }
- else if (values && typeof (values) === 'object') {
- var arrayValues = [];
- coders.forEach(function (coder) {
- arrayValues.push(values[coder.localName]);
- });
- values = arrayValues;
- }
- else {
- errors.throwError('invalid tuple value', errors.INVALID_ARGUMENT, {
- coderType: 'tuple',
- value: values
- });
- }
- if (coders.length !== values.length) {
- errors.throwError('types/value length mismatch', errors.INVALID_ARGUMENT, {
- coderType: 'tuple',
- value: values
- });
- }
- var parts = [];
- coders.forEach(function (coder, index) {
- parts.push({ dynamic: coder.dynamic, value: coder.encode(values[index]) });
- });
- var staticSize = 0, dynamicSize = 0;
- parts.forEach(function (part) {
- if (part.dynamic) {
- staticSize += 32;
- dynamicSize += alignSize(part.value.length);
- }
- else {
- staticSize += alignSize(part.value.length);
- }
- });
- var offset = 0, dynamicOffset = staticSize;
- var data = new Uint8Array(staticSize + dynamicSize);
- parts.forEach(function (part) {
- if (part.dynamic) {
- //uint256Coder.encode(dynamicOffset).copy(data, offset);
- data.set(uint256Coder.encode(dynamicOffset), offset);
- offset += 32;
- //part.value.copy(data, dynamicOffset); @TODO
- data.set(part.value, dynamicOffset);
- dynamicOffset += alignSize(part.value.length);
- }
- else {
- //part.value.copy(data, offset); @TODO
- data.set(part.value, offset);
- offset += alignSize(part.value.length);
- }
- });
- return data;
-}
-function unpack(coders, data, offset) {
- var baseOffset = offset;
- var consumed = 0;
- var value = [];
- coders.forEach(function (coder) {
- if (coder.dynamic) {
- var dynamicOffset = uint256Coder.decode(data, offset);
- var result = coder.decode(data, baseOffset + dynamicOffset.value.toNumber());
- // The dynamic part is leap-frogged somewhere else; doesn't count towards size
- result.consumed = dynamicOffset.consumed;
- }
- else {
- var result = coder.decode(data, offset);
- }
- if (result.value != undefined) {
- value.push(result.value);
- }
- offset += result.consumed;
- consumed += result.consumed;
- });
- coders.forEach(function (coder, index) {
- var name = coder.localName;
- if (!name) {
- return;
- }
- if (name === 'length') {
- name = '_length';
- }
- if (value[name] != null) {
- return;
- }
- value[name] = value[index];
- });
- return {
- value: value,
- consumed: consumed
- };
-}
-var CoderArray = /** @class */ (function (_super) {
- __extends(CoderArray, _super);
- function CoderArray(coerceFunc, coder, length, localName) {
- var _this = this;
- var type = (coder.type + '[' + (length >= 0 ? length : '') + ']');
- var dynamic = (length === -1 || coder.dynamic);
- _this = _super.call(this, coerceFunc, 'array', type, localName, dynamic) || this;
- _this.coder = coder;
- _this.length = length;
- return _this;
- }
- CoderArray.prototype.encode = function (value) {
- if (!Array.isArray(value)) {
- errors.throwError('expected array value', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'array',
- value: value
- });
- }
- var count = this.length;
- var result = new Uint8Array(0);
- if (count === -1) {
- count = value.length;
- result = uint256Coder.encode(count);
- }
- errors.checkArgumentCount(count, value.length, 'in coder array' + (this.localName ? (" " + this.localName) : ""));
- var coders = [];
- for (var i = 0; i < value.length; i++) {
- coders.push(this.coder);
- }
- return bytes_1.concat([result, pack(coders, value)]);
- };
- CoderArray.prototype.decode = function (data, offset) {
- // @TODO:
- //if (data.length < offset + length * 32) { throw new Error('invalid array'); }
- var consumed = 0;
- var count = this.length;
- if (count === -1) {
- try {
- var decodedLength = uint256Coder.decode(data, offset);
- }
- catch (error) {
- errors.throwError('insufficient data for dynamic array length', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'array',
- value: error.value
- });
- }
- try {
- count = decodedLength.value.toNumber();
- }
- catch (error) {
- errors.throwError('array count too large', errors.INVALID_ARGUMENT, {
- arg: this.localName,
- coderType: 'array',
- value: decodedLength.value.toString()
- });
- }
- consumed += decodedLength.consumed;
- offset += decodedLength.consumed;
- }
- var coders = [];
- for (var i = 0; i < count; i++) {
- coders.push(new CoderAnonymous(this.coder));
- }
- var result = unpack(coders, data, offset);
- result.consumed += consumed;
- result.value = this.coerceFunc(this.type, result.value);
- return result;
- };
- return CoderArray;
-}(Coder));
-var CoderTuple = /** @class */ (function (_super) {
- __extends(CoderTuple, _super);
- function CoderTuple(coerceFunc, coders, localName) {
- var _this = this;
- var dynamic = false;
- var types = [];
- coders.forEach(function (coder) {
- if (coder.dynamic) {
- dynamic = true;
- }
- types.push(coder.type);
- });
- var type = ('tuple(' + types.join(',') + ')');
- _this = _super.call(this, coerceFunc, 'tuple', type, localName, dynamic) || this;
- _this.coders = coders;
- return _this;
- }
- CoderTuple.prototype.encode = function (value) {
- return pack(this.coders, value);
- };
- CoderTuple.prototype.decode = function (data, offset) {
- var result = unpack(this.coders, data, offset);
- result.value = this.coerceFunc(this.type, result.value);
- return result;
- };
- return CoderTuple;
-}(Coder));
-/*
-function getTypes(coders) {
- var type = coderTuple(coders).type;
- return type.substring(6, type.length - 1);
-}
-*/
-function splitNesting(value) {
- var result = [];
- var accum = '';
- var depth = 0;
- for (var offset = 0; offset < value.length; offset++) {
- var c = value[offset];
- if (c === ',' && depth === 0) {
- result.push(accum);
- accum = '';
- }
- else {
- accum += c;
- if (c === '(') {
- depth++;
- }
- else if (c === ')') {
- depth--;
- if (depth === -1) {
- throw new Error('unbalanced parenthsis');
- }
- }
- }
- }
- result.push(accum);
- return result;
-}
-// @TODO: Is there a way to return "class"?
-var paramTypeSimple = {
- address: CoderAddress,
- bool: CoderBoolean,
- string: CoderString,
- bytes: CoderDynamicBytes,
-};
-function getTupleParamCoder(coerceFunc, components, localName) {
- if (!components) {
- components = [];
- }
- var coders = [];
- components.forEach(function (component) {
- coders.push(getParamCoder(coerceFunc, component));
- });
- return new CoderTuple(coerceFunc, coders, localName);
-}
-function getParamCoder(coerceFunc, param) {
- var coder = paramTypeSimple[param.type];
- if (coder) {
- return new coder(coerceFunc, param.name);
- }
- var match = param.type.match(paramTypeNumber);
- if (match) {
- var size = parseInt(match[2] || "256");
- if (size === 0 || size > 256 || (size % 8) !== 0) {
- errors.throwError('invalid ' + match[1] + ' bit length', errors.INVALID_ARGUMENT, {
- arg: 'param',
- value: param
- });
- }
- return new CoderNumber(coerceFunc, size / 8, (match[1] === 'int'), param.name);
- }
- var match = param.type.match(paramTypeBytes);
- if (match) {
- var size = parseInt(match[1]);
- if (size === 0 || size > 32) {
- errors.throwError('invalid bytes length', errors.INVALID_ARGUMENT, {
- arg: 'param',
- value: param
- });
- }
- return new CoderFixedBytes(coerceFunc, size, param.name);
- }
- var match = param.type.match(paramTypeArray);
- if (match) {
- var size = parseInt(match[2] || "-1");
- param = properties_1.jsonCopy(param);
- param.type = match[1];
- return new CoderArray(coerceFunc, getParamCoder(coerceFunc, param), size, param.name);
- }
- if (param.type.substring(0, 5) === 'tuple') {
- return getTupleParamCoder(coerceFunc, param.components, param.name);
- }
- if (param.type === '') {
- return new CoderNull(coerceFunc, param.name);
- }
- errors.throwError('invalid type', errors.INVALID_ARGUMENT, {
- arg: 'type',
- value: param.type
- });
- return null;
-}
-var AbiCoder = /** @class */ (function () {
- function AbiCoder(coerceFunc) {
- errors.checkNew(this, AbiCoder);
- if (!coerceFunc) {
- coerceFunc = exports.defaultCoerceFunc;
- }
- properties_1.defineReadOnly(this, 'coerceFunc', coerceFunc);
- }
- AbiCoder.prototype.encode = function (types, values) {
- if (types.length !== values.length) {
- errors.throwError('types/values length mismatch', errors.INVALID_ARGUMENT, {
- count: { types: types.length, values: values.length },
- value: { types: types, values: values }
- });
- }
- var coders = [];
- types.forEach(function (type) {
- // Convert types to type objects
- // - "uint foo" => { type: "uint", name: "foo" }
- // - "tuple(uint, uint)" => { type: "tuple", components: [ { type: "uint" }, { type: "uint" }, ] }
- var typeObject = null;
- if (typeof (type) === 'string') {
- typeObject = parseParam(type);
- }
- else {
- typeObject = type;
- }
- coders.push(getParamCoder(this.coerceFunc, typeObject));
- }, this);
- return bytes_1.hexlify(new CoderTuple(this.coerceFunc, coders, '_').encode(values));
- };
- AbiCoder.prototype.decode = function (types, data) {
- var coders = [];
- types.forEach(function (type) {
- // See encode for details
- var typeObject = null;
- if (typeof (type) === 'string') {
- typeObject = parseParam(type);
- }
- else {
- typeObject = properties_1.jsonCopy(type);
- }
- coders.push(getParamCoder(this.coerceFunc, typeObject));
- }, this);
- return new CoderTuple(this.coerceFunc, coders, '_').decode(bytes_1.arrayify(data), 0).value;
- };
- return AbiCoder;
-}());
-exports.AbiCoder = AbiCoder;
-exports.defaultAbiCoder = new AbiCoder();
-
-},{"./address":358,"./bignumber":359,"./bytes":360,"./errors":361,"./properties":363,"./utf8":366}],358:[function(require,module,exports){
-'use strict';
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-// We use this for base 36 maths
-var bn_js_1 = __importDefault(require("bn.js"));
-var bytes_1 = require("./bytes");
-var keccak256_1 = require("./keccak256");
-var rlp_1 = require("./rlp");
-var errors = require("./errors");
-function getChecksumAddress(address) {
- if (typeof (address) !== 'string' || !address.match(/^0x[0-9A-Fa-f]{40}$/)) {
- errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address });
- }
- address = address.toLowerCase();
- var chars = address.substring(2).split('');
- var hashed = new Uint8Array(40);
- for (var i_1 = 0; i_1 < 40; i_1++) {
- hashed[i_1] = chars[i_1].charCodeAt(0);
- }
- hashed = bytes_1.arrayify(keccak256_1.keccak256(hashed));
- for (var i = 0; i < 40; i += 2) {
- if ((hashed[i >> 1] >> 4) >= 8) {
- chars[i] = chars[i].toUpperCase();
- }
- if ((hashed[i >> 1] & 0x0f) >= 8) {
- chars[i + 1] = chars[i + 1].toUpperCase();
- }
- }
- return '0x' + chars.join('');
-}
-// Shims for environments that are missing some required constants and functions
-var MAX_SAFE_INTEGER = 0x1fffffffffffff;
-function log10(x) {
- if (Math.log10) {
- return Math.log10(x);
- }
- return Math.log(x) / Math.LN10;
-}
-// See: https://en.wikipedia.org/wiki/International_Bank_Account_Number
-// Create lookup table
-var ibanLookup = {};
-for (var i = 0; i < 10; i++) {
- ibanLookup[String(i)] = String(i);
-}
-for (var i = 0; i < 26; i++) {
- ibanLookup[String.fromCharCode(65 + i)] = String(10 + i);
-}
-// How many decimal digits can we process? (for 64-bit float, this is 15)
-var safeDigits = Math.floor(log10(MAX_SAFE_INTEGER));
-function ibanChecksum(address) {
- address = address.toUpperCase();
- address = address.substring(4) + address.substring(0, 2) + '00';
- var expanded = '';
- address.split('').forEach(function (c) {
- expanded += ibanLookup[c];
- });
- // Javascript can handle integers safely up to 15 (decimal) digits
- while (expanded.length >= safeDigits) {
- var block = expanded.substring(0, safeDigits);
- expanded = parseInt(block, 10) % 97 + expanded.substring(block.length);
- }
- var checksum = String(98 - (parseInt(expanded, 10) % 97));
- while (checksum.length < 2) {
- checksum = '0' + checksum;
- }
- return checksum;
-}
-;
-function getAddress(address) {
- var result = null;
- if (typeof (address) !== 'string') {
- errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address });
- }
- if (address.match(/^(0x)?[0-9a-fA-F]{40}$/)) {
- // Missing the 0x prefix
- if (address.substring(0, 2) !== '0x') {
- address = '0x' + address;
- }
- result = getChecksumAddress(address);
- // It is a checksummed address with a bad checksum
- if (address.match(/([A-F].*[a-f])|([a-f].*[A-F])/) && result !== address) {
- errors.throwError('bad address checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address });
- }
- // Maybe ICAP? (we only support direct mode)
- }
- else if (address.match(/^XE[0-9]{2}[0-9A-Za-z]{30,31}$/)) {
- // It is an ICAP address with a bad checksum
- if (address.substring(2, 4) !== ibanChecksum(address)) {
- errors.throwError('bad icap checksum', errors.INVALID_ARGUMENT, { arg: 'address', value: address });
- }
- result = (new bn_js_1.default.BN(address.substring(4), 36)).toString(16);
- while (result.length < 40) {
- result = '0' + result;
- }
- result = getChecksumAddress('0x' + result);
- }
- else {
- errors.throwError('invalid address', errors.INVALID_ARGUMENT, { arg: 'address', value: address });
- }
- return result;
-}
-exports.getAddress = getAddress;
-function getIcapAddress(address) {
- var base36 = (new bn_js_1.default.BN(getAddress(address).substring(2), 16)).toString(36).toUpperCase();
- while (base36.length < 30) {
- base36 = '0' + base36;
- }
- return 'XE' + ibanChecksum('XE00' + base36) + base36;
-}
-exports.getIcapAddress = getIcapAddress;
-// http://ethereum.stackexchange.com/questions/760/how-is-the-address-of-an-ethereum-contract-computed
-function getContractAddress(transaction) {
- if (!transaction.from) {
- throw new Error('missing from address');
- }
- var nonce = transaction.nonce;
- return getAddress('0x' + keccak256_1.keccak256(rlp_1.encode([
- getAddress(transaction.from),
- bytes_1.stripZeros(bytes_1.hexlify(nonce))
- ])).substring(26));
-}
-exports.getContractAddress = getContractAddress;
-
-},{"./bytes":360,"./errors":361,"./keccak256":362,"./rlp":364,"bn.js":171}],359:[function(require,module,exports){
-'use strict';
-var __extends = (this && this.__extends) || (function () {
- var extendStatics = Object.setPrototypeOf ||
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
- function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
- return function (d, b) {
- extendStatics(d, b);
- function __() { this.constructor = d; }
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
- };
-})();
-var __importDefault = (this && this.__importDefault) || function (mod) {
- return (mod && mod.__esModule) ? mod : { "default": mod };
-};
-var __importStar = (this && this.__importStar) || function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
- result["default"] = mod;
- return result;
-};
-Object.defineProperty(exports, "__esModule", { value: true });
-/**
- * BigNumber
- *
- * A wrapper around the BN.js object. We use the BN.js library
- * because it is used by elliptic, so it is required regardles.
- *
- */
-var bn_js_1 = __importDefault(require("bn.js"));
-var bytes_1 = require("./bytes");
-var properties_1 = require("./properties");
-var types_1 = require("./types");
-var errors = __importStar(require("./errors"));
-var BN_1 = new bn_js_1.default.BN(-1);
-function toHex(bn) {
- var value = bn.toString(16);
- if (value[0] === '-') {
- if ((value.length % 2) === 0) {
- return '-0x0' + value.substring(1);
- }
- return "-0x" + value.substring(1);
- }
- if ((value.length % 2) === 1) {
- return '0x0' + value;
- }
- return '0x' + value;
-}
-function toBN(value) {
- return bigNumberify(value)._bn;
-}
-function toBigNumber(bn) {
- return new BigNumber(toHex(bn));
-}
-var BigNumber = /** @class */ (function (_super) {
- __extends(BigNumber, _super);
- function BigNumber(value) {
- var _this = _super.call(this) || this;
- errors.checkNew(_this, BigNumber);
- if (typeof (value) === 'string') {
- if (bytes_1.isHexString(value)) {
- if (value == '0x') {
- value = '0x0';
- }
- properties_1.defineReadOnly(_this, '_hex', value);
- }
- else if (value[0] === '-' && bytes_1.isHexString(value.substring(1))) {
- properties_1.defineReadOnly(_this, '_hex', value);
- }
- else if (value.match(/^-?[0-9]*$/)) {
- if (value == '') {
- value = '0';
- }
- properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value)));
- }
- else {
- errors.throwError('invalid BigNumber string value', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- }
- else if (typeof (value) === 'number') {
- if (parseInt(String(value)) !== value) {
- errors.throwError('underflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'underflow', value: value, outputValue: parseInt(String(value)) });
- }
- try {
- properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(value)));
- }
- catch (error) {
- errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message });
- }
- }
- else if (value instanceof BigNumber) {
- properties_1.defineReadOnly(_this, '_hex', value._hex);
- }
- else if (value.toHexString) {
- properties_1.defineReadOnly(_this, '_hex', toHex(toBN(value.toHexString())));
- }
- else if (bytes_1.isArrayish(value)) {
- properties_1.defineReadOnly(_this, '_hex', toHex(new bn_js_1.default.BN(bytes_1.hexlify(value).substring(2), 16)));
- }
- else {
- errors.throwError('invalid BigNumber value', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- return _this;
- }
- Object.defineProperty(BigNumber.prototype, "_bn", {
- get: function () {
- if (this._hex[0] === '-') {
- return (new bn_js_1.default.BN(this._hex.substring(3), 16)).mul(BN_1);
- }
- return new bn_js_1.default.BN(this._hex.substring(2), 16);
- },
- enumerable: true,
- configurable: true
- });
- BigNumber.prototype.fromTwos = function (value) {
- return toBigNumber(this._bn.fromTwos(value));
- };
- BigNumber.prototype.toTwos = function (value) {
- return toBigNumber(this._bn.toTwos(value));
- };
- BigNumber.prototype.add = function (other) {
- return toBigNumber(this._bn.add(toBN(other)));
- };
- BigNumber.prototype.sub = function (other) {
- return toBigNumber(this._bn.sub(toBN(other)));
- };
- BigNumber.prototype.div = function (other) {
- var o = bigNumberify(other);
- if (o.isZero()) {
- errors.throwError('division by zero', errors.NUMERIC_FAULT, { operation: 'divide', fault: 'division by zero' });
- }
- return toBigNumber(this._bn.div(toBN(other)));
- };
- BigNumber.prototype.mul = function (other) {
- return toBigNumber(this._bn.mul(toBN(other)));
- };
- BigNumber.prototype.mod = function (other) {
- return toBigNumber(this._bn.mod(toBN(other)));
- };
- BigNumber.prototype.pow = function (other) {
- return toBigNumber(this._bn.pow(toBN(other)));
- };
- BigNumber.prototype.maskn = function (value) {
- return toBigNumber(this._bn.maskn(value));
- };
- BigNumber.prototype.eq = function (other) {
- return this._bn.eq(toBN(other));
- };
- BigNumber.prototype.lt = function (other) {
- return this._bn.lt(toBN(other));
- };
- BigNumber.prototype.lte = function (other) {
- return this._bn.lte(toBN(other));
- };
- BigNumber.prototype.gt = function (other) {
- return this._bn.gt(toBN(other));
- };
- BigNumber.prototype.gte = function (other) {
- return this._bn.gte(toBN(other));
- };
- BigNumber.prototype.isZero = function () {
- return this._bn.isZero();
- };
- BigNumber.prototype.toNumber = function () {
- try {
- return this._bn.toNumber();
- }
- catch (error) {
- errors.throwError('overflow', errors.NUMERIC_FAULT, { operation: 'setValue', fault: 'overflow', details: error.message });
- }
- return null;
- };
- BigNumber.prototype.toString = function () {
- return this._bn.toString(10);
- };
- BigNumber.prototype.toHexString = function () {
- return this._hex;
- };
- return BigNumber;
-}(types_1.BigNumber));
-function bigNumberify(value) {
- if (value instanceof BigNumber) {
- return value;
- }
- return new BigNumber(value);
-}
-exports.bigNumberify = bigNumberify;
-exports.ConstantNegativeOne = bigNumberify(-1);
-exports.ConstantZero = bigNumberify(0);
-exports.ConstantOne = bigNumberify(1);
-exports.ConstantTwo = bigNumberify(2);
-exports.ConstantWeiPerEther = bigNumberify('1000000000000000000');
-
-},{"./bytes":360,"./errors":361,"./properties":363,"./types":365,"bn.js":171}],360:[function(require,module,exports){
-"use strict";
-/**
- * Conversion Utilities
- *
- */
-Object.defineProperty(exports, "__esModule", { value: true });
-var types_1 = require("./types");
-var errors = require("./errors");
-exports.AddressZero = '0x0000000000000000000000000000000000000000';
-exports.HashZero = '0x0000000000000000000000000000000000000000000000000000000000000000';
-function isBigNumber(value) {
- return (value instanceof types_1.BigNumber);
-}
-function addSlice(array) {
- if (array.slice) {
- return array;
- }
- array.slice = function () {
- var args = Array.prototype.slice.call(arguments);
- return new Uint8Array(Array.prototype.slice.apply(array, args));
- };
- return array;
-}
-function isArrayish(value) {
- if (!value || parseInt(String(value.length)) != value.length || typeof (value) === 'string') {
- return false;
- }
- for (var i = 0; i < value.length; i++) {
- var v = value[i];
- if (v < 0 || v >= 256 || parseInt(String(v)) != v) {
- return false;
- }
- }
- return true;
-}
-exports.isArrayish = isArrayish;
-function arrayify(value) {
- if (value == null) {
- errors.throwError('cannot convert null value to array', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- if (isBigNumber(value)) {
- value = value.toHexString();
- }
- if (typeof (value) === 'string') {
- var match = value.match(/^(0x)?[0-9a-fA-F]*$/);
- if (!match) {
- errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- if (match[1] !== '0x') {
- errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- value = value.substring(2);
- if (value.length % 2) {
- value = '0' + value;
- }
- var result = [];
- for (var i = 0; i < value.length; i += 2) {
- result.push(parseInt(value.substr(i, 2), 16));
- }
- return addSlice(new Uint8Array(result));
- }
- else if (typeof (value) === 'string') {
- }
- if (isArrayish(value)) {
- return addSlice(new Uint8Array(value));
- }
- errors.throwError('invalid arrayify value', null, { arg: 'value', value: value, type: typeof (value) });
- return null;
-}
-exports.arrayify = arrayify;
-function concat(objects) {
- var arrays = [];
- var length = 0;
- for (var i = 0; i < objects.length; i++) {
- var object = arrayify(objects[i]);
- arrays.push(object);
- length += object.length;
- }
- var result = new Uint8Array(length);
- var offset = 0;
- for (var i = 0; i < arrays.length; i++) {
- result.set(arrays[i], offset);
- offset += arrays[i].length;
- }
- return addSlice(result);
-}
-exports.concat = concat;
-function stripZeros(value) {
- var result = arrayify(value);
- if (result.length === 0) {
- return result;
- }
- // Find the first non-zero entry
- var start = 0;
- while (result[start] === 0) {
- start++;
- }
- // If we started with zeros, strip them
- if (start) {
- result = result.slice(start);
- }
- return result;
-}
-exports.stripZeros = stripZeros;
-function padZeros(value, length) {
- value = arrayify(value);
- if (length < value.length) {
- throw new Error('cannot pad');
- }
- var result = new Uint8Array(length);
- result.set(value, length - value.length);
- return addSlice(result);
-}
-exports.padZeros = padZeros;
-function isHexString(value, length) {
- if (typeof (value) !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
- return false;
- }
- if (length && value.length !== 2 + 2 * length) {
- return false;
- }
- return true;
-}
-exports.isHexString = isHexString;
-var HexCharacters = '0123456789abcdef';
-function hexlify(value) {
- if (isBigNumber(value)) {
- return value.toHexString();
- }
- if (typeof (value) === 'number') {
- if (value < 0) {
- errors.throwError('cannot hexlify negative value', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- var hex = '';
- while (value) {
- hex = HexCharacters[value & 0x0f] + hex;
- value = Math.floor(value / 16);
- }
- if (hex.length) {
- if (hex.length % 2) {
- hex = '0' + hex;
- }
- return '0x' + hex;
- }
- return '0x00';
- }
- if (typeof (value) === 'string') {
- var match = value.match(/^(0x)?[0-9a-fA-F]*$/);
- if (!match) {
- errors.throwError('invalid hexidecimal string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- if (match[1] !== '0x') {
- errors.throwError('hex string must have 0x prefix', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- if (value.length % 2) {
- value = '0x0' + value.substring(2);
- }
- return value;
- }
- if (isArrayish(value)) {
- var result = [];
- for (var i = 0; i < value.length; i++) {
- var v = value[i];
- result.push(HexCharacters[(v & 0xf0) >> 4] + HexCharacters[v & 0x0f]);
- }
- return '0x' + result.join('');
- }
- errors.throwError('invalid hexlify value', null, { arg: 'value', value: value });
- return 'never';
-}
-exports.hexlify = hexlify;
-function hexDataLength(data) {
- if (!isHexString(data) || (data.length % 2) !== 0) {
- return null;
- }
- return (data.length - 2) / 2;
-}
-exports.hexDataLength = hexDataLength;
-function hexDataSlice(data, offset, length) {
- if (!isHexString(data)) {
- errors.throwError('invalid hex data', errors.INVALID_ARGUMENT, { arg: 'value', value: data });
- }
- if ((data.length % 2) !== 0) {
- errors.throwError('hex data length must be even', errors.INVALID_ARGUMENT, { arg: 'value', value: data });
- }
- offset = 2 + 2 * offset;
- if (length != null) {
- return '0x' + data.substring(offset, offset + 2 * length);
- }
- return '0x' + data.substring(offset);
-}
-exports.hexDataSlice = hexDataSlice;
-function hexStripZeros(value) {
- if (!isHexString(value)) {
- errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- while (value.length > 3 && value.substring(0, 3) === '0x0') {
- value = '0x' + value.substring(3);
- }
- return value;
-}
-exports.hexStripZeros = hexStripZeros;
-function hexZeroPad(value, length) {
- if (!isHexString(value)) {
- errors.throwError('invalid hex string', errors.INVALID_ARGUMENT, { arg: 'value', value: value });
- }
- while (value.length < 2 * length + 2) {
- value = '0x0' + value.substring(2);
- }
- return value;
-}
-exports.hexZeroPad = hexZeroPad;
-function isSignature(value) {
- return (value && value.r != null && value.s != null);
-}
-function splitSignature(signature) {
- var v = 0;
- var r = '0x', s = '0x';
- if (isSignature(signature)) {
- if (signature.v == null && signature.recoveryParam == null) {
- errors.throwError('at least on of recoveryParam or v must be specified', errors.INVALID_ARGUMENT, { argument: 'signature', value: signature });
- }
- r = hexZeroPad(signature.r, 32);
- s = hexZeroPad(signature.s, 32);
- v = signature.v;
- if (typeof (v) === 'string') {
- v = parseInt(v, 16);
- }
- var recoveryParam = signature.recoveryParam;
- if (recoveryParam == null && signature.v != null) {
- recoveryParam = 1 - (v % 2);
- }
- v = 27 + recoveryParam;
- }
- else {
- var bytes = arrayify(signature);
- if (bytes.length !== 65) {
- throw new Error('invalid signature');
- }
- r = hexlify(bytes.slice(0, 32));
- s = hexlify(bytes.slice(32, 64));
- v = bytes[64];
- if (v !== 27 && v !== 28) {
- v = 27 + (v % 2);
- }
- }
- return {
- r: r,
- s: s,
- recoveryParam: (v - 27),
- v: v
- };
-}
-exports.splitSignature = splitSignature;
-function joinSignature(signature) {
- signature = splitSignature(signature);
- return hexlify(concat([
- signature.r,
- signature.s,
- (signature.recoveryParam ? '0x1c' : '0x1b')
- ]));
-}
-exports.joinSignature = joinSignature;
-
-},{"./errors":361,"./types":365}],361:[function(require,module,exports){
-'use strict';
-Object.defineProperty(exports, "__esModule", { value: true });
-// Unknown Error
-exports.UNKNOWN_ERROR = 'UNKNOWN_ERROR';
-// Not implemented
-exports.NOT_IMPLEMENTED = 'NOT_IMPLEMENTED';
-// Missing new operator to an object
-// - name: The name of the class
-exports.MISSING_NEW = 'MISSING_NEW';
-// Call exception
-// - transaction: the transaction
-// - address?: the contract address
-// - args?: The arguments passed into the function
-// - method?: The Solidity method signature
-// - errorSignature?: The EIP848 error signature
-// - errorArgs?: The EIP848 error parameters
-// - reason: The reason (only for EIP848 "Error(string)")
-exports.CALL_EXCEPTION = 'CALL_EXCEPTION';
-// Response from a server was invalid
-// - response: The body of the response
-//'BAD_RESPONSE',
-// Invalid argument (e.g. value is incompatible with type) to a function:
-// - arg: The argument name that was invalid
-// - value: The value of the argument
-exports.INVALID_ARGUMENT = 'INVALID_ARGUMENT';
-// Missing argument to a function:
-// - count: The number of arguments received
-// - expectedCount: The number of arguments expected
-exports.MISSING_ARGUMENT = 'MISSING_ARGUMENT';
-// Too many arguments
-// - count: The number of arguments received
-// - expectedCount: The number of arguments expected
-exports.UNEXPECTED_ARGUMENT = 'UNEXPECTED_ARGUMENT';
-// Numeric Fault
-// - operation: the operation being executed
-// - fault: the reason this faulted
-exports.NUMERIC_FAULT = 'NUMERIC_FAULT';
-// Unsupported operation
-// - operation
-exports.UNSUPPORTED_OPERATION = 'UNSUPPORTED_OPERATION';
-var _permanentCensorErrors = false;
-var _censorErrors = false;
-// @TODO: Enum
-function throwError(message, code, params) {
- if (_censorErrors) {
- throw new Error('unknown error');
- }
- if (!code) {
- code = exports.UNKNOWN_ERROR;
- }
- if (!params) {
- params = {};
- }
- var messageDetails = [];
- Object.keys(params).forEach(function (key) {
- try {
- messageDetails.push(key + '=' + JSON.stringify(params[key]));
- }
- catch (error) {
- messageDetails.push(key + '=' + JSON.stringify(params[key].toString()));
- }
- });
- var reason = message;
- if (messageDetails.length) {
- message += ' (' + messageDetails.join(', ') + ')';
- }
- // @TODO: Any??
- var error = new Error(message);
- error.reason = reason;
- error.code = code;
- Object.keys(params).forEach(function (key) {
- error[key] = params[key];
- });
- throw error;
-}
-exports.throwError = throwError;
-function checkNew(self, kind) {
- if (!(self instanceof kind)) {
- throwError('missing new', exports.MISSING_NEW, { name: kind.name });
- }
-}
-exports.checkNew = checkNew;
-function checkArgumentCount(count, expectedCount, suffix) {
- if (!suffix) {
- suffix = '';
- }
- if (count < expectedCount) {
- throwError('missing argument' + suffix, exports.MISSING_ARGUMENT, { count: count, expectedCount: expectedCount });
- }
- if (count > expectedCount) {
- throwError('too many arguments' + suffix, exports.UNEXPECTED_ARGUMENT, { count: count, expectedCount: expectedCount });
- }
-}
-exports.checkArgumentCount = checkArgumentCount;
-function setCensorship(censorship, permanent) {
- if (_permanentCensorErrors) {
- throwError('error censorship permanent', exports.UNSUPPORTED_OPERATION, { operation: 'setCersorship' });
- }
- _censorErrors = !!censorship;
- _permanentCensorErrors = !!permanent;
-}
-exports.setCensorship = setCensorship;
-
-},{}],362:[function(require,module,exports){
-'use strict';
-Object.defineProperty(exports, "__esModule", { value: true });
-var sha3 = require("js-sha3");
-var bytes_1 = require("./bytes");
-function keccak256(data) {
- return '0x' + sha3.keccak_256(bytes_1.arrayify(data));
-}
-exports.keccak256 = keccak256;
-
-},{"./bytes":360,"js-sha3":356}],363:[function(require,module,exports){
-'use strict';
-Object.defineProperty(exports, "__esModule", { value: true });
-function defineReadOnly(object, name, value) {
- Object.defineProperty(object, name, {
- enumerable: true,
- value: value,
- writable: false,
- });
-}
-exports.defineReadOnly = defineReadOnly;
-function defineFrozen(object, name, value) {
- var frozen = JSON.stringify(value);
- Object.defineProperty(object, name, {
- enumerable: true,
- get: function () { return JSON.parse(frozen); }
- });
-}
-exports.defineFrozen = defineFrozen;
-function resolveProperties(object) {
- var result = {};
- var promises = [];
- Object.keys(object).forEach(function (key) {
- var value = object[key];
- if (value instanceof Promise) {
- promises.push(value.then(function (value) {
- result[key] = value;
- return null;
- }));
- }
- else {
- result[key] = value;
- }
- });
- return Promise.all(promises).then(function () {
- return result;
- });
-}
-exports.resolveProperties = resolveProperties;
-function shallowCopy(object) {
- var result = {};
- for (var key in object) {
- result[key] = object[key];
- }
- return result;
-}
-exports.shallowCopy = shallowCopy;
-function jsonCopy(object) {
- return JSON.parse(JSON.stringify(object));
-}
-exports.jsonCopy = jsonCopy;
-
-},{}],364:[function(require,module,exports){
-"use strict";
-//See: https://github.com/ethereum/wiki/wiki/RLP
-Object.defineProperty(exports, "__esModule", { value: true });
-var bytes_1 = require("./bytes");
-function arrayifyInteger(value) {
- var result = [];
- while (value) {
- result.unshift(value & 0xff);
- value >>= 8;
- }
- return result;
-}
-function unarrayifyInteger(data, offset, length) {
- var result = 0;
- for (var i = 0; i < length; i++) {
- result = (result * 256) + data[offset + i];
- }
- return result;
-}
-function _encode(object) {
- if (Array.isArray(object)) {
- var payload = [];
- object.forEach(function (child) {
- payload = payload.concat(_encode(child));
- });
- if (payload.length <= 55) {
- payload.unshift(0xc0 + payload.length);
- return payload;
- }
- var length = arrayifyInteger(payload.length);
- length.unshift(0xf7 + length.length);
- return length.concat(payload);
- }
- var data = Array.prototype.slice.call(bytes_1.arrayify(object));
- if (data.length === 1 && data[0] <= 0x7f) {
- return data;
- }
- else if (data.length <= 55) {
- data.unshift(0x80 + data.length);
- return data;
- }
- var length = arrayifyInteger(data.length);
- length.unshift(0xb7 + length.length);
- return length.concat(data);
-}
-function encode(object) {
- return bytes_1.hexlify(_encode(object));
-}
-exports.encode = encode;
-function _decodeChildren(data, offset, childOffset, length) {
- var result = [];
- while (childOffset < offset + 1 + length) {
- var decoded = _decode(data, childOffset);
- result.push(decoded.result);
- childOffset += decoded.consumed;
- if (childOffset > offset + 1 + length) {
- throw new Error('invalid rlp');
- }
- }
- return { consumed: (1 + length), result: result };
-}
-// returns { consumed: number, result: Object }
-function _decode(data, offset) {
- if (data.length === 0) {
- throw new Error('invalid rlp data');
- }
- // Array with extra length prefix
- if (data[offset] >= 0xf8) {
- var lengthLength = data[offset] - 0xf7;
- if (offset + 1 + lengthLength > data.length) {
- throw new Error('too short');
- }
- var length = unarrayifyInteger(data, offset + 1, lengthLength);
- if (offset + 1 + lengthLength + length > data.length) {
- throw new Error('to short');
- }
- return _decodeChildren(data, offset, offset + 1 + lengthLength, lengthLength + length);
- }
- else if (data[offset] >= 0xc0) {
- var length = data[offset] - 0xc0;
- if (offset + 1 + length > data.length) {
- throw new Error('invalid rlp data');
- }
- return _decodeChildren(data, offset, offset + 1, length);
- }
- else if (data[offset] >= 0xb8) {
- var lengthLength = data[offset] - 0xb7;
- if (offset + 1 + lengthLength > data.length) {
- throw new Error('invalid rlp data');
- }
- var length = unarrayifyInteger(data, offset + 1, lengthLength);
- if (offset + 1 + lengthLength + length > data.length) {
- throw new Error('invalid rlp data');
- }
- var result = bytes_1.hexlify(data.slice(offset + 1 + lengthLength, offset + 1 + lengthLength + length));
- return { consumed: (1 + lengthLength + length), result: result };
- }
- else if (data[offset] >= 0x80) {
- var length = data[offset] - 0x80;
- if (offset + 1 + length > data.length) {
- throw new Error('invlaid rlp data');
- }
- var result = bytes_1.hexlify(data.slice(offset + 1, offset + 1 + length));
- return { consumed: (1 + length), result: result };
- }
- return { consumed: 1, result: bytes_1.hexlify(data[offset]) };
-}
-function decode(data) {
- var bytes = bytes_1.arrayify(data);
- var decoded = _decode(bytes, 0);
- if (decoded.consumed !== bytes.length) {
- throw new Error('invalid rlp data');
- }
- return decoded.result;
-}
-exports.decode = decode;
-
-},{"./bytes":360}],365:[function(require,module,exports){
-"use strict";
-///////////////////////////////
-// Bytes
-Object.defineProperty(exports, "__esModule", { value: true });
-///////////////////////////////
-// BigNumber
-var BigNumber = /** @class */ (function () {
- function BigNumber() {
- }
- return BigNumber;
-}());
-exports.BigNumber = BigNumber;
-;
-;
-;
-///////////////////////////////
-// Interface
-var Indexed = /** @class */ (function () {
- function Indexed() {
- }
- return Indexed;
-}());
-exports.Indexed = Indexed;
-/**
- * Provider
- *
- * Note: We use an abstract class so we can use instanceof to determine if an
- * object is a Provider.
- */
-var MinimalProvider = /** @class */ (function () {
- function MinimalProvider() {
- }
- return MinimalProvider;
-}());
-exports.MinimalProvider = MinimalProvider;
-/**
- * Signer
- *
- * Note: We use an abstract class so we can use instanceof to determine if an
- * object is a Signer.
- */
-var Signer = /** @class */ (function () {
- function Signer() {
- }
- return Signer;
-}());
-exports.Signer = Signer;
-///////////////////////////////
-// HDNode
-var HDNode = /** @class */ (function () {
- function HDNode() {
- }
- return HDNode;
-}());
-exports.HDNode = HDNode;
-
-},{}],366:[function(require,module,exports){
-'use strict';
-Object.defineProperty(exports, "__esModule", { value: true });
-var bytes_1 = require("./bytes");
-var UnicodeNormalizationForm;
-(function (UnicodeNormalizationForm) {
- UnicodeNormalizationForm["current"] = "";
- UnicodeNormalizationForm["NFC"] = "NFC";
- UnicodeNormalizationForm["NFD"] = "NFD";
- UnicodeNormalizationForm["NFKC"] = "NFKC";
- UnicodeNormalizationForm["NFKD"] = "NFKD";
-})(UnicodeNormalizationForm = exports.UnicodeNormalizationForm || (exports.UnicodeNormalizationForm = {}));
-;
-// http://stackoverflow.com/questions/18729405/how-to-convert-utf8-string-to-byte-array
-function toUtf8Bytes(str, form) {
- if (form === void 0) { form = UnicodeNormalizationForm.current; }
- if (form != UnicodeNormalizationForm.current) {
- str = str.normalize(form);
- }
- var result = [];
- var offset = 0;
- for (var i = 0; i < str.length; i++) {
- var c = str.charCodeAt(i);
- if (c < 128) {
- result[offset++] = c;
- }
- else if (c < 2048) {
- result[offset++] = (c >> 6) | 192;
- result[offset++] = (c & 63) | 128;
- }
- else if (((c & 0xFC00) == 0xD800) && (i + 1) < str.length && ((str.charCodeAt(i + 1) & 0xFC00) == 0xDC00)) {
- // Surrogate Pair
- c = 0x10000 + ((c & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF);
- result[offset++] = (c >> 18) | 240;
- result[offset++] = ((c >> 12) & 63) | 128;
- result[offset++] = ((c >> 6) & 63) | 128;
- result[offset++] = (c & 63) | 128;
- }
- else {
- result[offset++] = (c >> 12) | 224;
- result[offset++] = ((c >> 6) & 63) | 128;
- result[offset++] = (c & 63) | 128;
- }
- }
- return bytes_1.arrayify(result);
-}
-exports.toUtf8Bytes = toUtf8Bytes;
-;
-// http://stackoverflow.com/questions/13356493/decode-utf-8-with-javascript#13691499
-function toUtf8String(bytes) {
- bytes = bytes_1.arrayify(bytes);
- var result = '';
- var i = 0;
- // Invalid bytes are ignored
- while (i < bytes.length) {
- var c = bytes[i++];
- if (c >> 7 == 0) {
- // 0xxx xxxx
- result += String.fromCharCode(c);
- continue;
- }
- // Invalid starting byte
- if (c >> 6 == 0x02) {
- continue;
- }
- // Multibyte; how many bytes left for thus character?
- var extraLength = null;
- if (c >> 5 == 0x06) {
- extraLength = 1;
- }
- else if (c >> 4 == 0x0e) {
- extraLength = 2;
- }
- else if (c >> 3 == 0x1e) {
- extraLength = 3;
- }
- else if (c >> 2 == 0x3e) {
- extraLength = 4;
- }
- else if (c >> 1 == 0x7e) {
- extraLength = 5;
- }
- else {
- continue;
- }
- // Do we have enough bytes in our data?
- if (i + extraLength > bytes.length) {
- // If there is an invalid unprocessed byte, try to continue
- for (; i < bytes.length; i++) {
- if (bytes[i] >> 6 != 0x02) {
- break;
- }
- }
- if (i != bytes.length)
- continue;
- // All leftover bytes are valid.
- return result;
- }
- // Remove the UTF-8 prefix from the char (res)
- var res = c & ((1 << (8 - extraLength - 1)) - 1);
- var count;
- for (count = 0; count < extraLength; count++) {
- var nextChar = bytes[i++];
- // Is the char valid multibyte part?
- if (nextChar >> 6 != 0x02) {
- break;
- }
- ;
- res = (res << 6) | (nextChar & 0x3f);
- }
- if (count != extraLength) {
- i--;
- continue;
- }
- if (res <= 0xffff) {
- result += String.fromCharCode(res);
- continue;
- }
- res -= 0x10000;
- result += String.fromCharCode(((res >> 10) & 0x3ff) + 0xd800, (res & 0x3ff) + 0xdc00);
- }
- return result;
-}
-exports.toUtf8String = toUtf8String;
-
-},{"./bytes":360}],367:[function(require,module,exports){
-'use strict';
-
-var BN = require('bn.js');
-var numberToBN = require('number-to-bn');
-
-var zero = new BN(0);
-var negative1 = new BN(-1);
-
-// complete ethereum unit map
-var unitMap = {
- 'noether': '0', // eslint-disable-line
- 'wei': '1', // eslint-disable-line
- 'kwei': '1000', // eslint-disable-line
- 'Kwei': '1000', // eslint-disable-line
- 'babbage': '1000', // eslint-disable-line
- 'femtoether': '1000', // eslint-disable-line
- 'mwei': '1000000', // eslint-disable-line
- 'Mwei': '1000000', // eslint-disable-line
- 'lovelace': '1000000', // eslint-disable-line
- 'picoether': '1000000', // eslint-disable-line
- 'gwei': '1000000000', // eslint-disable-line
- 'Gwei': '1000000000', // eslint-disable-line
- 'shannon': '1000000000', // eslint-disable-line
- 'nanoether': '1000000000', // eslint-disable-line
- 'nano': '1000000000', // eslint-disable-line
- 'szabo': '1000000000000', // eslint-disable-line
- 'microether': '1000000000000', // eslint-disable-line
- 'micro': '1000000000000', // eslint-disable-line
- 'finney': '1000000000000000', // eslint-disable-line
- 'milliether': '1000000000000000', // eslint-disable-line
- 'milli': '1000000000000000', // eslint-disable-line
- 'ether': '1000000000000000000', // eslint-disable-line
- 'kether': '1000000000000000000000', // eslint-disable-line
- 'grand': '1000000000000000000000', // eslint-disable-line
- 'mether': '1000000000000000000000000', // eslint-disable-line
- 'gether': '1000000000000000000000000000', // eslint-disable-line
- 'tether': '1000000000000000000000000000000' };
-
-/**
- * Returns value of unit in Wei
- *
- * @method getValueOfUnit
- * @param {String} unit the unit to convert to, default ether
- * @returns {BigNumber} value of the unit (in Wei)
- * @throws error if the unit is not correct:w
- */
-function getValueOfUnit(unitInput) {
- var unit = unitInput ? unitInput.toLowerCase() : 'ether';
- var unitValue = unitMap[unit]; // eslint-disable-line
-
- if (typeof unitValue !== 'string') {
- throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2));
- }
-
- return new BN(unitValue, 10);
-}
-
-function numberToString(arg) {
- if (typeof arg === 'string') {
- if (!arg.match(/^-?[0-9.]+$/)) {
- throw new Error('while converting number to string, invalid number value \'' + arg + '\', should be a number matching (^-?[0-9.]+).');
- }
- return arg;
- } else if (typeof arg === 'number') {
- return String(arg);
- } else if (typeof arg === 'object' && arg.toString && (arg.toTwos || arg.dividedToIntegerBy)) {
- if (arg.toPrecision) {
- return String(arg.toPrecision());
- } else {
- // eslint-disable-line
- return arg.toString(10);
- }
- }
- throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.');
-}
-
-function fromWei(weiInput, unit, optionsInput) {
- var wei = numberToBN(weiInput); // eslint-disable-line
- var negative = wei.lt(zero); // eslint-disable-line
- var base = getValueOfUnit(unit);
- var baseLength = unitMap[unit].length - 1 || 1;
- var options = optionsInput || {};
-
- if (negative) {
- wei = wei.mul(negative1);
- }
-
- var fraction = wei.mod(base).toString(10); // eslint-disable-line
-
- while (fraction.length < baseLength) {
- fraction = '0' + fraction;
- }
-
- if (!options.pad) {
- fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1];
- }
-
- var whole = wei.div(base).toString(10); // eslint-disable-line
-
- if (options.commify) {
- whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
- }
-
- var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line
-
- if (negative) {
- value = '-' + value;
- }
-
- return value;
-}
-
-function toWei(etherInput, unit) {
- var ether = numberToString(etherInput); // eslint-disable-line
- var base = getValueOfUnit(unit);
- var baseLength = unitMap[unit].length - 1 || 1;
-
- // Is it negative?
- var negative = ether.substring(0, 1) === '-'; // eslint-disable-line
- if (negative) {
- ether = ether.substring(1);
- }
-
- if (ether === '.') {
- throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value');
- }
-
- // Split it into a whole and fractional part
- var comps = ether.split('.'); // eslint-disable-line
- if (comps.length > 2) {
- throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points');
- }
-
- var whole = comps[0],
- fraction = comps[1]; // eslint-disable-line
-
- if (!whole) {
- whole = '0';
- }
- if (!fraction) {
- fraction = '0';
- }
- if (fraction.length > baseLength) {
- throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places');
- }
-
- while (fraction.length < baseLength) {
- fraction += '0';
- }
-
- whole = new BN(whole);
- fraction = new BN(fraction);
- var wei = whole.mul(base).add(fraction); // eslint-disable-line
-
- if (negative) {
- wei = wei.mul(negative1);
- }
-
- return new BN(wei.toString(10), 10);
-}
-
-module.exports = {
- unitMap: unitMap,
- numberToString: numberToString,
- getValueOfUnit: getValueOfUnit,
- fromWei: fromWei,
- toWei: toWei
-};
-},{"bn.js":368,"number-to-bn":1386}],368:[function(require,module,exports){
-(function (module, exports) {
- 'use strict';
-
- // Utils
- function assert (val, msg) {
- if (!val) throw new Error(msg || 'Assertion failed');
- }
-
- // Could use `inherits` module, but don't want to move from single file
- // architecture yet.
- function inherits (ctor, superCtor) {
- ctor.super_ = superCtor;
- var TempCtor = function () {};
- TempCtor.prototype = superCtor.prototype;
- ctor.prototype = new TempCtor();
- ctor.prototype.constructor = ctor;
- }
-
- // BN
-
- function BN (number, base, endian) {
- if (BN.isBN(number)) {
- return number;
- }
-
- this.negative = 0;
- this.words = null;
- this.length = 0;
-
- // Reduction context
- this.red = null;
-
- if (number !== null) {
- if (base === 'le' || base === 'be') {
- endian = base;
- base = 10;
- }
-
- this._init(number || 0, base || 10, endian || 'be');
- }
- }
- if (typeof module === 'object') {
- module.exports = BN;
- } else {
- exports.BN = BN;
- }
-
- BN.BN = BN;
- BN.wordSize = 26;
-
- var Buffer;
- try {
- Buffer = require('buf' + 'fer').Buffer;
- } catch (e) {
- }
-
- BN.isBN = function isBN (num) {
- if (num instanceof BN) {
- return true;
- }
-
- return num !== null && typeof num === 'object' &&
- num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
- };
-
- BN.max = function max (left, right) {
- if (left.cmp(right) > 0) return left;
- return right;
- };
-
- BN.min = function min (left, right) {
- if (left.cmp(right) < 0) return left;
- return right;
- };
-
- BN.prototype._init = function init (number, base, endian) {
- if (typeof number === 'number') {
- return this._initNumber(number, base, endian);
- }
-
- if (typeof number === 'object') {
- return this._initArray(number, base, endian);
- }
-
- if (base === 'hex') {
- base = 16;
- }
- assert(base === (base | 0) && base >= 2 && base <= 36);
-
- number = number.toString().replace(/\s+/g, '');
- var start = 0;
- if (number[0] === '-') {
- start++;
- }
-
- if (base === 16) {
- this._parseHex(number, start);
- } else {
- this._parseBase(number, base, start);
- }
-
- if (number[0] === '-') {
- this.negative = 1;
- }
-
- this.strip();
-
- if (endian !== 'le') return;
-
- this._initArray(this.toArray(), base, endian);
- };
-
- BN.prototype._initNumber = function _initNumber (number, base, endian) {
- if (number < 0) {
- this.negative = 1;
- number = -number;
- }
- if (number < 0x4000000) {
- this.words = [ number & 0x3ffffff ];
- this.length = 1;
- } else if (number < 0x10000000000000) {
- this.words = [
- number & 0x3ffffff,
- (number / 0x4000000) & 0x3ffffff
- ];
- this.length = 2;
- } else {
- assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
- this.words = [
- number & 0x3ffffff,
- (number / 0x4000000) & 0x3ffffff,
- 1
- ];
- this.length = 3;
- }
-
- if (endian !== 'le') return;
-
- // Reverse the bytes
- this._initArray(this.toArray(), base, endian);
- };
-
- BN.prototype._initArray = function _initArray (number, base, endian) {
- // Perhaps a Uint8Array
- assert(typeof number.length === 'number');
- if (number.length <= 0) {
- this.words = [ 0 ];
- this.length = 1;
- return this;
- }
-
- this.length = Math.ceil(number.length / 3);
- this.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- this.words[i] = 0;
- }
-
- var j, w;
- var off = 0;
- if (endian === 'be') {
- for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
- w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
- this.words[j] |= (w << off) & 0x3ffffff;
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
- off += 24;
- if (off >= 26) {
- off -= 26;
- j++;
- }
- }
- } else if (endian === 'le') {
- for (i = 0, j = 0; i < number.length; i += 3) {
- w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
- this.words[j] |= (w << off) & 0x3ffffff;
- this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
- off += 24;
- if (off >= 26) {
- off -= 26;
- j++;
- }
- }
- }
- return this.strip();
- };
-
- function parseHex (str, start, end) {
- var r = 0;
- var len = Math.min(str.length, end);
- for (var i = start; i < len; i++) {
- var c = str.charCodeAt(i) - 48;
-
- r <<= 4;
-
- // 'a' - 'f'
- if (c >= 49 && c <= 54) {
- r |= c - 49 + 0xa;
-
- // 'A' - 'F'
- } else if (c >= 17 && c <= 22) {
- r |= c - 17 + 0xa;
-
- // '0' - '9'
- } else {
- r |= c & 0xf;
- }
- }
- return r;
- }
-
- BN.prototype._parseHex = function _parseHex (number, start) {
- // Create possibly bigger array to ensure that it fits the number
- this.length = Math.ceil((number.length - start) / 6);
- this.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- this.words[i] = 0;
- }
-
- var j, w;
- // Scan 24-bit chunks and add them to the number
- var off = 0;
- for (i = number.length - 6, j = 0; i >= start; i -= 6) {
- w = parseHex(number, i, i + 6);
- this.words[j] |= (w << off) & 0x3ffffff;
- // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
- this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
- off += 24;
- if (off >= 26) {
- off -= 26;
- j++;
- }
- }
- if (i + 6 !== start) {
- w = parseHex(number, start, i + 6);
- this.words[j] |= (w << off) & 0x3ffffff;
- this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
- }
- this.strip();
- };
-
- function parseBase (str, start, end, mul) {
- var r = 0;
- var len = Math.min(str.length, end);
- for (var i = start; i < len; i++) {
- var c = str.charCodeAt(i) - 48;
-
- r *= mul;
-
- // 'a'
- if (c >= 49) {
- r += c - 49 + 0xa;
-
- // 'A'
- } else if (c >= 17) {
- r += c - 17 + 0xa;
-
- // '0' - '9'
- } else {
- r += c;
- }
- }
- return r;
- }
-
- BN.prototype._parseBase = function _parseBase (number, base, start) {
- // Initialize as zero
- this.words = [ 0 ];
- this.length = 1;
-
- // Find length of limb in base
- for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
- limbLen++;
- }
- limbLen--;
- limbPow = (limbPow / base) | 0;
-
- var total = number.length - start;
- var mod = total % limbLen;
- var end = Math.min(total, total - mod) + start;
-
- var word = 0;
- for (var i = start; i < end; i += limbLen) {
- word = parseBase(number, i, i + limbLen, base);
-
- this.imuln(limbPow);
- if (this.words[0] + word < 0x4000000) {
- this.words[0] += word;
- } else {
- this._iaddn(word);
- }
- }
-
- if (mod !== 0) {
- var pow = 1;
- word = parseBase(number, i, number.length, base);
-
- for (i = 0; i < mod; i++) {
- pow *= base;
- }
-
- this.imuln(pow);
- if (this.words[0] + word < 0x4000000) {
- this.words[0] += word;
- } else {
- this._iaddn(word);
- }
- }
- };
-
- BN.prototype.copy = function copy (dest) {
- dest.words = new Array(this.length);
- for (var i = 0; i < this.length; i++) {
- dest.words[i] = this.words[i];
- }
- dest.length = this.length;
- dest.negative = this.negative;
- dest.red = this.red;
- };
-
- BN.prototype.clone = function clone () {
- var r = new BN(null);
- this.copy(r);
- return r;
- };
-
- BN.prototype._expand = function _expand (size) {
- while (this.length < size) {
- this.words[this.length++] = 0;
- }
- return this;
- };
-
- // Remove leading `0` from `this`
- BN.prototype.strip = function strip () {
- while (this.length > 1 && this.words[this.length - 1] === 0) {
- this.length--;
- }
- return this._normSign();
- };
-
- BN.prototype._normSign = function _normSign () {
- // -0 = 0
- if (this.length === 1 && this.words[0] === 0) {
- this.negative = 0;
- }
- return this;
- };
-
- BN.prototype.inspect = function inspect () {
- return (this.red ? '';
- };
-
- /*
-
- var zeros = [];
- var groupSizes = [];
- var groupBases = [];
-
- var s = '';
- var i = -1;
- while (++i < BN.wordSize) {
- zeros[i] = s;
- s += '0';
- }
- groupSizes[0] = 0;
- groupSizes[1] = 0;
- groupBases[0] = 0;
- groupBases[1] = 0;
- var base = 2 - 1;
- while (++base < 36 + 1) {
- var groupSize = 0;
- var groupBase = 1;
- while (groupBase < (1 << BN.wordSize) / base) {
- groupBase *= base;
- groupSize += 1;
- }
- groupSizes[base] = groupSize;
- groupBases[base] = groupBase;
- }
-
- */
-
- var zeros = [
- '',
- '0',
- '00',
- '000',
- '0000',
- '00000',
- '000000',
- '0000000',
- '00000000',
- '000000000',
- '0000000000',
- '00000000000',
- '000000000000',
- '0000000000000',
- '00000000000000',
- '000000000000000',
- '0000000000000000',
- '00000000000000000',
- '000000000000000000',
- '0000000000000000000',
- '00000000000000000000',
- '000000000000000000000',
- '0000000000000000000000',
- '00000000000000000000000',
- '000000000000000000000000',
- '0000000000000000000000000'
- ];
-
- var groupSizes = [
- 0, 0,
- 25, 16, 12, 11, 10, 9, 8,
- 8, 7, 7, 7, 7, 6, 6,
- 6, 6, 6, 6, 6, 5, 5,
- 5, 5, 5, 5, 5, 5, 5,
- 5, 5, 5, 5, 5, 5, 5
- ];
-
- var groupBases = [
- 0, 0,
- 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
- 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
- 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
- 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
- 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
- ];
-
- BN.prototype.toString = function toString (base, padding) {
- base = base || 10;
- padding = padding | 0 || 1;
-
- var out;
- if (base === 16 || base === 'hex') {
- out = '';
- var off = 0;
- var carry = 0;
- for (var i = 0; i < this.length; i++) {
- var w = this.words[i];
- var word = (((w << off) | carry) & 0xffffff).toString(16);
- carry = (w >>> (24 - off)) & 0xffffff;
- if (carry !== 0 || i !== this.length - 1) {
- out = zeros[6 - word.length] + word + out;
- } else {
- out = word + out;
- }
- off += 2;
- if (off >= 26) {
- off -= 26;
- i--;
- }
- }
- if (carry !== 0) {
- out = carry.toString(16) + out;
- }
- while (out.length % padding !== 0) {
- out = '0' + out;
- }
- if (this.negative !== 0) {
- out = '-' + out;
- }
- return out;
- }
-
- if (base === (base | 0) && base >= 2 && base <= 36) {
- // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
- var groupSize = groupSizes[base];
- // var groupBase = Math.pow(base, groupSize);
- var groupBase = groupBases[base];
- out = '';
- var c = this.clone();
- c.negative = 0;
- while (!c.isZero()) {
- var r = c.modn(groupBase).toString(base);
- c = c.idivn(groupBase);
-
- if (!c.isZero()) {
- out = zeros[groupSize - r.length] + r + out;
- } else {
- out = r + out;
- }
- }
- if (this.isZero()) {
- out = '0' + out;
- }
- while (out.length % padding !== 0) {
- out = '0' + out;
- }
- if (this.negative !== 0) {
- out = '-' + out;
- }
- return out;
- }
-
- assert(false, 'Base should be between 2 and 36');
- };
-
- BN.prototype.toNumber = function toNumber () {
- var ret = this.words[0];
- if (this.length === 2) {
- ret += this.words[1] * 0x4000000;
- } else if (this.length === 3 && this.words[2] === 0x01) {
- // NOTE: at this stage it is known that the top bit is set
- ret += 0x10000000000000 + (this.words[1] * 0x4000000);
- } else if (this.length > 2) {
- assert(false, 'Number can only safely store up to 53 bits');
- }
- return (this.negative !== 0) ? -ret : ret;
- };
-
- BN.prototype.toJSON = function toJSON () {
- return this.toString(16);
- };
-
- BN.prototype.toBuffer = function toBuffer (endian, length) {
- assert(typeof Buffer !== 'undefined');
- return this.toArrayLike(Buffer, endian, length);
- };
-
- BN.prototype.toArray = function toArray (endian, length) {
- return this.toArrayLike(Array, endian, length);
- };
-
- BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
- var byteLength = this.byteLength();
- var reqLength = length || Math.max(1, byteLength);
- assert(byteLength <= reqLength, 'byte array longer than desired length');
- assert(reqLength > 0, 'Requested array length <= 0');
-
- this.strip();
- var littleEndian = endian === 'le';
- var res = new ArrayType(reqLength);
-
- var b, i;
- var q = this.clone();
- if (!littleEndian) {
- // Assume big-endian
- for (i = 0; i < reqLength - byteLength; i++) {
- res[i] = 0;
- }
-
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
-
- res[reqLength - i - 1] = b;
- }
- } else {
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
-
- res[i] = b;
- }
-
- for (; i < reqLength; i++) {
- res[i] = 0;
- }
- }
-
- return res;
- };
-
- if (Math.clz32) {
- BN.prototype._countBits = function _countBits (w) {
- return 32 - Math.clz32(w);
- };
- } else {
- BN.prototype._countBits = function _countBits (w) {
- var t = w;
- var r = 0;
- if (t >= 0x1000) {
- r += 13;
- t >>>= 13;
- }
- if (t >= 0x40) {
- r += 7;
- t >>>= 7;
- }
- if (t >= 0x8) {
- r += 4;
- t >>>= 4;
- }
- if (t >= 0x02) {
- r += 2;
- t >>>= 2;
- }
- return r + t;
- };
- }
-
- BN.prototype._zeroBits = function _zeroBits (w) {
- // Short-cut
- if (w === 0) return 26;
-
- var t = w;
- var r = 0;
- if ((t & 0x1fff) === 0) {
- r += 13;
- t >>>= 13;
- }
- if ((t & 0x7f) === 0) {
- r += 7;
- t >>>= 7;
- }
- if ((t & 0xf) === 0) {
- r += 4;
- t >>>= 4;
- }
- if ((t & 0x3) === 0) {
- r += 2;
- t >>>= 2;
- }
- if ((t & 0x1) === 0) {
- r++;
- }
- return r;
- };
-
- // Return number of used bits in a BN
- BN.prototype.bitLength = function bitLength () {
- var w = this.words[this.length - 1];
- var hi = this._countBits(w);
- return (this.length - 1) * 26 + hi;
- };
-
- function toBitArray (num) {
- var w = new Array(num.bitLength());
-
- for (var bit = 0; bit < w.length; bit++) {
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
-
- w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
- }
-
- return w;
- }
-
- // Number of trailing zero bits
- BN.prototype.zeroBits = function zeroBits () {
- if (this.isZero()) return 0;
-
- var r = 0;
- for (var i = 0; i < this.length; i++) {
- var b = this._zeroBits(this.words[i]);
- r += b;
- if (b !== 26) break;
- }
- return r;
- };
-
- BN.prototype.byteLength = function byteLength () {
- return Math.ceil(this.bitLength() / 8);
- };
-
- BN.prototype.toTwos = function toTwos (width) {
- if (this.negative !== 0) {
- return this.abs().inotn(width).iaddn(1);
- }
- return this.clone();
- };
-
- BN.prototype.fromTwos = function fromTwos (width) {
- if (this.testn(width - 1)) {
- return this.notn(width).iaddn(1).ineg();
- }
- return this.clone();
- };
-
- BN.prototype.isNeg = function isNeg () {
- return this.negative !== 0;
- };
-
- // Return negative clone of `this`
- BN.prototype.neg = function neg () {
- return this.clone().ineg();
- };
-
- BN.prototype.ineg = function ineg () {
- if (!this.isZero()) {
- this.negative ^= 1;
- }
-
- return this;
- };
-
- // Or `num` with `this` in-place
- BN.prototype.iuor = function iuor (num) {
- while (this.length < num.length) {
- this.words[this.length++] = 0;
- }
-
- for (var i = 0; i < num.length; i++) {
- this.words[i] = this.words[i] | num.words[i];
- }
-
- return this.strip();
- };
-
- BN.prototype.ior = function ior (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuor(num);
- };
-
- // Or `num` with `this`
- BN.prototype.or = function or (num) {
- if (this.length > num.length) return this.clone().ior(num);
- return num.clone().ior(this);
- };
-
- BN.prototype.uor = function uor (num) {
- if (this.length > num.length) return this.clone().iuor(num);
- return num.clone().iuor(this);
- };
-
- // And `num` with `this` in-place
- BN.prototype.iuand = function iuand (num) {
- // b = min-length(num, this)
- var b;
- if (this.length > num.length) {
- b = num;
- } else {
- b = this;
- }
-
- for (var i = 0; i < b.length; i++) {
- this.words[i] = this.words[i] & num.words[i];
- }
-
- this.length = b.length;
-
- return this.strip();
- };
-
- BN.prototype.iand = function iand (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuand(num);
- };
-
- // And `num` with `this`
- BN.prototype.and = function and (num) {
- if (this.length > num.length) return this.clone().iand(num);
- return num.clone().iand(this);
- };
-
- BN.prototype.uand = function uand (num) {
- if (this.length > num.length) return this.clone().iuand(num);
- return num.clone().iuand(this);
- };
-
- // Xor `num` with `this` in-place
- BN.prototype.iuxor = function iuxor (num) {
- // a.length > b.length
- var a;
- var b;
- if (this.length > num.length) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
-
- for (var i = 0; i < b.length; i++) {
- this.words[i] = a.words[i] ^ b.words[i];
- }
-
- if (this !== a) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
-
- this.length = a.length;
-
- return this.strip();
- };
-
- BN.prototype.ixor = function ixor (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuxor(num);
- };
-
- // Xor `num` with `this`
- BN.prototype.xor = function xor (num) {
- if (this.length > num.length) return this.clone().ixor(num);
- return num.clone().ixor(this);
- };
-
- BN.prototype.uxor = function uxor (num) {
- if (this.length > num.length) return this.clone().iuxor(num);
- return num.clone().iuxor(this);
- };
-
- // Not ``this`` with ``width`` bitwidth
- BN.prototype.inotn = function inotn (width) {
- assert(typeof width === 'number' && width >= 0);
-
- var bytesNeeded = Math.ceil(width / 26) | 0;
- var bitsLeft = width % 26;
-
- // Extend the buffer with leading zeroes
- this._expand(bytesNeeded);
-
- if (bitsLeft > 0) {
- bytesNeeded--;
- }
-
- // Handle complete words
- for (var i = 0; i < bytesNeeded; i++) {
- this.words[i] = ~this.words[i] & 0x3ffffff;
- }
-
- // Handle the residue
- if (bitsLeft > 0) {
- this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
- }
-
- // And remove leading zeroes
- return this.strip();
- };
-
- BN.prototype.notn = function notn (width) {
- return this.clone().inotn(width);
- };
-
- // Set `bit` of `this`
- BN.prototype.setn = function setn (bit, val) {
- assert(typeof bit === 'number' && bit >= 0);
-
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
-
- this._expand(off + 1);
-
- if (val) {
- this.words[off] = this.words[off] | (1 << wbit);
- } else {
- this.words[off] = this.words[off] & ~(1 << wbit);
- }
-
- return this.strip();
- };
-
- // Add `num` to `this` in-place
- BN.prototype.iadd = function iadd (num) {
- var r;
-
- // negative + positive
- if (this.negative !== 0 && num.negative === 0) {
- this.negative = 0;
- r = this.isub(num);
- this.negative ^= 1;
- return this._normSign();
-
- // positive + negative
- } else if (this.negative === 0 && num.negative !== 0) {
- num.negative = 0;
- r = this.isub(num);
- num.negative = 1;
- return r._normSign();
- }
-
- // a.length > b.length
- var a, b;
- if (this.length > num.length) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
-
- var carry = 0;
- for (var i = 0; i < b.length; i++) {
- r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
- this.words[i] = r & 0x3ffffff;
- carry = r >>> 26;
- }
- for (; carry !== 0 && i < a.length; i++) {
- r = (a.words[i] | 0) + carry;
- this.words[i] = r & 0x3ffffff;
- carry = r >>> 26;
- }
-
- this.length = a.length;
- if (carry !== 0) {
- this.words[this.length] = carry;
- this.length++;
- // Copy the rest of the words
- } else if (a !== this) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
-
- return this;
- };
-
- // Add `num` to `this`
- BN.prototype.add = function add (num) {
- var res;
- if (num.negative !== 0 && this.negative === 0) {
- num.negative = 0;
- res = this.sub(num);
- num.negative ^= 1;
- return res;
- } else if (num.negative === 0 && this.negative !== 0) {
- this.negative = 0;
- res = num.sub(this);
- this.negative = 1;
- return res;
- }
-
- if (this.length > num.length) return this.clone().iadd(num);
-
- return num.clone().iadd(this);
- };
-
- // Subtract `num` from `this` in-place
- BN.prototype.isub = function isub (num) {
- // this - (-num) = this + num
- if (num.negative !== 0) {
- num.negative = 0;
- var r = this.iadd(num);
- num.negative = 1;
- return r._normSign();
-
- // -this - num = -(this + num)
- } else if (this.negative !== 0) {
- this.negative = 0;
- this.iadd(num);
- this.negative = 1;
- return this._normSign();
- }
-
- // At this point both numbers are positive
- var cmp = this.cmp(num);
-
- // Optimization - zeroify
- if (cmp === 0) {
- this.negative = 0;
- this.length = 1;
- this.words[0] = 0;
- return this;
- }
-
- // a > b
- var a, b;
- if (cmp > 0) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
-
- var carry = 0;
- for (var i = 0; i < b.length; i++) {
- r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
- carry = r >> 26;
- this.words[i] = r & 0x3ffffff;
- }
- for (; carry !== 0 && i < a.length; i++) {
- r = (a.words[i] | 0) + carry;
- carry = r >> 26;
- this.words[i] = r & 0x3ffffff;
- }
-
- // Copy rest of the words
- if (carry === 0 && i < a.length && a !== this) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
- }
- }
-
- this.length = Math.max(this.length, i);
-
- if (a !== this) {
- this.negative = 1;
- }
-
- return this.strip();
- };
-
- // Subtract `num` from `this`
- BN.prototype.sub = function sub (num) {
- return this.clone().isub(num);
- };
-
- function smallMulTo (self, num, out) {
- out.negative = num.negative ^ self.negative;
- var len = (self.length + num.length) | 0;
- out.length = len;
- len = (len - 1) | 0;
-
- // Peel one iteration (compiler can't do it, because of code complexity)
- var a = self.words[0] | 0;
- var b = num.words[0] | 0;
- var r = a * b;
-
- var lo = r & 0x3ffffff;
- var carry = (r / 0x4000000) | 0;
- out.words[0] = lo;
-
- for (var k = 1; k < len; k++) {
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
- // note that ncarry could be >= 0x3ffffff
- var ncarry = carry >>> 26;
- var rword = carry & 0x3ffffff;
- var maxJ = Math.min(k, num.length - 1);
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
- var i = (k - j) | 0;
- a = self.words[i] | 0;
- b = num.words[j] | 0;
- r = a * b + rword;
- ncarry += (r / 0x4000000) | 0;
- rword = r & 0x3ffffff;
- }
- out.words[k] = rword | 0;
- carry = ncarry | 0;
- }
- if (carry !== 0) {
- out.words[k] = carry | 0;
- } else {
- out.length--;
- }
-
- return out.strip();
- }
-
- // TODO(indutny): it may be reasonable to omit it for users who don't need
- // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
- // multiplication (like elliptic secp256k1).
- var comb10MulTo = function comb10MulTo (self, num, out) {
- var a = self.words;
- var b = num.words;
- var o = out.words;
- var c = 0;
- var lo;
- var mid;
- var hi;
- var a0 = a[0] | 0;
- var al0 = a0 & 0x1fff;
- var ah0 = a0 >>> 13;
- var a1 = a[1] | 0;
- var al1 = a1 & 0x1fff;
- var ah1 = a1 >>> 13;
- var a2 = a[2] | 0;
- var al2 = a2 & 0x1fff;
- var ah2 = a2 >>> 13;
- var a3 = a[3] | 0;
- var al3 = a3 & 0x1fff;
- var ah3 = a3 >>> 13;
- var a4 = a[4] | 0;
- var al4 = a4 & 0x1fff;
- var ah4 = a4 >>> 13;
- var a5 = a[5] | 0;
- var al5 = a5 & 0x1fff;
- var ah5 = a5 >>> 13;
- var a6 = a[6] | 0;
- var al6 = a6 & 0x1fff;
- var ah6 = a6 >>> 13;
- var a7 = a[7] | 0;
- var al7 = a7 & 0x1fff;
- var ah7 = a7 >>> 13;
- var a8 = a[8] | 0;
- var al8 = a8 & 0x1fff;
- var ah8 = a8 >>> 13;
- var a9 = a[9] | 0;
- var al9 = a9 & 0x1fff;
- var ah9 = a9 >>> 13;
- var b0 = b[0] | 0;
- var bl0 = b0 & 0x1fff;
- var bh0 = b0 >>> 13;
- var b1 = b[1] | 0;
- var bl1 = b1 & 0x1fff;
- var bh1 = b1 >>> 13;
- var b2 = b[2] | 0;
- var bl2 = b2 & 0x1fff;
- var bh2 = b2 >>> 13;
- var b3 = b[3] | 0;
- var bl3 = b3 & 0x1fff;
- var bh3 = b3 >>> 13;
- var b4 = b[4] | 0;
- var bl4 = b4 & 0x1fff;
- var bh4 = b4 >>> 13;
- var b5 = b[5] | 0;
- var bl5 = b5 & 0x1fff;
- var bh5 = b5 >>> 13;
- var b6 = b[6] | 0;
- var bl6 = b6 & 0x1fff;
- var bh6 = b6 >>> 13;
- var b7 = b[7] | 0;
- var bl7 = b7 & 0x1fff;
- var bh7 = b7 >>> 13;
- var b8 = b[8] | 0;
- var bl8 = b8 & 0x1fff;
- var bh8 = b8 >>> 13;
- var b9 = b[9] | 0;
- var bl9 = b9 & 0x1fff;
- var bh9 = b9 >>> 13;
-
- out.negative = self.negative ^ num.negative;
- out.length = 19;
- /* k = 0 */
- lo = Math.imul(al0, bl0);
- mid = Math.imul(al0, bh0);
- mid = (mid + Math.imul(ah0, bl0)) | 0;
- hi = Math.imul(ah0, bh0);
- var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
- w0 &= 0x3ffffff;
- /* k = 1 */
- lo = Math.imul(al1, bl0);
- mid = Math.imul(al1, bh0);
- mid = (mid + Math.imul(ah1, bl0)) | 0;
- hi = Math.imul(ah1, bh0);
- lo = (lo + Math.imul(al0, bl1)) | 0;
- mid = (mid + Math.imul(al0, bh1)) | 0;
- mid = (mid + Math.imul(ah0, bl1)) | 0;
- hi = (hi + Math.imul(ah0, bh1)) | 0;
- var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
- w1 &= 0x3ffffff;
- /* k = 2 */
- lo = Math.imul(al2, bl0);
- mid = Math.imul(al2, bh0);
- mid = (mid + Math.imul(ah2, bl0)) | 0;
- hi = Math.imul(ah2, bh0);
- lo = (lo + Math.imul(al1, bl1)) | 0;
- mid = (mid + Math.imul(al1, bh1)) | 0;
- mid = (mid + Math.imul(ah1, bl1)) | 0;
- hi = (hi + Math.imul(ah1, bh1)) | 0;
- lo = (lo + Math.imul(al0, bl2)) | 0;
- mid = (mid + Math.imul(al0, bh2)) | 0;
- mid = (mid + Math.imul(ah0, bl2)) | 0;
- hi = (hi + Math.imul(ah0, bh2)) | 0;
- var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
- w2 &= 0x3ffffff;
- /* k = 3 */
- lo = Math.imul(al3, bl0);
- mid = Math.imul(al3, bh0);
- mid = (mid + Math.imul(ah3, bl0)) | 0;
- hi = Math.imul(ah3, bh0);
- lo = (lo + Math.imul(al2, bl1)) | 0;
- mid = (mid + Math.imul(al2, bh1)) | 0;
- mid = (mid + Math.imul(ah2, bl1)) | 0;
- hi = (hi + Math.imul(ah2, bh1)) | 0;
- lo = (lo + Math.imul(al1, bl2)) | 0;
- mid = (mid + Math.imul(al1, bh2)) | 0;
- mid = (mid + Math.imul(ah1, bl2)) | 0;
- hi = (hi + Math.imul(ah1, bh2)) | 0;
- lo = (lo + Math.imul(al0, bl3)) | 0;
- mid = (mid + Math.imul(al0, bh3)) | 0;
- mid = (mid + Math.imul(ah0, bl3)) | 0;
- hi = (hi + Math.imul(ah0, bh3)) | 0;
- var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
- w3 &= 0x3ffffff;
- /* k = 4 */
- lo = Math.imul(al4, bl0);
- mid = Math.imul(al4, bh0);
- mid = (mid + Math.imul(ah4, bl0)) | 0;
- hi = Math.imul(ah4, bh0);
- lo = (lo + Math.imul(al3, bl1)) | 0;
- mid = (mid + Math.imul(al3, bh1)) | 0;
- mid = (mid + Math.imul(ah3, bl1)) | 0;
- hi = (hi + Math.imul(ah3, bh1)) | 0;
- lo = (lo + Math.imul(al2, bl2)) | 0;
- mid = (mid + Math.imul(al2, bh2)) | 0;
- mid = (mid + Math.imul(ah2, bl2)) | 0;
- hi = (hi + Math.imul(ah2, bh2)) | 0;
- lo = (lo + Math.imul(al1, bl3)) | 0;
- mid = (mid + Math.imul(al1, bh3)) | 0;
- mid = (mid + Math.imul(ah1, bl3)) | 0;
- hi = (hi + Math.imul(ah1, bh3)) | 0;
- lo = (lo + Math.imul(al0, bl4)) | 0;
- mid = (mid + Math.imul(al0, bh4)) | 0;
- mid = (mid + Math.imul(ah0, bl4)) | 0;
- hi = (hi + Math.imul(ah0, bh4)) | 0;
- var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
- w4 &= 0x3ffffff;
- /* k = 5 */
- lo = Math.imul(al5, bl0);
- mid = Math.imul(al5, bh0);
- mid = (mid + Math.imul(ah5, bl0)) | 0;
- hi = Math.imul(ah5, bh0);
- lo = (lo + Math.imul(al4, bl1)) | 0;
- mid = (mid + Math.imul(al4, bh1)) | 0;
- mid = (mid + Math.imul(ah4, bl1)) | 0;
- hi = (hi + Math.imul(ah4, bh1)) | 0;
- lo = (lo + Math.imul(al3, bl2)) | 0;
- mid = (mid + Math.imul(al3, bh2)) | 0;
- mid = (mid + Math.imul(ah3, bl2)) | 0;
- hi = (hi + Math.imul(ah3, bh2)) | 0;
- lo = (lo + Math.imul(al2, bl3)) | 0;
- mid = (mid + Math.imul(al2, bh3)) | 0;
- mid = (mid + Math.imul(ah2, bl3)) | 0;
- hi = (hi + Math.imul(ah2, bh3)) | 0;
- lo = (lo + Math.imul(al1, bl4)) | 0;
- mid = (mid + Math.imul(al1, bh4)) | 0;
- mid = (mid + Math.imul(ah1, bl4)) | 0;
- hi = (hi + Math.imul(ah1, bh4)) | 0;
- lo = (lo + Math.imul(al0, bl5)) | 0;
- mid = (mid + Math.imul(al0, bh5)) | 0;
- mid = (mid + Math.imul(ah0, bl5)) | 0;
- hi = (hi + Math.imul(ah0, bh5)) | 0;
- var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
- w5 &= 0x3ffffff;
- /* k = 6 */
- lo = Math.imul(al6, bl0);
- mid = Math.imul(al6, bh0);
- mid = (mid + Math.imul(ah6, bl0)) | 0;
- hi = Math.imul(ah6, bh0);
- lo = (lo + Math.imul(al5, bl1)) | 0;
- mid = (mid + Math.imul(al5, bh1)) | 0;
- mid = (mid + Math.imul(ah5, bl1)) | 0;
- hi = (hi + Math.imul(ah5, bh1)) | 0;
- lo = (lo + Math.imul(al4, bl2)) | 0;
- mid = (mid + Math.imul(al4, bh2)) | 0;
- mid = (mid + Math.imul(ah4, bl2)) | 0;
- hi = (hi + Math.imul(ah4, bh2)) | 0;
- lo = (lo + Math.imul(al3, bl3)) | 0;
- mid = (mid + Math.imul(al3, bh3)) | 0;
- mid = (mid + Math.imul(ah3, bl3)) | 0;
- hi = (hi + Math.imul(ah3, bh3)) | 0;
- lo = (lo + Math.imul(al2, bl4)) | 0;
- mid = (mid + Math.imul(al2, bh4)) | 0;
- mid = (mid + Math.imul(ah2, bl4)) | 0;
- hi = (hi + Math.imul(ah2, bh4)) | 0;
- lo = (lo + Math.imul(al1, bl5)) | 0;
- mid = (mid + Math.imul(al1, bh5)) | 0;
- mid = (mid + Math.imul(ah1, bl5)) | 0;
- hi = (hi + Math.imul(ah1, bh5)) | 0;
- lo = (lo + Math.imul(al0, bl6)) | 0;
- mid = (mid + Math.imul(al0, bh6)) | 0;
- mid = (mid + Math.imul(ah0, bl6)) | 0;
- hi = (hi + Math.imul(ah0, bh6)) | 0;
- var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
- w6 &= 0x3ffffff;
- /* k = 7 */
- lo = Math.imul(al7, bl0);
- mid = Math.imul(al7, bh0);
- mid = (mid + Math.imul(ah7, bl0)) | 0;
- hi = Math.imul(ah7, bh0);
- lo = (lo + Math.imul(al6, bl1)) | 0;
- mid = (mid + Math.imul(al6, bh1)) | 0;
- mid = (mid + Math.imul(ah6, bl1)) | 0;
- hi = (hi + Math.imul(ah6, bh1)) | 0;
- lo = (lo + Math.imul(al5, bl2)) | 0;
- mid = (mid + Math.imul(al5, bh2)) | 0;
- mid = (mid + Math.imul(ah5, bl2)) | 0;
- hi = (hi + Math.imul(ah5, bh2)) | 0;
- lo = (lo + Math.imul(al4, bl3)) | 0;
- mid = (mid + Math.imul(al4, bh3)) | 0;
- mid = (mid + Math.imul(ah4, bl3)) | 0;
- hi = (hi + Math.imul(ah4, bh3)) | 0;
- lo = (lo + Math.imul(al3, bl4)) | 0;
- mid = (mid + Math.imul(al3, bh4)) | 0;
- mid = (mid + Math.imul(ah3, bl4)) | 0;
- hi = (hi + Math.imul(ah3, bh4)) | 0;
- lo = (lo + Math.imul(al2, bl5)) | 0;
- mid = (mid + Math.imul(al2, bh5)) | 0;
- mid = (mid + Math.imul(ah2, bl5)) | 0;
- hi = (hi + Math.imul(ah2, bh5)) | 0;
- lo = (lo + Math.imul(al1, bl6)) | 0;
- mid = (mid + Math.imul(al1, bh6)) | 0;
- mid = (mid + Math.imul(ah1, bl6)) | 0;
- hi = (hi + Math.imul(ah1, bh6)) | 0;
- lo = (lo + Math.imul(al0, bl7)) | 0;
- mid = (mid + Math.imul(al0, bh7)) | 0;
- mid = (mid + Math.imul(ah0, bl7)) | 0;
- hi = (hi + Math.imul(ah0, bh7)) | 0;
- var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
- w7 &= 0x3ffffff;
- /* k = 8 */
- lo = Math.imul(al8, bl0);
- mid = Math.imul(al8, bh0);
- mid = (mid + Math.imul(ah8, bl0)) | 0;
- hi = Math.imul(ah8, bh0);
- lo = (lo + Math.imul(al7, bl1)) | 0;
- mid = (mid + Math.imul(al7, bh1)) | 0;
- mid = (mid + Math.imul(ah7, bl1)) | 0;
- hi = (hi + Math.imul(ah7, bh1)) | 0;
- lo = (lo + Math.imul(al6, bl2)) | 0;
- mid = (mid + Math.imul(al6, bh2)) | 0;
- mid = (mid + Math.imul(ah6, bl2)) | 0;
- hi = (hi + Math.imul(ah6, bh2)) | 0;
- lo = (lo + Math.imul(al5, bl3)) | 0;
- mid = (mid + Math.imul(al5, bh3)) | 0;
- mid = (mid + Math.imul(ah5, bl3)) | 0;
- hi = (hi + Math.imul(ah5, bh3)) | 0;
- lo = (lo + Math.imul(al4, bl4)) | 0;
- mid = (mid + Math.imul(al4, bh4)) | 0;
- mid = (mid + Math.imul(ah4, bl4)) | 0;
- hi = (hi + Math.imul(ah4, bh4)) | 0;
- lo = (lo + Math.imul(al3, bl5)) | 0;
- mid = (mid + Math.imul(al3, bh5)) | 0;
- mid = (mid + Math.imul(ah3, bl5)) | 0;
- hi = (hi + Math.imul(ah3, bh5)) | 0;
- lo = (lo + Math.imul(al2, bl6)) | 0;
- mid = (mid + Math.imul(al2, bh6)) | 0;
- mid = (mid + Math.imul(ah2, bl6)) | 0;
- hi = (hi + Math.imul(ah2, bh6)) | 0;
- lo = (lo + Math.imul(al1, bl7)) | 0;
- mid = (mid + Math.imul(al1, bh7)) | 0;
- mid = (mid + Math.imul(ah1, bl7)) | 0;
- hi = (hi + Math.imul(ah1, bh7)) | 0;
- lo = (lo + Math.imul(al0, bl8)) | 0;
- mid = (mid + Math.imul(al0, bh8)) | 0;
- mid = (mid + Math.imul(ah0, bl8)) | 0;
- hi = (hi + Math.imul(ah0, bh8)) | 0;
- var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
- w8 &= 0x3ffffff;
- /* k = 9 */
- lo = Math.imul(al9, bl0);
- mid = Math.imul(al9, bh0);
- mid = (mid + Math.imul(ah9, bl0)) | 0;
- hi = Math.imul(ah9, bh0);
- lo = (lo + Math.imul(al8, bl1)) | 0;
- mid = (mid + Math.imul(al8, bh1)) | 0;
- mid = (mid + Math.imul(ah8, bl1)) | 0;
- hi = (hi + Math.imul(ah8, bh1)) | 0;
- lo = (lo + Math.imul(al7, bl2)) | 0;
- mid = (mid + Math.imul(al7, bh2)) | 0;
- mid = (mid + Math.imul(ah7, bl2)) | 0;
- hi = (hi + Math.imul(ah7, bh2)) | 0;
- lo = (lo + Math.imul(al6, bl3)) | 0;
- mid = (mid + Math.imul(al6, bh3)) | 0;
- mid = (mid + Math.imul(ah6, bl3)) | 0;
- hi = (hi + Math.imul(ah6, bh3)) | 0;
- lo = (lo + Math.imul(al5, bl4)) | 0;
- mid = (mid + Math.imul(al5, bh4)) | 0;
- mid = (mid + Math.imul(ah5, bl4)) | 0;
- hi = (hi + Math.imul(ah5, bh4)) | 0;
- lo = (lo + Math.imul(al4, bl5)) | 0;
- mid = (mid + Math.imul(al4, bh5)) | 0;
- mid = (mid + Math.imul(ah4, bl5)) | 0;
- hi = (hi + Math.imul(ah4, bh5)) | 0;
- lo = (lo + Math.imul(al3, bl6)) | 0;
- mid = (mid + Math.imul(al3, bh6)) | 0;
- mid = (mid + Math.imul(ah3, bl6)) | 0;
- hi = (hi + Math.imul(ah3, bh6)) | 0;
- lo = (lo + Math.imul(al2, bl7)) | 0;
- mid = (mid + Math.imul(al2, bh7)) | 0;
- mid = (mid + Math.imul(ah2, bl7)) | 0;
- hi = (hi + Math.imul(ah2, bh7)) | 0;
- lo = (lo + Math.imul(al1, bl8)) | 0;
- mid = (mid + Math.imul(al1, bh8)) | 0;
- mid = (mid + Math.imul(ah1, bl8)) | 0;
- hi = (hi + Math.imul(ah1, bh8)) | 0;
- lo = (lo + Math.imul(al0, bl9)) | 0;
- mid = (mid + Math.imul(al0, bh9)) | 0;
- mid = (mid + Math.imul(ah0, bl9)) | 0;
- hi = (hi + Math.imul(ah0, bh9)) | 0;
- var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
- w9 &= 0x3ffffff;
- /* k = 10 */
- lo = Math.imul(al9, bl1);
- mid = Math.imul(al9, bh1);
- mid = (mid + Math.imul(ah9, bl1)) | 0;
- hi = Math.imul(ah9, bh1);
- lo = (lo + Math.imul(al8, bl2)) | 0;
- mid = (mid + Math.imul(al8, bh2)) | 0;
- mid = (mid + Math.imul(ah8, bl2)) | 0;
- hi = (hi + Math.imul(ah8, bh2)) | 0;
- lo = (lo + Math.imul(al7, bl3)) | 0;
- mid = (mid + Math.imul(al7, bh3)) | 0;
- mid = (mid + Math.imul(ah7, bl3)) | 0;
- hi = (hi + Math.imul(ah7, bh3)) | 0;
- lo = (lo + Math.imul(al6, bl4)) | 0;
- mid = (mid + Math.imul(al6, bh4)) | 0;
- mid = (mid + Math.imul(ah6, bl4)) | 0;
- hi = (hi + Math.imul(ah6, bh4)) | 0;
- lo = (lo + Math.imul(al5, bl5)) | 0;
- mid = (mid + Math.imul(al5, bh5)) | 0;
- mid = (mid + Math.imul(ah5, bl5)) | 0;
- hi = (hi + Math.imul(ah5, bh5)) | 0;
- lo = (lo + Math.imul(al4, bl6)) | 0;
- mid = (mid + Math.imul(al4, bh6)) | 0;
- mid = (mid + Math.imul(ah4, bl6)) | 0;
- hi = (hi + Math.imul(ah4, bh6)) | 0;
- lo = (lo + Math.imul(al3, bl7)) | 0;
- mid = (mid + Math.imul(al3, bh7)) | 0;
- mid = (mid + Math.imul(ah3, bl7)) | 0;
- hi = (hi + Math.imul(ah3, bh7)) | 0;
- lo = (lo + Math.imul(al2, bl8)) | 0;
- mid = (mid + Math.imul(al2, bh8)) | 0;
- mid = (mid + Math.imul(ah2, bl8)) | 0;
- hi = (hi + Math.imul(ah2, bh8)) | 0;
- lo = (lo + Math.imul(al1, bl9)) | 0;
- mid = (mid + Math.imul(al1, bh9)) | 0;
- mid = (mid + Math.imul(ah1, bl9)) | 0;
- hi = (hi + Math.imul(ah1, bh9)) | 0;
- var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
- w10 &= 0x3ffffff;
- /* k = 11 */
- lo = Math.imul(al9, bl2);
- mid = Math.imul(al9, bh2);
- mid = (mid + Math.imul(ah9, bl2)) | 0;
- hi = Math.imul(ah9, bh2);
- lo = (lo + Math.imul(al8, bl3)) | 0;
- mid = (mid + Math.imul(al8, bh3)) | 0;
- mid = (mid + Math.imul(ah8, bl3)) | 0;
- hi = (hi + Math.imul(ah8, bh3)) | 0;
- lo = (lo + Math.imul(al7, bl4)) | 0;
- mid = (mid + Math.imul(al7, bh4)) | 0;
- mid = (mid + Math.imul(ah7, bl4)) | 0;
- hi = (hi + Math.imul(ah7, bh4)) | 0;
- lo = (lo + Math.imul(al6, bl5)) | 0;
- mid = (mid + Math.imul(al6, bh5)) | 0;
- mid = (mid + Math.imul(ah6, bl5)) | 0;
- hi = (hi + Math.imul(ah6, bh5)) | 0;
- lo = (lo + Math.imul(al5, bl6)) | 0;
- mid = (mid + Math.imul(al5, bh6)) | 0;
- mid = (mid + Math.imul(ah5, bl6)) | 0;
- hi = (hi + Math.imul(ah5, bh6)) | 0;
- lo = (lo + Math.imul(al4, bl7)) | 0;
- mid = (mid + Math.imul(al4, bh7)) | 0;
- mid = (mid + Math.imul(ah4, bl7)) | 0;
- hi = (hi + Math.imul(ah4, bh7)) | 0;
- lo = (lo + Math.imul(al3, bl8)) | 0;
- mid = (mid + Math.imul(al3, bh8)) | 0;
- mid = (mid + Math.imul(ah3, bl8)) | 0;
- hi = (hi + Math.imul(ah3, bh8)) | 0;
- lo = (lo + Math.imul(al2, bl9)) | 0;
- mid = (mid + Math.imul(al2, bh9)) | 0;
- mid = (mid + Math.imul(ah2, bl9)) | 0;
- hi = (hi + Math.imul(ah2, bh9)) | 0;
- var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
- w11 &= 0x3ffffff;
- /* k = 12 */
- lo = Math.imul(al9, bl3);
- mid = Math.imul(al9, bh3);
- mid = (mid + Math.imul(ah9, bl3)) | 0;
- hi = Math.imul(ah9, bh3);
- lo = (lo + Math.imul(al8, bl4)) | 0;
- mid = (mid + Math.imul(al8, bh4)) | 0;
- mid = (mid + Math.imul(ah8, bl4)) | 0;
- hi = (hi + Math.imul(ah8, bh4)) | 0;
- lo = (lo + Math.imul(al7, bl5)) | 0;
- mid = (mid + Math.imul(al7, bh5)) | 0;
- mid = (mid + Math.imul(ah7, bl5)) | 0;
- hi = (hi + Math.imul(ah7, bh5)) | 0;
- lo = (lo + Math.imul(al6, bl6)) | 0;
- mid = (mid + Math.imul(al6, bh6)) | 0;
- mid = (mid + Math.imul(ah6, bl6)) | 0;
- hi = (hi + Math.imul(ah6, bh6)) | 0;
- lo = (lo + Math.imul(al5, bl7)) | 0;
- mid = (mid + Math.imul(al5, bh7)) | 0;
- mid = (mid + Math.imul(ah5, bl7)) | 0;
- hi = (hi + Math.imul(ah5, bh7)) | 0;
- lo = (lo + Math.imul(al4, bl8)) | 0;
- mid = (mid + Math.imul(al4, bh8)) | 0;
- mid = (mid + Math.imul(ah4, bl8)) | 0;
- hi = (hi + Math.imul(ah4, bh8)) | 0;
- lo = (lo + Math.imul(al3, bl9)) | 0;
- mid = (mid + Math.imul(al3, bh9)) | 0;
- mid = (mid + Math.imul(ah3, bl9)) | 0;
- hi = (hi + Math.imul(ah3, bh9)) | 0;
- var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
- w12 &= 0x3ffffff;
- /* k = 13 */
- lo = Math.imul(al9, bl4);
- mid = Math.imul(al9, bh4);
- mid = (mid + Math.imul(ah9, bl4)) | 0;
- hi = Math.imul(ah9, bh4);
- lo = (lo + Math.imul(al8, bl5)) | 0;
- mid = (mid + Math.imul(al8, bh5)) | 0;
- mid = (mid + Math.imul(ah8, bl5)) | 0;
- hi = (hi + Math.imul(ah8, bh5)) | 0;
- lo = (lo + Math.imul(al7, bl6)) | 0;
- mid = (mid + Math.imul(al7, bh6)) | 0;
- mid = (mid + Math.imul(ah7, bl6)) | 0;
- hi = (hi + Math.imul(ah7, bh6)) | 0;
- lo = (lo + Math.imul(al6, bl7)) | 0;
- mid = (mid + Math.imul(al6, bh7)) | 0;
- mid = (mid + Math.imul(ah6, bl7)) | 0;
- hi = (hi + Math.imul(ah6, bh7)) | 0;
- lo = (lo + Math.imul(al5, bl8)) | 0;
- mid = (mid + Math.imul(al5, bh8)) | 0;
- mid = (mid + Math.imul(ah5, bl8)) | 0;
- hi = (hi + Math.imul(ah5, bh8)) | 0;
- lo = (lo + Math.imul(al4, bl9)) | 0;
- mid = (mid + Math.imul(al4, bh9)) | 0;
- mid = (mid + Math.imul(ah4, bl9)) | 0;
- hi = (hi + Math.imul(ah4, bh9)) | 0;
- var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
- w13 &= 0x3ffffff;
- /* k = 14 */
- lo = Math.imul(al9, bl5);
- mid = Math.imul(al9, bh5);
- mid = (mid + Math.imul(ah9, bl5)) | 0;
- hi = Math.imul(ah9, bh5);
- lo = (lo + Math.imul(al8, bl6)) | 0;
- mid = (mid + Math.imul(al8, bh6)) | 0;
- mid = (mid + Math.imul(ah8, bl6)) | 0;
- hi = (hi + Math.imul(ah8, bh6)) | 0;
- lo = (lo + Math.imul(al7, bl7)) | 0;
- mid = (mid + Math.imul(al7, bh7)) | 0;
- mid = (mid + Math.imul(ah7, bl7)) | 0;
- hi = (hi + Math.imul(ah7, bh7)) | 0;
- lo = (lo + Math.imul(al6, bl8)) | 0;
- mid = (mid + Math.imul(al6, bh8)) | 0;
- mid = (mid + Math.imul(ah6, bl8)) | 0;
- hi = (hi + Math.imul(ah6, bh8)) | 0;
- lo = (lo + Math.imul(al5, bl9)) | 0;
- mid = (mid + Math.imul(al5, bh9)) | 0;
- mid = (mid + Math.imul(ah5, bl9)) | 0;
- hi = (hi + Math.imul(ah5, bh9)) | 0;
- var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
- w14 &= 0x3ffffff;
- /* k = 15 */
- lo = Math.imul(al9, bl6);
- mid = Math.imul(al9, bh6);
- mid = (mid + Math.imul(ah9, bl6)) | 0;
- hi = Math.imul(ah9, bh6);
- lo = (lo + Math.imul(al8, bl7)) | 0;
- mid = (mid + Math.imul(al8, bh7)) | 0;
- mid = (mid + Math.imul(ah8, bl7)) | 0;
- hi = (hi + Math.imul(ah8, bh7)) | 0;
- lo = (lo + Math.imul(al7, bl8)) | 0;
- mid = (mid + Math.imul(al7, bh8)) | 0;
- mid = (mid + Math.imul(ah7, bl8)) | 0;
- hi = (hi + Math.imul(ah7, bh8)) | 0;
- lo = (lo + Math.imul(al6, bl9)) | 0;
- mid = (mid + Math.imul(al6, bh9)) | 0;
- mid = (mid + Math.imul(ah6, bl9)) | 0;
- hi = (hi + Math.imul(ah6, bh9)) | 0;
- var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
- w15 &= 0x3ffffff;
- /* k = 16 */
- lo = Math.imul(al9, bl7);
- mid = Math.imul(al9, bh7);
- mid = (mid + Math.imul(ah9, bl7)) | 0;
- hi = Math.imul(ah9, bh7);
- lo = (lo + Math.imul(al8, bl8)) | 0;
- mid = (mid + Math.imul(al8, bh8)) | 0;
- mid = (mid + Math.imul(ah8, bl8)) | 0;
- hi = (hi + Math.imul(ah8, bh8)) | 0;
- lo = (lo + Math.imul(al7, bl9)) | 0;
- mid = (mid + Math.imul(al7, bh9)) | 0;
- mid = (mid + Math.imul(ah7, bl9)) | 0;
- hi = (hi + Math.imul(ah7, bh9)) | 0;
- var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
- w16 &= 0x3ffffff;
- /* k = 17 */
- lo = Math.imul(al9, bl8);
- mid = Math.imul(al9, bh8);
- mid = (mid + Math.imul(ah9, bl8)) | 0;
- hi = Math.imul(ah9, bh8);
- lo = (lo + Math.imul(al8, bl9)) | 0;
- mid = (mid + Math.imul(al8, bh9)) | 0;
- mid = (mid + Math.imul(ah8, bl9)) | 0;
- hi = (hi + Math.imul(ah8, bh9)) | 0;
- var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
- w17 &= 0x3ffffff;
- /* k = 18 */
- lo = Math.imul(al9, bl9);
- mid = Math.imul(al9, bh9);
- mid = (mid + Math.imul(ah9, bl9)) | 0;
- hi = Math.imul(ah9, bh9);
- var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
- c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
- w18 &= 0x3ffffff;
- o[0] = w0;
- o[1] = w1;
- o[2] = w2;
- o[3] = w3;
- o[4] = w4;
- o[5] = w5;
- o[6] = w6;
- o[7] = w7;
- o[8] = w8;
- o[9] = w9;
- o[10] = w10;
- o[11] = w11;
- o[12] = w12;
- o[13] = w13;
- o[14] = w14;
- o[15] = w15;
- o[16] = w16;
- o[17] = w17;
- o[18] = w18;
- if (c !== 0) {
- o[19] = c;
- out.length++;
- }
- return out;
- };
-
- // Polyfill comb
- if (!Math.imul) {
- comb10MulTo = smallMulTo;
- }
-
- function bigMulTo (self, num, out) {
- out.negative = num.negative ^ self.negative;
- out.length = self.length + num.length;
-
- var carry = 0;
- var hncarry = 0;
- for (var k = 0; k < out.length - 1; k++) {
- // Sum all words with the same `i + j = k` and accumulate `ncarry`,
- // note that ncarry could be >= 0x3ffffff
- var ncarry = hncarry;
- hncarry = 0;
- var rword = carry & 0x3ffffff;
- var maxJ = Math.min(k, num.length - 1);
- for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
- var i = k - j;
- var a = self.words[i] | 0;
- var b = num.words[j] | 0;
- var r = a * b;
-
- var lo = r & 0x3ffffff;
- ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
- lo = (lo + rword) | 0;
- rword = lo & 0x3ffffff;
- ncarry = (ncarry + (lo >>> 26)) | 0;
-
- hncarry += ncarry >>> 26;
- ncarry &= 0x3ffffff;
- }
- out.words[k] = rword;
- carry = ncarry;
- ncarry = hncarry;
- }
- if (carry !== 0) {
- out.words[k] = carry;
- } else {
- out.length--;
- }
-
- return out.strip();
- }
-
- function jumboMulTo (self, num, out) {
- var fftm = new FFTM();
- return fftm.mulp(self, num, out);
- }
-
- BN.prototype.mulTo = function mulTo (num, out) {
- var res;
- var len = this.length + num.length;
- if (this.length === 10 && num.length === 10) {
- res = comb10MulTo(this, num, out);
- } else if (len < 63) {
- res = smallMulTo(this, num, out);
- } else if (len < 1024) {
- res = bigMulTo(this, num, out);
- } else {
- res = jumboMulTo(this, num, out);
- }
-
- return res;
- };
-
- // Cooley-Tukey algorithm for FFT
- // slightly revisited to rely on looping instead of recursion
-
- function FFTM (x, y) {
- this.x = x;
- this.y = y;
- }
-
- FFTM.prototype.makeRBT = function makeRBT (N) {
- var t = new Array(N);
- var l = BN.prototype._countBits(N) - 1;
- for (var i = 0; i < N; i++) {
- t[i] = this.revBin(i, l, N);
- }
-
- return t;
- };
-
- // Returns binary-reversed representation of `x`
- FFTM.prototype.revBin = function revBin (x, l, N) {
- if (x === 0 || x === N - 1) return x;
-
- var rb = 0;
- for (var i = 0; i < l; i++) {
- rb |= (x & 1) << (l - i - 1);
- x >>= 1;
- }
-
- return rb;
- };
-
- // Performs "tweedling" phase, therefore 'emulating'
- // behaviour of the recursive algorithm
- FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
- for (var i = 0; i < N; i++) {
- rtws[i] = rws[rbt[i]];
- itws[i] = iws[rbt[i]];
- }
- };
-
- FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
- this.permute(rbt, rws, iws, rtws, itws, N);
-
- for (var s = 1; s < N; s <<= 1) {
- var l = s << 1;
-
- var rtwdf = Math.cos(2 * Math.PI / l);
- var itwdf = Math.sin(2 * Math.PI / l);
-
- for (var p = 0; p < N; p += l) {
- var rtwdf_ = rtwdf;
- var itwdf_ = itwdf;
-
- for (var j = 0; j < s; j++) {
- var re = rtws[p + j];
- var ie = itws[p + j];
-
- var ro = rtws[p + j + s];
- var io = itws[p + j + s];
-
- var rx = rtwdf_ * ro - itwdf_ * io;
-
- io = rtwdf_ * io + itwdf_ * ro;
- ro = rx;
-
- rtws[p + j] = re + ro;
- itws[p + j] = ie + io;
-
- rtws[p + j + s] = re - ro;
- itws[p + j + s] = ie - io;
-
- /* jshint maxdepth : false */
- if (j !== l) {
- rx = rtwdf * rtwdf_ - itwdf * itwdf_;
-
- itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
- rtwdf_ = rx;
- }
- }
- }
- }
- };
-
- FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
- var N = Math.max(m, n) | 1;
- var odd = N & 1;
- var i = 0;
- for (N = N / 2 | 0; N; N = N >>> 1) {
- i++;
- }
-
- return 1 << i + 1 + odd;
- };
-
- FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
- if (N <= 1) return;
-
- for (var i = 0; i < N / 2; i++) {
- var t = rws[i];
-
- rws[i] = rws[N - i - 1];
- rws[N - i - 1] = t;
-
- t = iws[i];
-
- iws[i] = -iws[N - i - 1];
- iws[N - i - 1] = -t;
- }
- };
-
- FFTM.prototype.normalize13b = function normalize13b (ws, N) {
- var carry = 0;
- for (var i = 0; i < N / 2; i++) {
- var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
- Math.round(ws[2 * i] / N) +
- carry;
-
- ws[i] = w & 0x3ffffff;
-
- if (w < 0x4000000) {
- carry = 0;
- } else {
- carry = w / 0x4000000 | 0;
- }
- }
-
- return ws;
- };
-
- FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
- var carry = 0;
- for (var i = 0; i < len; i++) {
- carry = carry + (ws[i] | 0);
-
- rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
- rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
- }
-
- // Pad with zeroes
- for (i = 2 * len; i < N; ++i) {
- rws[i] = 0;
- }
-
- assert(carry === 0);
- assert((carry & ~0x1fff) === 0);
- };
-
- FFTM.prototype.stub = function stub (N) {
- var ph = new Array(N);
- for (var i = 0; i < N; i++) {
- ph[i] = 0;
- }
-
- return ph;
- };
-
- FFTM.prototype.mulp = function mulp (x, y, out) {
- var N = 2 * this.guessLen13b(x.length, y.length);
-
- var rbt = this.makeRBT(N);
-
- var _ = this.stub(N);
-
- var rws = new Array(N);
- var rwst = new Array(N);
- var iwst = new Array(N);
-
- var nrws = new Array(N);
- var nrwst = new Array(N);
- var niwst = new Array(N);
-
- var rmws = out.words;
- rmws.length = N;
-
- this.convert13b(x.words, x.length, rws, N);
- this.convert13b(y.words, y.length, nrws, N);
-
- this.transform(rws, _, rwst, iwst, N, rbt);
- this.transform(nrws, _, nrwst, niwst, N, rbt);
-
- for (var i = 0; i < N; i++) {
- var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
- iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
- rwst[i] = rx;
- }
-
- this.conjugate(rwst, iwst, N);
- this.transform(rwst, iwst, rmws, _, N, rbt);
- this.conjugate(rmws, _, N);
- this.normalize13b(rmws, N);
-
- out.negative = x.negative ^ y.negative;
- out.length = x.length + y.length;
- return out.strip();
- };
-
- // Multiply `this` by `num`
- BN.prototype.mul = function mul (num) {
- var out = new BN(null);
- out.words = new Array(this.length + num.length);
- return this.mulTo(num, out);
- };
-
- // Multiply employing FFT
- BN.prototype.mulf = function mulf (num) {
- var out = new BN(null);
- out.words = new Array(this.length + num.length);
- return jumboMulTo(this, num, out);
- };
-
- // In-place Multiplication
- BN.prototype.imul = function imul (num) {
- return this.clone().mulTo(num, this);
- };
-
- BN.prototype.imuln = function imuln (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
-
- // Carry
- var carry = 0;
- for (var i = 0; i < this.length; i++) {
- var w = (this.words[i] | 0) * num;
- var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
- carry >>= 26;
- carry += (w / 0x4000000) | 0;
- // NOTE: lo is 27bit maximum
- carry += lo >>> 26;
- this.words[i] = lo & 0x3ffffff;
- }
-
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
-
- return this;
- };
-
- BN.prototype.muln = function muln (num) {
- return this.clone().imuln(num);
- };
-
- // `this` * `this`
- BN.prototype.sqr = function sqr () {
- return this.mul(this);
- };
-
- // `this` * `this` in-place
- BN.prototype.isqr = function isqr () {
- return this.imul(this.clone());
- };
-
- // Math.pow(`this`, `num`)
- BN.prototype.pow = function pow (num) {
- var w = toBitArray(num);
- if (w.length === 0) return new BN(1);
-
- // Skip leading zeroes
- var res = this;
- for (var i = 0; i < w.length; i++, res = res.sqr()) {
- if (w[i] !== 0) break;
- }
-
- if (++i < w.length) {
- for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
- if (w[i] === 0) continue;
-
- res = res.mul(q);
- }
- }
-
- return res;
- };
-
- // Shift-left in-place
- BN.prototype.iushln = function iushln (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
- var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
- var i;
-
- if (r !== 0) {
- var carry = 0;
-
- for (i = 0; i < this.length; i++) {
- var newCarry = this.words[i] & carryMask;
- var c = ((this.words[i] | 0) - newCarry) << r;
- this.words[i] = c | carry;
- carry = newCarry >>> (26 - r);
- }
-
- if (carry) {
- this.words[i] = carry;
- this.length++;
- }
- }
-
- if (s !== 0) {
- for (i = this.length - 1; i >= 0; i--) {
- this.words[i + s] = this.words[i];
- }
-
- for (i = 0; i < s; i++) {
- this.words[i] = 0;
- }
-
- this.length += s;
- }
-
- return this.strip();
- };
-
- BN.prototype.ishln = function ishln (bits) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushln(bits);
- };
-
- // Shift-right in-place
- // NOTE: `hint` is a lowest bit before trailing zeroes
- // NOTE: if `extended` is present - it will be filled with destroyed bits
- BN.prototype.iushrn = function iushrn (bits, hint, extended) {
- assert(typeof bits === 'number' && bits >= 0);
- var h;
- if (hint) {
- h = (hint - (hint % 26)) / 26;
- } else {
- h = 0;
- }
-
- var r = bits % 26;
- var s = Math.min((bits - r) / 26, this.length);
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- var maskedWords = extended;
-
- h -= s;
- h = Math.max(0, h);
-
- // Extended mode, copy masked part
- if (maskedWords) {
- for (var i = 0; i < s; i++) {
- maskedWords.words[i] = this.words[i];
- }
- maskedWords.length = s;
- }
-
- if (s === 0) {
- // No-op, we should not move anything at all
- } else if (this.length > s) {
- this.length -= s;
- for (i = 0; i < this.length; i++) {
- this.words[i] = this.words[i + s];
- }
- } else {
- this.words[0] = 0;
- this.length = 1;
- }
-
- var carry = 0;
- for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
- var word = this.words[i] | 0;
- this.words[i] = (carry << (26 - r)) | (word >>> r);
- carry = word & mask;
- }
-
- // Push carried bits as a mask
- if (maskedWords && carry !== 0) {
- maskedWords.words[maskedWords.length++] = carry;
- }
-
- if (this.length === 0) {
- this.words[0] = 0;
- this.length = 1;
- }
-
- return this.strip();
- };
-
- BN.prototype.ishrn = function ishrn (bits, hint, extended) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushrn(bits, hint, extended);
- };
-
- // Shift-left
- BN.prototype.shln = function shln (bits) {
- return this.clone().ishln(bits);
- };
-
- BN.prototype.ushln = function ushln (bits) {
- return this.clone().iushln(bits);
- };
-
- // Shift-right
- BN.prototype.shrn = function shrn (bits) {
- return this.clone().ishrn(bits);
- };
-
- BN.prototype.ushrn = function ushrn (bits) {
- return this.clone().iushrn(bits);
- };
-
- // Test if n bit is set
- BN.prototype.testn = function testn (bit) {
- assert(typeof bit === 'number' && bit >= 0);
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
-
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) return false;
-
- // Check bit and return
- var w = this.words[s];
-
- return !!(w & q);
- };
-
- // Return only lowers bits of number (in-place)
- BN.prototype.imaskn = function imaskn (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
-
- assert(this.negative === 0, 'imaskn works only with positive numbers');
-
- if (this.length <= s) {
- return this;
- }
-
- if (r !== 0) {
- s++;
- }
- this.length = Math.min(s, this.length);
-
- if (r !== 0) {
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- this.words[this.length - 1] &= mask;
- }
-
- return this.strip();
- };
-
- // Return only lowers bits of number
- BN.prototype.maskn = function maskn (bits) {
- return this.clone().imaskn(bits);
- };
-
- // Add plain number `num` to `this`
- BN.prototype.iaddn = function iaddn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.isubn(-num);
-
- // Possible sign change
- if (this.negative !== 0) {
- if (this.length === 1 && (this.words[0] | 0) < num) {
- this.words[0] = num - (this.words[0] | 0);
- this.negative = 0;
- return this;
- }
-
- this.negative = 0;
- this.isubn(num);
- this.negative = 1;
- return this;
- }
-
- // Add without checks
- return this._iaddn(num);
- };
-
- BN.prototype._iaddn = function _iaddn (num) {
- this.words[0] += num;
-
- // Carry
- for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
- this.words[i] -= 0x4000000;
- if (i === this.length - 1) {
- this.words[i + 1] = 1;
- } else {
- this.words[i + 1]++;
- }
- }
- this.length = Math.max(this.length, i + 1);
-
- return this;
- };
-
- // Subtract plain number `num` from `this`
- BN.prototype.isubn = function isubn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.iaddn(-num);
-
- if (this.negative !== 0) {
- this.negative = 0;
- this.iaddn(num);
- this.negative = 1;
- return this;
- }
-
- this.words[0] -= num;
-
- if (this.length === 1 && this.words[0] < 0) {
- this.words[0] = -this.words[0];
- this.negative = 1;
- } else {
- // Carry
- for (var i = 0; i < this.length && this.words[i] < 0; i++) {
- this.words[i] += 0x4000000;
- this.words[i + 1] -= 1;
- }
- }
-
- return this.strip();
- };
-
- BN.prototype.addn = function addn (num) {
- return this.clone().iaddn(num);
- };
-
- BN.prototype.subn = function subn (num) {
- return this.clone().isubn(num);
- };
-
- BN.prototype.iabs = function iabs () {
- this.negative = 0;
-
- return this;
- };
-
- BN.prototype.abs = function abs () {
- return this.clone().iabs();
- };
-
- BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
- var len = num.length + shift;
- var i;
-
- this._expand(len);
-
- var w;
- var carry = 0;
- for (i = 0; i < num.length; i++) {
- w = (this.words[i + shift] | 0) + carry;
- var right = (num.words[i] | 0) * mul;
- w -= right & 0x3ffffff;
- carry = (w >> 26) - ((right / 0x4000000) | 0);
- this.words[i + shift] = w & 0x3ffffff;
- }
- for (; i < this.length - shift; i++) {
- w = (this.words[i + shift] | 0) + carry;
- carry = w >> 26;
- this.words[i + shift] = w & 0x3ffffff;
- }
-
- if (carry === 0) return this.strip();
-
- // Subtraction overflow
- assert(carry === -1);
- carry = 0;
- for (i = 0; i < this.length; i++) {
- w = -(this.words[i] | 0) + carry;
- carry = w >> 26;
- this.words[i] = w & 0x3ffffff;
- }
- this.negative = 1;
-
- return this.strip();
- };
-
- BN.prototype._wordDiv = function _wordDiv (num, mode) {
- var shift = this.length - num.length;
-
- var a = this.clone();
- var b = num;
-
- // Normalize
- var bhi = b.words[b.length - 1] | 0;
- var bhiBits = this._countBits(bhi);
- shift = 26 - bhiBits;
- if (shift !== 0) {
- b = b.ushln(shift);
- a.iushln(shift);
- bhi = b.words[b.length - 1] | 0;
- }
-
- // Initialize quotient
- var m = a.length - b.length;
- var q;
-
- if (mode !== 'mod') {
- q = new BN(null);
- q.length = m + 1;
- q.words = new Array(q.length);
- for (var i = 0; i < q.length; i++) {
- q.words[i] = 0;
- }
- }
-
- var diff = a.clone()._ishlnsubmul(b, 1, m);
- if (diff.negative === 0) {
- a = diff;
- if (q) {
- q.words[m] = 1;
- }
- }
-
- for (var j = m - 1; j >= 0; j--) {
- var qj = (a.words[b.length + j] | 0) * 0x4000000 +
- (a.words[b.length + j - 1] | 0);
-
- // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
- // (0x7ffffff)
- qj = Math.min((qj / bhi) | 0, 0x3ffffff);
-
- a._ishlnsubmul(b, qj, j);
- while (a.negative !== 0) {
- qj--;
- a.negative = 0;
- a._ishlnsubmul(b, 1, j);
- if (!a.isZero()) {
- a.negative ^= 1;
- }
- }
- if (q) {
- q.words[j] = qj;
- }
- }
- if (q) {
- q.strip();
- }
- a.strip();
-
- // Denormalize
- if (mode !== 'div' && shift !== 0) {
- a.iushrn(shift);
- }
-
- return {
- div: q || null,
- mod: a
- };
- };
-
- // NOTE: 1) `mode` can be set to `mod` to request mod only,
- // to `div` to request div only, or be absent to
- // request both div & mod
- // 2) `positive` is true if unsigned mod is requested
- BN.prototype.divmod = function divmod (num, mode, positive) {
- assert(!num.isZero());
-
- if (this.isZero()) {
- return {
- div: new BN(0),
- mod: new BN(0)
- };
- }
-
- var div, mod, res;
- if (this.negative !== 0 && num.negative === 0) {
- res = this.neg().divmod(num, mode);
-
- if (mode !== 'mod') {
- div = res.div.neg();
- }
-
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.iadd(num);
- }
- }
-
- return {
- div: div,
- mod: mod
- };
- }
-
- if (this.negative === 0 && num.negative !== 0) {
- res = this.divmod(num.neg(), mode);
-
- if (mode !== 'mod') {
- div = res.div.neg();
- }
-
- return {
- div: div,
- mod: res.mod
- };
- }
-
- if ((this.negative & num.negative) !== 0) {
- res = this.neg().divmod(num.neg(), mode);
-
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.isub(num);
- }
- }
-
- return {
- div: res.div,
- mod: mod
- };
- }
-
- // Both numbers are positive at this point
-
- // Strip both numbers to approximate shift value
- if (num.length > this.length || this.cmp(num) < 0) {
- return {
- div: new BN(0),
- mod: this
- };
- }
-
- // Very short reduction
- if (num.length === 1) {
- if (mode === 'div') {
- return {
- div: this.divn(num.words[0]),
- mod: null
- };
- }
-
- if (mode === 'mod') {
- return {
- div: null,
- mod: new BN(this.modn(num.words[0]))
- };
- }
-
- return {
- div: this.divn(num.words[0]),
- mod: new BN(this.modn(num.words[0]))
- };
- }
-
- return this._wordDiv(num, mode);
- };
-
- // Find `this` / `num`
- BN.prototype.div = function div (num) {
- return this.divmod(num, 'div', false).div;
- };
-
- // Find `this` % `num`
- BN.prototype.mod = function mod (num) {
- return this.divmod(num, 'mod', false).mod;
- };
-
- BN.prototype.umod = function umod (num) {
- return this.divmod(num, 'mod', true).mod;
- };
-
- // Find Round(`this` / `num`)
- BN.prototype.divRound = function divRound (num) {
- var dm = this.divmod(num);
-
- // Fast case - exact division
- if (dm.mod.isZero()) return dm.div;
-
- var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
-
- var half = num.ushrn(1);
- var r2 = num.andln(1);
- var cmp = mod.cmp(half);
-
- // Round down
- if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
-
- // Round up
- return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
- };
-
- BN.prototype.modn = function modn (num) {
- assert(num <= 0x3ffffff);
- var p = (1 << 26) % num;
-
- var acc = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- acc = (p * acc + (this.words[i] | 0)) % num;
- }
-
- return acc;
- };
-
- // In-place division by number
- BN.prototype.idivn = function idivn (num) {
- assert(num <= 0x3ffffff);
-
- var carry = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var w = (this.words[i] | 0) + carry * 0x4000000;
- this.words[i] = (w / num) | 0;
- carry = w % num;
- }
-
- return this.strip();
- };
-
- BN.prototype.divn = function divn (num) {
- return this.clone().idivn(num);
- };
-
- BN.prototype.egcd = function egcd (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
-
- var x = this;
- var y = p.clone();
-
- if (x.negative !== 0) {
- x = x.umod(p);
- } else {
- x = x.clone();
- }
-
- // A * x + B * y = x
- var A = new BN(1);
- var B = new BN(0);
-
- // C * x + D * y = y
- var C = new BN(0);
- var D = new BN(1);
-
- var g = 0;
-
- while (x.isEven() && y.isEven()) {
- x.iushrn(1);
- y.iushrn(1);
- ++g;
- }
-
- var yp = y.clone();
- var xp = x.clone();
-
- while (!x.isZero()) {
- for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- x.iushrn(i);
- while (i-- > 0) {
- if (A.isOdd() || B.isOdd()) {
- A.iadd(yp);
- B.isub(xp);
- }
-
- A.iushrn(1);
- B.iushrn(1);
- }
- }
-
- for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- y.iushrn(j);
- while (j-- > 0) {
- if (C.isOdd() || D.isOdd()) {
- C.iadd(yp);
- D.isub(xp);
- }
-
- C.iushrn(1);
- D.iushrn(1);
- }
- }
-
- if (x.cmp(y) >= 0) {
- x.isub(y);
- A.isub(C);
- B.isub(D);
- } else {
- y.isub(x);
- C.isub(A);
- D.isub(B);
- }
- }
-
- return {
- a: C,
- b: D,
- gcd: y.iushln(g)
- };
- };
-
- // This is reduced incarnation of the binary EEA
- // above, designated to invert members of the
- // _prime_ fields F(p) at a maximal speed
- BN.prototype._invmp = function _invmp (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
-
- var a = this;
- var b = p.clone();
-
- if (a.negative !== 0) {
- a = a.umod(p);
- } else {
- a = a.clone();
- }
-
- var x1 = new BN(1);
- var x2 = new BN(0);
-
- var delta = b.clone();
-
- while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
- for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- a.iushrn(i);
- while (i-- > 0) {
- if (x1.isOdd()) {
- x1.iadd(delta);
- }
-
- x1.iushrn(1);
- }
- }
-
- for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- b.iushrn(j);
- while (j-- > 0) {
- if (x2.isOdd()) {
- x2.iadd(delta);
- }
-
- x2.iushrn(1);
- }
- }
-
- if (a.cmp(b) >= 0) {
- a.isub(b);
- x1.isub(x2);
- } else {
- b.isub(a);
- x2.isub(x1);
- }
- }
-
- var res;
- if (a.cmpn(1) === 0) {
- res = x1;
- } else {
- res = x2;
- }
-
- if (res.cmpn(0) < 0) {
- res.iadd(p);
- }
-
- return res;
- };
-
- BN.prototype.gcd = function gcd (num) {
- if (this.isZero()) return num.abs();
- if (num.isZero()) return this.abs();
-
- var a = this.clone();
- var b = num.clone();
- a.negative = 0;
- b.negative = 0;
-
- // Remove common factor of two
- for (var shift = 0; a.isEven() && b.isEven(); shift++) {
- a.iushrn(1);
- b.iushrn(1);
- }
-
- do {
- while (a.isEven()) {
- a.iushrn(1);
- }
- while (b.isEven()) {
- b.iushrn(1);
- }
-
- var r = a.cmp(b);
- if (r < 0) {
- // Swap `a` and `b` to make `a` always bigger than `b`
- var t = a;
- a = b;
- b = t;
- } else if (r === 0 || b.cmpn(1) === 0) {
- break;
- }
-
- a.isub(b);
- } while (true);
-
- return b.iushln(shift);
- };
-
- // Invert number in the field F(num)
- BN.prototype.invm = function invm (num) {
- return this.egcd(num).a.umod(num);
- };
-
- BN.prototype.isEven = function isEven () {
- return (this.words[0] & 1) === 0;
- };
-
- BN.prototype.isOdd = function isOdd () {
- return (this.words[0] & 1) === 1;
- };
-
- // And first word and num
- BN.prototype.andln = function andln (num) {
- return this.words[0] & num;
- };
-
- // Increment at the bit position in-line
- BN.prototype.bincn = function bincn (bit) {
- assert(typeof bit === 'number');
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
-
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) {
- this._expand(s + 1);
- this.words[s] |= q;
- return this;
- }
-
- // Add bit and propagate, if needed
- var carry = q;
- for (var i = s; carry !== 0 && i < this.length; i++) {
- var w = this.words[i] | 0;
- w += carry;
- carry = w >>> 26;
- w &= 0x3ffffff;
- this.words[i] = w;
- }
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
- return this;
- };
-
- BN.prototype.isZero = function isZero () {
- return this.length === 1 && this.words[0] === 0;
- };
-
- BN.prototype.cmpn = function cmpn (num) {
- var negative = num < 0;
-
- if (this.negative !== 0 && !negative) return -1;
- if (this.negative === 0 && negative) return 1;
-
- this.strip();
-
- var res;
- if (this.length > 1) {
- res = 1;
- } else {
- if (negative) {
- num = -num;
- }
-
- assert(num <= 0x3ffffff, 'Number is too big');
-
- var w = this.words[0] | 0;
- res = w === num ? 0 : w < num ? -1 : 1;
- }
- if (this.negative !== 0) return -res | 0;
- return res;
- };
-
- // Compare two numbers and return:
- // 1 - if `this` > `num`
- // 0 - if `this` == `num`
- // -1 - if `this` < `num`
- BN.prototype.cmp = function cmp (num) {
- if (this.negative !== 0 && num.negative === 0) return -1;
- if (this.negative === 0 && num.negative !== 0) return 1;
-
- var res = this.ucmp(num);
- if (this.negative !== 0) return -res | 0;
- return res;
- };
-
- // Unsigned comparison
- BN.prototype.ucmp = function ucmp (num) {
- // At this point both numbers have the same sign
- if (this.length > num.length) return 1;
- if (this.length < num.length) return -1;
-
- var res = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var a = this.words[i] | 0;
- var b = num.words[i] | 0;
-
- if (a === b) continue;
- if (a < b) {
- res = -1;
- } else if (a > b) {
- res = 1;
- }
- break;
- }
- return res;
- };
-
- BN.prototype.gtn = function gtn (num) {
- return this.cmpn(num) === 1;
- };
-
- BN.prototype.gt = function gt (num) {
- return this.cmp(num) === 1;
- };
-
- BN.prototype.gten = function gten (num) {
- return this.cmpn(num) >= 0;
- };
-
- BN.prototype.gte = function gte (num) {
- return this.cmp(num) >= 0;
- };
-
- BN.prototype.ltn = function ltn (num) {
- return this.cmpn(num) === -1;
- };
-
- BN.prototype.lt = function lt (num) {
- return this.cmp(num) === -1;
- };
-
- BN.prototype.lten = function lten (num) {
- return this.cmpn(num) <= 0;
- };
-
- BN.prototype.lte = function lte (num) {
- return this.cmp(num) <= 0;
- };
-
- BN.prototype.eqn = function eqn (num) {
- return this.cmpn(num) === 0;
- };
-
- BN.prototype.eq = function eq (num) {
- return this.cmp(num) === 0;
- };
-
- //
- // A reduce context, could be using montgomery or something better, depending
- // on the `m` itself.
- //
- BN.red = function red (num) {
- return new Red(num);
- };
-
- BN.prototype.toRed = function toRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- assert(this.negative === 0, 'red works only with positives');
- return ctx.convertTo(this)._forceRed(ctx);
- };
-
- BN.prototype.fromRed = function fromRed () {
- assert(this.red, 'fromRed works only with numbers in reduction context');
- return this.red.convertFrom(this);
- };
-
- BN.prototype._forceRed = function _forceRed (ctx) {
- this.red = ctx;
- return this;
- };
-
- BN.prototype.forceRed = function forceRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- return this._forceRed(ctx);
- };
-
- BN.prototype.redAdd = function redAdd (num) {
- assert(this.red, 'redAdd works only with red numbers');
- return this.red.add(this, num);
- };
-
- BN.prototype.redIAdd = function redIAdd (num) {
- assert(this.red, 'redIAdd works only with red numbers');
- return this.red.iadd(this, num);
- };
-
- BN.prototype.redSub = function redSub (num) {
- assert(this.red, 'redSub works only with red numbers');
- return this.red.sub(this, num);
- };
-
- BN.prototype.redISub = function redISub (num) {
- assert(this.red, 'redISub works only with red numbers');
- return this.red.isub(this, num);
- };
-
- BN.prototype.redShl = function redShl (num) {
- assert(this.red, 'redShl works only with red numbers');
- return this.red.shl(this, num);
- };
-
- BN.prototype.redMul = function redMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.mul(this, num);
- };
-
- BN.prototype.redIMul = function redIMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.imul(this, num);
- };
-
- BN.prototype.redSqr = function redSqr () {
- assert(this.red, 'redSqr works only with red numbers');
- this.red._verify1(this);
- return this.red.sqr(this);
- };
-
- BN.prototype.redISqr = function redISqr () {
- assert(this.red, 'redISqr works only with red numbers');
- this.red._verify1(this);
- return this.red.isqr(this);
- };
-
- // Square root over p
- BN.prototype.redSqrt = function redSqrt () {
- assert(this.red, 'redSqrt works only with red numbers');
- this.red._verify1(this);
- return this.red.sqrt(this);
- };
-
- BN.prototype.redInvm = function redInvm () {
- assert(this.red, 'redInvm works only with red numbers');
- this.red._verify1(this);
- return this.red.invm(this);
- };
-
- // Return negative clone of `this` % `red modulo`
- BN.prototype.redNeg = function redNeg () {
- assert(this.red, 'redNeg works only with red numbers');
- this.red._verify1(this);
- return this.red.neg(this);
- };
-
- BN.prototype.redPow = function redPow (num) {
- assert(this.red && !num.red, 'redPow(normalNum)');
- this.red._verify1(this);
- return this.red.pow(this, num);
- };
-
- // Prime numbers with efficient reduction
- var primes = {
- k256: null,
- p224: null,
- p192: null,
- p25519: null
- };
-
- // Pseudo-Mersenne prime
- function MPrime (name, p) {
- // P = 2 ^ N - K
- this.name = name;
- this.p = new BN(p, 16);
- this.n = this.p.bitLength();
- this.k = new BN(1).iushln(this.n).isub(this.p);
-
- this.tmp = this._tmp();
- }
-
- MPrime.prototype._tmp = function _tmp () {
- var tmp = new BN(null);
- tmp.words = new Array(Math.ceil(this.n / 13));
- return tmp;
- };
-
- MPrime.prototype.ireduce = function ireduce (num) {
- // Assumes that `num` is less than `P^2`
- // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
- var r = num;
- var rlen;
-
- do {
- this.split(r, this.tmp);
- r = this.imulK(r);
- r = r.iadd(this.tmp);
- rlen = r.bitLength();
- } while (rlen > this.n);
-
- var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
- if (cmp === 0) {
- r.words[0] = 0;
- r.length = 1;
- } else if (cmp > 0) {
- r.isub(this.p);
- } else {
- r.strip();
- }
-
- return r;
- };
-
- MPrime.prototype.split = function split (input, out) {
- input.iushrn(this.n, 0, out);
- };
-
- MPrime.prototype.imulK = function imulK (num) {
- return num.imul(this.k);
- };
-
- function K256 () {
- MPrime.call(
- this,
- 'k256',
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
- }
- inherits(K256, MPrime);
-
- K256.prototype.split = function split (input, output) {
- // 256 = 9 * 26 + 22
- var mask = 0x3fffff;
-
- var outLen = Math.min(input.length, 9);
- for (var i = 0; i < outLen; i++) {
- output.words[i] = input.words[i];
- }
- output.length = outLen;
-
- if (input.length <= 9) {
- input.words[0] = 0;
- input.length = 1;
- return;
- }
-
- // Shift by 9 limbs
- var prev = input.words[9];
- output.words[output.length++] = prev & mask;
-
- for (i = 10; i < input.length; i++) {
- var next = input.words[i] | 0;
- input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
- prev = next;
- }
- prev >>>= 22;
- input.words[i - 10] = prev;
- if (prev === 0 && input.length > 10) {
- input.length -= 10;
- } else {
- input.length -= 9;
- }
- };
-
- K256.prototype.imulK = function imulK (num) {
- // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
- num.words[num.length] = 0;
- num.words[num.length + 1] = 0;
- num.length += 2;
-
- // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
- var lo = 0;
- for (var i = 0; i < num.length; i++) {
- var w = num.words[i] | 0;
- lo += w * 0x3d1;
- num.words[i] = lo & 0x3ffffff;
- lo = w * 0x40 + ((lo / 0x4000000) | 0);
- }
-
- // Fast length reduction
- if (num.words[num.length - 1] === 0) {
- num.length--;
- if (num.words[num.length - 1] === 0) {
- num.length--;
- }
- }
- return num;
- };
-
- function P224 () {
- MPrime.call(
- this,
- 'p224',
- 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
- }
- inherits(P224, MPrime);
-
- function P192 () {
- MPrime.call(
- this,
- 'p192',
- 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
- }
- inherits(P192, MPrime);
-
- function P25519 () {
- // 2 ^ 255 - 19
- MPrime.call(
- this,
- '25519',
- '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
- }
- inherits(P25519, MPrime);
-
- P25519.prototype.imulK = function imulK (num) {
- // K = 0x13
- var carry = 0;
- for (var i = 0; i < num.length; i++) {
- var hi = (num.words[i] | 0) * 0x13 + carry;
- var lo = hi & 0x3ffffff;
- hi >>>= 26;
-
- num.words[i] = lo;
- carry = hi;
- }
- if (carry !== 0) {
- num.words[num.length++] = carry;
- }
- return num;
- };
-
- // Exported mostly for testing purposes, use plain name instead
- BN._prime = function prime (name) {
- // Cached version of prime
- if (primes[name]) return primes[name];
-
- var prime;
- if (name === 'k256') {
- prime = new K256();
- } else if (name === 'p224') {
- prime = new P224();
- } else if (name === 'p192') {
- prime = new P192();
- } else if (name === 'p25519') {
- prime = new P25519();
- } else {
- throw new Error('Unknown prime ' + name);
- }
- primes[name] = prime;
-
- return prime;
- };
-
- //
- // Base reduction engine
- //
- function Red (m) {
- if (typeof m === 'string') {
- var prime = BN._prime(m);
- this.m = prime.p;
- this.prime = prime;
- } else {
- assert(m.gtn(1), 'modulus must be greater than 1');
- this.m = m;
- this.prime = null;
- }
- }
-
- Red.prototype._verify1 = function _verify1 (a) {
- assert(a.negative === 0, 'red works only with positives');
- assert(a.red, 'red works only with red numbers');
- };
-
- Red.prototype._verify2 = function _verify2 (a, b) {
- assert((a.negative | b.negative) === 0, 'red works only with positives');
- assert(a.red && a.red === b.red,
- 'red works only with red numbers');
- };
-
- Red.prototype.imod = function imod (a) {
- if (this.prime) return this.prime.ireduce(a)._forceRed(this);
- return a.umod(this.m)._forceRed(this);
- };
-
- Red.prototype.neg = function neg (a) {
- if (a.isZero()) {
- return a.clone();
- }
-
- return this.m.sub(a)._forceRed(this);
- };
-
- Red.prototype.add = function add (a, b) {
- this._verify2(a, b);
-
- var res = a.add(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res._forceRed(this);
- };
-
- Red.prototype.iadd = function iadd (a, b) {
- this._verify2(a, b);
-
- var res = a.iadd(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res;
- };
-
- Red.prototype.sub = function sub (a, b) {
- this._verify2(a, b);
-
- var res = a.sub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res._forceRed(this);
- };
-
- Red.prototype.isub = function isub (a, b) {
- this._verify2(a, b);
-
- var res = a.isub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res;
- };
-
- Red.prototype.shl = function shl (a, num) {
- this._verify1(a);
- return this.imod(a.ushln(num));
- };
-
- Red.prototype.imul = function imul (a, b) {
- this._verify2(a, b);
- return this.imod(a.imul(b));
- };
-
- Red.prototype.mul = function mul (a, b) {
- this._verify2(a, b);
- return this.imod(a.mul(b));
- };
-
- Red.prototype.isqr = function isqr (a) {
- return this.imul(a, a.clone());
- };
-
- Red.prototype.sqr = function sqr (a) {
- return this.mul(a, a);
- };
-
- Red.prototype.sqrt = function sqrt (a) {
- if (a.isZero()) return a.clone();
-
- var mod3 = this.m.andln(3);
- assert(mod3 % 2 === 1);
-
- // Fast case
- if (mod3 === 3) {
- var pow = this.m.add(new BN(1)).iushrn(2);
- return this.pow(a, pow);
- }
-
- // Tonelli-Shanks algorithm (Totally unoptimized and slow)
- //
- // Find Q and S, that Q * 2 ^ S = (P - 1)
- var q = this.m.subn(1);
- var s = 0;
- while (!q.isZero() && q.andln(1) === 0) {
- s++;
- q.iushrn(1);
- }
- assert(!q.isZero());
-
- var one = new BN(1).toRed(this);
- var nOne = one.redNeg();
-
- // Find quadratic non-residue
- // NOTE: Max is such because of generalized Riemann hypothesis.
- var lpow = this.m.subn(1).iushrn(1);
- var z = this.m.bitLength();
- z = new BN(2 * z * z).toRed(this);
-
- while (this.pow(z, lpow).cmp(nOne) !== 0) {
- z.redIAdd(nOne);
- }
-
- var c = this.pow(z, q);
- var r = this.pow(a, q.addn(1).iushrn(1));
- var t = this.pow(a, q);
- var m = s;
- while (t.cmp(one) !== 0) {
- var tmp = t;
- for (var i = 0; tmp.cmp(one) !== 0; i++) {
- tmp = tmp.redSqr();
- }
- assert(i < m);
- var b = this.pow(c, new BN(1).iushln(m - i - 1));
-
- r = r.redMul(b);
- c = b.redSqr();
- t = t.redMul(c);
- m = i;
- }
-
- return r;
- };
-
- Red.prototype.invm = function invm (a) {
- var inv = a._invmp(this.m);
- if (inv.negative !== 0) {
- inv.negative = 0;
- return this.imod(inv).redNeg();
- } else {
- return this.imod(inv);
- }
- };
-
- Red.prototype.pow = function pow (a, num) {
- if (num.isZero()) return new BN(1);
- if (num.cmpn(1) === 0) return a.clone();
-
- var windowSize = 4;
- var wnd = new Array(1 << windowSize);
- wnd[0] = new BN(1).toRed(this);
- wnd[1] = a;
- for (var i = 2; i < wnd.length; i++) {
- wnd[i] = this.mul(wnd[i - 1], a);
- }
-
- var res = wnd[0];
- var current = 0;
- var currentLen = 0;
- var start = num.bitLength() % 26;
- if (start === 0) {
- start = 26;
- }
-
- for (i = num.length - 1; i >= 0; i--) {
- var word = num.words[i];
- for (var j = start - 1; j >= 0; j--) {
- var bit = (word >> j) & 1;
- if (res !== wnd[0]) {
- res = this.sqr(res);
- }
-
- if (bit === 0 && current === 0) {
- currentLen = 0;
- continue;
- }
-
- current <<= 1;
- current |= bit;
- currentLen++;
- if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
-
- res = this.mul(res, wnd[current]);
- currentLen = 0;
- current = 0;
- }
- start = 26;
- }
-
- return res;
- };
-
- Red.prototype.convertTo = function convertTo (num) {
- var r = num.umod(this.m);
-
- return r === num ? r.clone() : r;
- };
-
- Red.prototype.convertFrom = function convertFrom (num) {
- var res = num.clone();
- res.red = null;
- return res;
- };
-
- //
- // Montgomery method engine
- //
-
- BN.mont = function mont (num) {
- return new Mont(num);
- };
-
- function Mont (m) {
- Red.call(this, m);
-
- this.shift = this.m.bitLength();
- if (this.shift % 26 !== 0) {
- this.shift += 26 - (this.shift % 26);
- }
-
- this.r = new BN(1).iushln(this.shift);
- this.r2 = this.imod(this.r.sqr());
- this.rinv = this.r._invmp(this.m);
-
- this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
- this.minv = this.minv.umod(this.r);
- this.minv = this.r.sub(this.minv);
- }
- inherits(Mont, Red);
-
- Mont.prototype.convertTo = function convertTo (num) {
- return this.imod(num.ushln(this.shift));
- };
-
- Mont.prototype.convertFrom = function convertFrom (num) {
- var r = this.imod(num.mul(this.rinv));
- r.red = null;
- return r;
- };
-
- Mont.prototype.imul = function imul (a, b) {
- if (a.isZero() || b.isZero()) {
- a.words[0] = 0;
- a.length = 1;
- return a;
- }
-
- var t = a.imul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
-
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
-
- return res._forceRed(this);
- };
-
- Mont.prototype.mul = function mul (a, b) {
- if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
-
- var t = a.mul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
-
- return res._forceRed(this);
- };
-
- Mont.prototype.invm = function invm (a) {
- // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
- var res = this.imod(a._invmp(this.m).mul(this.r2));
- return res._forceRed(this);
- };
-})(typeof module === 'undefined' || module, this);
-
-},{}],369:[function(require,module,exports){
+},{"./custom":269}],271:[function(require,module,exports){
'use strict';
var has = Object.prototype.hasOwnProperty
@@ -58596,7 +39620,7 @@ if ('undefined' !== typeof module) {
module.exports = EventEmitter;
}
-},{}],370:[function(require,module,exports){
+},{}],272:[function(require,module,exports){
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
@@ -59121,7 +40145,7 @@ function functionBindPolyfill(context) {
};
}
-},{}],371:[function(require,module,exports){
+},{}],273:[function(require,module,exports){
var Buffer = require('safe-buffer').Buffer
var MD5 = require('md5.js')
@@ -59168,7 +40192,7 @@ function EVP_BytesToKey (password, salt, keyBits, ivLen) {
module.exports = EVP_BytesToKey
-},{"md5.js":1297,"safe-buffer":1593}],372:[function(require,module,exports){
+},{"md5.js":1126,"safe-buffer":1371}],274:[function(require,module,exports){
function getStack(err) {
if(err.stack && err.name && err.message)
@@ -59205,370 +40229,7 @@ var explain = module.exports = function (err, message) {
-},{}],373:[function(require,module,exports){
-'use strict';
-
-var hasOwn = Object.prototype.hasOwnProperty;
-var toStr = Object.prototype.toString;
-var defineProperty = Object.defineProperty;
-var gOPD = Object.getOwnPropertyDescriptor;
-
-var isArray = function isArray(arr) {
- if (typeof Array.isArray === 'function') {
- return Array.isArray(arr);
- }
-
- return toStr.call(arr) === '[object Array]';
-};
-
-var isPlainObject = function isPlainObject(obj) {
- if (!obj || toStr.call(obj) !== '[object Object]') {
- return false;
- }
-
- var hasOwnConstructor = hasOwn.call(obj, 'constructor');
- var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
- // Not own constructor property must be Object
- if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
- return false;
- }
-
- // Own properties are enumerated firstly, so to speed up,
- // if last one is own, then all properties are own.
- var key;
- for (key in obj) { /**/ }
-
- return typeof key === 'undefined' || hasOwn.call(obj, key);
-};
-
-// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target
-var setProperty = function setProperty(target, options) {
- if (defineProperty && options.name === '__proto__') {
- defineProperty(target, options.name, {
- enumerable: true,
- configurable: true,
- value: options.newValue,
- writable: true
- });
- } else {
- target[options.name] = options.newValue;
- }
-};
-
-// Return undefined instead of __proto__ if '__proto__' is not an own property
-var getProperty = function getProperty(obj, name) {
- if (name === '__proto__') {
- if (!hasOwn.call(obj, name)) {
- return void 0;
- } else if (gOPD) {
- // In early versions of node, obj['__proto__'] is buggy when obj has
- // __proto__ as an own property. Object.getOwnPropertyDescriptor() works.
- return gOPD(obj, name).value;
- }
- }
-
- return obj[name];
-};
-
-module.exports = function extend() {
- var options, name, src, copy, copyIsArray, clone;
- var target = arguments[0];
- var i = 1;
- var length = arguments.length;
- var deep = false;
-
- // Handle a deep copy situation
- if (typeof target === 'boolean') {
- deep = target;
- target = arguments[1] || {};
- // skip the boolean and the target
- i = 2;
- }
- if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
- target = {};
- }
-
- for (; i < length; ++i) {
- options = arguments[i];
- // Only deal with non-null/undefined values
- if (options != null) {
- // Extend the base object
- for (name in options) {
- src = getProperty(target, name);
- copy = getProperty(options, name);
-
- // Prevent never-ending loop
- if (target !== copy) {
- // Recurse if we're merging plain objects or arrays
- if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
- if (copyIsArray) {
- copyIsArray = false;
- clone = src && isArray(src) ? src : [];
- } else {
- clone = src && isPlainObject(src) ? src : {};
- }
-
- // Never move original objects, clone them
- setProperty(target, { name: name, newValue: extend(deep, clone, copy) });
-
- // Don't bring in undefined values
- } else if (typeof copy !== 'undefined') {
- setProperty(target, { name: name, newValue: copy });
- }
- }
- }
- }
- }
-
- // Return the modified object
- return target;
-};
-
-},{}],374:[function(require,module,exports){
-(function (process){
-/*
- * extsprintf.js: extended POSIX-style sprintf
- */
-
-var mod_assert = require('assert');
-var mod_util = require('util');
-
-/*
- * Public interface
- */
-exports.sprintf = jsSprintf;
-exports.printf = jsPrintf;
-exports.fprintf = jsFprintf;
-
-/*
- * Stripped down version of s[n]printf(3c). We make a best effort to throw an
- * exception when given a format string we don't understand, rather than
- * ignoring it, so that we won't break existing programs if/when we go implement
- * the rest of this.
- *
- * This implementation currently supports specifying
- * - field alignment ('-' flag),
- * - zero-pad ('0' flag)
- * - always show numeric sign ('+' flag),
- * - field width
- * - conversions for strings, decimal integers, and floats (numbers).
- * - argument size specifiers. These are all accepted but ignored, since
- * Javascript has no notion of the physical size of an argument.
- *
- * Everything else is currently unsupported, most notably precision, unsigned
- * numbers, non-decimal numbers, and characters.
- */
-function jsSprintf(fmt)
-{
- var regex = [
- '([^%]*)', /* normal text */
- '%', /* start of format */
- '([\'\\-+ #0]*?)', /* flags (optional) */
- '([1-9]\\d*)?', /* width (optional) */
- '(\\.([1-9]\\d*))?', /* precision (optional) */
- '[lhjztL]*?', /* length mods (ignored) */
- '([diouxXfFeEgGaAcCsSp%jr])' /* conversion */
- ].join('');
-
- var re = new RegExp(regex);
- var args = Array.prototype.slice.call(arguments, 1);
- var flags, width, precision, conversion;
- var left, pad, sign, arg, match;
- var ret = '';
- var argn = 1;
-
- mod_assert.equal('string', typeof (fmt));
-
- while ((match = re.exec(fmt)) !== null) {
- ret += match[1];
- fmt = fmt.substring(match[0].length);
-
- flags = match[2] || '';
- width = match[3] || 0;
- precision = match[4] || '';
- conversion = match[6];
- left = false;
- sign = false;
- pad = ' ';
-
- if (conversion == '%') {
- ret += '%';
- continue;
- }
-
- if (args.length === 0)
- throw (new Error('too few args to sprintf'));
-
- arg = args.shift();
- argn++;
-
- if (flags.match(/[\' #]/))
- throw (new Error(
- 'unsupported flags: ' + flags));
-
- if (precision.length > 0)
- throw (new Error(
- 'non-zero precision not supported'));
-
- if (flags.match(/-/))
- left = true;
-
- if (flags.match(/0/))
- pad = '0';
-
- if (flags.match(/\+/))
- sign = true;
-
- switch (conversion) {
- case 's':
- if (arg === undefined || arg === null)
- throw (new Error('argument ' + argn +
- ': attempted to print undefined or null ' +
- 'as a string'));
- ret += doPad(pad, width, left, arg.toString());
- break;
-
- case 'd':
- arg = Math.floor(arg);
- /*jsl:fallthru*/
- case 'f':
- sign = sign && arg > 0 ? '+' : '';
- ret += sign + doPad(pad, width, left,
- arg.toString());
- break;
-
- case 'x':
- ret += doPad(pad, width, left, arg.toString(16));
- break;
-
- case 'j': /* non-standard */
- if (width === 0)
- width = 10;
- ret += mod_util.inspect(arg, false, width);
- break;
-
- case 'r': /* non-standard */
- ret += dumpException(arg);
- break;
-
- default:
- throw (new Error('unsupported conversion: ' +
- conversion));
- }
- }
-
- ret += fmt;
- return (ret);
-}
-
-function jsPrintf() {
- var args = Array.prototype.slice.call(arguments);
- args.unshift(process.stdout);
- jsFprintf.apply(null, args);
-}
-
-function jsFprintf(stream) {
- var args = Array.prototype.slice.call(arguments, 1);
- return (stream.write(jsSprintf.apply(this, args)));
-}
-
-function doPad(chr, width, left, str)
-{
- var ret = str;
-
- while (ret.length < width) {
- if (left)
- ret += chr;
- else
- ret = chr + ret;
- }
-
- return (ret);
-}
-
-/*
- * This function dumps long stack traces for exceptions having a cause() method.
- * See node-verror for an example.
- */
-function dumpException(ex)
-{
- var ret;
-
- if (!(ex instanceof Error))
- throw (new Error(jsSprintf('invalid type for %%r: %j', ex)));
-
- /* Note that V8 prepends "ex.stack" with ex.toString(). */
- ret = 'EXCEPTION: ' + ex.constructor.name + ': ' + ex.stack;
-
- if (ex.cause && typeof (ex.cause) === 'function') {
- var cex = ex.cause();
- if (cex) {
- ret += '\nCaused by: ' + dumpException(cex);
- }
- }
-
- return (ret);
-}
-
-}).call(this,require('_process'))
-},{"_process":1438,"assert":78,"util":1776}],375:[function(require,module,exports){
-'use strict';
-
-var isArray = Array.isArray;
-var keyList = Object.keys;
-var hasProp = Object.prototype.hasOwnProperty;
-
-module.exports = function equal(a, b) {
- if (a === b) return true;
-
- if (a && b && typeof a == 'object' && typeof b == 'object') {
- var arrA = isArray(a)
- , arrB = isArray(b)
- , i
- , length
- , key;
-
- if (arrA && arrB) {
- length = a.length;
- if (length != b.length) return false;
- for (i = length; i-- !== 0;)
- if (!equal(a[i], b[i])) return false;
- return true;
- }
-
- if (arrA != arrB) return false;
-
- var dateA = a instanceof Date
- , dateB = b instanceof Date;
- if (dateA != dateB) return false;
- if (dateA && dateB) return a.getTime() == b.getTime();
-
- var regexpA = a instanceof RegExp
- , regexpB = b instanceof RegExp;
- if (regexpA != regexpB) return false;
- if (regexpA && regexpB) return a.toString() == b.toString();
-
- var keys = keyList(a);
- length = keys.length;
-
- if (length !== keyList(b).length)
- return false;
-
- for (i = length; i-- !== 0;)
- if (!hasProp.call(b, keys[i])) return false;
-
- for (i = length; i-- !== 0;) {
- key = keys[i];
- if (!equal(a[key], b[key])) return false;
- }
-
- return true;
- }
-
- return a!==a && b!==b;
-};
-
-},{}],376:[function(require,module,exports){
+},{}],275:[function(require,module,exports){
module.exports = class FixedFIFO {
constructor (hwm) {
if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two')
@@ -59599,7 +40260,7 @@ module.exports = class FixedFIFO {
}
}
-},{}],377:[function(require,module,exports){
+},{}],276:[function(require,module,exports){
const FixedFIFO = require('./fixed-size')
module.exports = class FastFIFO {
@@ -59633,68 +40294,7 @@ module.exports = class FastFIFO {
}
}
-},{"./fixed-size":376}],378:[function(require,module,exports){
-'use strict';
-
-module.exports = function (data, opts) {
- if (!opts) opts = {};
- if (typeof opts === 'function') opts = { cmp: opts };
- var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false;
-
- var cmp = opts.cmp && (function (f) {
- return function (node) {
- return function (a, b) {
- var aobj = { key: a, value: node[a] };
- var bobj = { key: b, value: node[b] };
- return f(aobj, bobj);
- };
- };
- })(opts.cmp);
-
- var seen = [];
- return (function stringify (node) {
- if (node && node.toJSON && typeof node.toJSON === 'function') {
- node = node.toJSON();
- }
-
- if (node === undefined) return;
- if (typeof node == 'number') return isFinite(node) ? '' + node : 'null';
- if (typeof node !== 'object') return JSON.stringify(node);
-
- var i, out;
- if (Array.isArray(node)) {
- out = '[';
- for (i = 0; i < node.length; i++) {
- if (i) out += ',';
- out += stringify(node[i]) || 'null';
- }
- return out + ']';
- }
-
- if (node === null) return 'null';
-
- if (seen.indexOf(node) !== -1) {
- if (cycles) return JSON.stringify('__cycle__');
- throw new TypeError('Converting circular structure to JSON');
- }
-
- var seenIndex = seen.push(node) - 1;
- var keys = Object.keys(node).sort(cmp && cmp(node));
- out = '';
- for (i = 0; i < keys.length; i++) {
- var key = keys[i];
- var value = stringify(node[key]);
-
- if (!value) continue;
- if (out) out += ',';
- out += JSON.stringify(key) + ':' + value;
- }
- seen.splice(seenIndex, 1);
- return '{' + out + '}';
- })(data);
-};
-
-},{}],379:[function(require,module,exports){
+},{"./fixed-size":275}],277:[function(require,module,exports){
/**
* Created by schwarzkopfb on 15/11/17.
*/
@@ -59727,215 +40327,7 @@ function hash(s) {
module.exports = hash
-},{}],380:[function(require,module,exports){
-'use strict';
-
-var isCallable = require('is-callable');
-
-var toStr = Object.prototype.toString;
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-var forEachArray = function forEachArray(array, iterator, receiver) {
- for (var i = 0, len = array.length; i < len; i++) {
- if (hasOwnProperty.call(array, i)) {
- if (receiver == null) {
- iterator(array[i], i, array);
- } else {
- iterator.call(receiver, array[i], i, array);
- }
- }
- }
-};
-
-var forEachString = function forEachString(string, iterator, receiver) {
- for (var i = 0, len = string.length; i < len; i++) {
- // no such thing as a sparse string.
- if (receiver == null) {
- iterator(string.charAt(i), i, string);
- } else {
- iterator.call(receiver, string.charAt(i), i, string);
- }
- }
-};
-
-var forEachObject = function forEachObject(object, iterator, receiver) {
- for (var k in object) {
- if (hasOwnProperty.call(object, k)) {
- if (receiver == null) {
- iterator(object[k], k, object);
- } else {
- iterator.call(receiver, object[k], k, object);
- }
- }
- }
-};
-
-var forEach = function forEach(list, iterator, thisArg) {
- if (!isCallable(iterator)) {
- throw new TypeError('iterator must be a function');
- }
-
- var receiver;
- if (arguments.length >= 3) {
- receiver = thisArg;
- }
-
- if (toStr.call(list) === '[object Array]') {
- forEachArray(list, iterator, receiver);
- } else if (typeof list === 'string') {
- forEachString(list, iterator, receiver);
- } else {
- forEachObject(list, iterator, receiver);
- }
-};
-
-module.exports = forEach;
-
-},{"is-callable":767}],381:[function(require,module,exports){
-module.exports = ForeverAgent
-ForeverAgent.SSL = ForeverAgentSSL
-
-var util = require('util')
- , Agent = require('http').Agent
- , net = require('net')
- , tls = require('tls')
- , AgentSSL = require('https').Agent
-
-function getConnectionName(host, port) {
- var name = ''
- if (typeof host === 'string') {
- name = host + ':' + port
- } else {
- // For node.js v012.0 and iojs-v1.5.1, host is an object. And any existing localAddress is part of the connection name.
- name = host.host + ':' + host.port + ':' + (host.localAddress ? (host.localAddress + ':') : ':')
- }
- return name
-}
-
-function ForeverAgent(options) {
- var self = this
- self.options = options || {}
- self.requests = {}
- self.sockets = {}
- self.freeSockets = {}
- self.maxSockets = self.options.maxSockets || Agent.defaultMaxSockets
- self.minSockets = self.options.minSockets || ForeverAgent.defaultMinSockets
- self.on('free', function(socket, host, port) {
- var name = getConnectionName(host, port)
-
- if (self.requests[name] && self.requests[name].length) {
- self.requests[name].shift().onSocket(socket)
- } else if (self.sockets[name].length < self.minSockets) {
- if (!self.freeSockets[name]) self.freeSockets[name] = []
- self.freeSockets[name].push(socket)
-
- // if an error happens while we don't use the socket anyway, meh, throw the socket away
- var onIdleError = function() {
- socket.destroy()
- }
- socket._onIdleError = onIdleError
- socket.on('error', onIdleError)
- } else {
- // If there are no pending requests just destroy the
- // socket and it will get removed from the pool. This
- // gets us out of timeout issues and allows us to
- // default to Connection:keep-alive.
- socket.destroy()
- }
- })
-
-}
-util.inherits(ForeverAgent, Agent)
-
-ForeverAgent.defaultMinSockets = 5
-
-
-ForeverAgent.prototype.createConnection = net.createConnection
-ForeverAgent.prototype.addRequestNoreuse = Agent.prototype.addRequest
-ForeverAgent.prototype.addRequest = function(req, host, port) {
- var name = getConnectionName(host, port)
-
- if (typeof host !== 'string') {
- var options = host
- port = options.port
- host = options.host
- }
-
- if (this.freeSockets[name] && this.freeSockets[name].length > 0 && !req.useChunkedEncodingByDefault) {
- var idleSocket = this.freeSockets[name].pop()
- idleSocket.removeListener('error', idleSocket._onIdleError)
- delete idleSocket._onIdleError
- req._reusedSocket = true
- req.onSocket(idleSocket)
- } else {
- this.addRequestNoreuse(req, host, port)
- }
-}
-
-ForeverAgent.prototype.removeSocket = function(s, name, host, port) {
- if (this.sockets[name]) {
- var index = this.sockets[name].indexOf(s)
- if (index !== -1) {
- this.sockets[name].splice(index, 1)
- }
- } else if (this.sockets[name] && this.sockets[name].length === 0) {
- // don't leak
- delete this.sockets[name]
- delete this.requests[name]
- }
-
- if (this.freeSockets[name]) {
- var index = this.freeSockets[name].indexOf(s)
- if (index !== -1) {
- this.freeSockets[name].splice(index, 1)
- if (this.freeSockets[name].length === 0) {
- delete this.freeSockets[name]
- }
- }
- }
-
- if (this.requests[name] && this.requests[name].length) {
- // If we have pending requests and a socket gets closed a new one
- // needs to be created to take over in the pool for the one that closed.
- this.createSocket(name, host, port).emit('free')
- }
-}
-
-function ForeverAgentSSL (options) {
- ForeverAgent.call(this, options)
-}
-util.inherits(ForeverAgentSSL, ForeverAgent)
-
-ForeverAgentSSL.prototype.createConnection = createConnectionSSL
-ForeverAgentSSL.prototype.addRequestNoreuse = AgentSSL.prototype.addRequest
-
-function createConnectionSSL (port, host, options) {
- if (typeof port === 'object') {
- options = port;
- } else if (typeof host === 'object') {
- options = host;
- } else if (typeof options === 'object') {
- options = options;
- } else {
- options = {};
- }
-
- if (typeof port === 'number') {
- options.port = port;
- }
-
- if (typeof host === 'string') {
- options.host = host;
- }
-
- return tls.connect(options);
-}
-
-},{"http":1716,"https":446,"net":212,"tls":212,"util":1776}],382:[function(require,module,exports){
-/* eslint-env browser */
-module.exports = typeof self == 'object' ? self.FormData : window.FormData;
-
-},{}],383:[function(require,module,exports){
+},{}],278:[function(require,module,exports){
const EventEmitter = require('events').EventEmitter
const assert = require('assert')
const fsm = require('fsm')
@@ -60014,7 +40406,7 @@ function reach (curr, next, reachable) {
return here[next].length === 1
}
-},{"assert":78,"events":370,"fsm":384}],384:[function(require,module,exports){
+},{"assert":26,"events":272,"fsm":279}],279:[function(require,module,exports){
function each(obj, iter) {
for(var key in obj) {
var value = obj[key]
@@ -60188,68 +40580,7 @@ var combine = exports.combine = function (fsm1, fsm2, start1, start2) {
}
-},{}],385:[function(require,module,exports){
-'use strict';
-
-/* eslint no-invalid-this: 1 */
-
-var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
-var slice = Array.prototype.slice;
-var toStr = Object.prototype.toString;
-var funcType = '[object Function]';
-
-module.exports = function bind(that) {
- var target = this;
- if (typeof target !== 'function' || toStr.call(target) !== funcType) {
- throw new TypeError(ERROR_MESSAGE + target);
- }
- var args = slice.call(arguments, 1);
-
- var bound;
- var binder = function () {
- if (this instanceof bound) {
- var result = target.apply(
- this,
- args.concat(slice.call(arguments))
- );
- if (Object(result) === result) {
- return result;
- }
- return this;
- } else {
- return target.apply(
- that,
- args.concat(slice.call(arguments))
- );
- }
- };
-
- var boundLength = Math.max(0, target.length - args.length);
- var boundArgs = [];
- for (var i = 0; i < boundLength; i++) {
- boundArgs.push('$' + i);
- }
-
- bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
-
- if (target.prototype) {
- var Empty = function Empty() {};
- Empty.prototype = target.prototype;
- bound.prototype = new Empty();
- Empty.prototype = null;
- }
-
- return bound;
-};
-
-},{}],386:[function(require,module,exports){
-'use strict';
-
-var implementation = require('./implementation');
-
-module.exports = Function.prototype.bind || implementation;
-
-},{"./implementation":385}],387:[function(require,module,exports){
+},{}],280:[function(require,module,exports){
// originally pulled out of simple-peer
module.exports = function getBrowserRTC () {
@@ -60266,7 +40597,7 @@ module.exports = function getBrowserRTC () {
return wrtc
}
-},{}],388:[function(require,module,exports){
+},{}],281:[function(require,module,exports){
// If the passed object is an (async) iterable, then get the iterator
// If it's probably an iterator already (i.e. has next function) return it
// else throw
@@ -60285,24 +40616,7 @@ module.exports = function getIterator (obj) {
throw new Error('argument is not an iterator or iterable')
}
-},{}],389:[function(require,module,exports){
-(function (global){
-var win;
-
-if (typeof window !== "undefined") {
- win = window;
-} else if (typeof global !== "undefined") {
- win = global;
-} else if (typeof self !== "undefined"){
- win = self;
-} else {
- win = {};
-}
-
-module.exports = win;
-
-}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],390:[function(require,module,exports){
+},{}],282:[function(require,module,exports){
(function (global){
/* globals self, window, global */
/* eslint no-negated-condition: 0, no-new-func: 0 */
@@ -60320,7 +40634,7 @@ if (typeof self !== 'undefined') {
}
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{}],391:[function(require,module,exports){
+},{}],283:[function(require,module,exports){
'use strict';
var defineProperties = require('define-properties');
@@ -60341,7 +40655,7 @@ defineProperties(getGlobal, {
module.exports = getGlobal;
-},{"./implementation":390,"./polyfill":392,"./shim":393,"define-properties":263}],392:[function(require,module,exports){
+},{"./implementation":282,"./polyfill":284,"./shim":285,"define-properties":218}],284:[function(require,module,exports){
(function (global){
'use strict';
@@ -60355,7 +40669,7 @@ module.exports = function getPolyfill() {
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"./implementation":390}],393:[function(require,module,exports){
+},{"./implementation":282}],285:[function(require,module,exports){
'use strict';
var define = require('define-properties');
@@ -60379,7 +40693,7 @@ module.exports = function shimGlobal() {
return polyfill;
};
-},{"./polyfill":392,"define-properties":263}],394:[function(require,module,exports){
+},{"./polyfill":284,"define-properties":218}],286:[function(require,module,exports){
'use strict'
const SparseArray = require('sparse-array')
@@ -60625,7 +40939,7 @@ async function asyncTransformBucket (bucket, asyncMap, asyncReduce) {
module.exports = Bucket
-},{"./consumable-hash":396,"sparse-array":1672}],395:[function(require,module,exports){
+},{"./consumable-hash":288,"sparse-array":1439}],287:[function(require,module,exports){
'use strict'
const START_MASKS = [
@@ -60709,7 +41023,7 @@ function maskFor (start, length) {
return START_MASKS[start] & STOP_MASKS[Math.min(length + start - 1, 7)]
}
-},{}],396:[function(require,module,exports){
+},{}],288:[function(require,module,exports){
(function (Buffer){
'use strict'
@@ -60794,7 +41108,7 @@ class InfiniteHash {
}
}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":766,"./consumable-buffer":395}],397:[function(require,module,exports){
+},{"../../is-buffer/index.js":608,"./consumable-buffer":287}],289:[function(require,module,exports){
'use strict'
const Bucket = require('./bucket')
@@ -60805,764 +41119,7 @@ module.exports = function createHAMT (options) {
module.exports.isBucket = Bucket.isBucket
-},{"./bucket":394}],398:[function(require,module,exports){
-module.exports={
- "$id": "afterRequest.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "optional": true,
- "required": [
- "lastAccess",
- "eTag",
- "hitCount"
- ],
- "properties": {
- "expires": {
- "type": "string",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
- },
- "lastAccess": {
- "type": "string",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
- },
- "eTag": {
- "type": "string"
- },
- "hitCount": {
- "type": "integer"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],399:[function(require,module,exports){
-module.exports={
- "$id": "beforeRequest.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "optional": true,
- "required": [
- "lastAccess",
- "eTag",
- "hitCount"
- ],
- "properties": {
- "expires": {
- "type": "string",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
- },
- "lastAccess": {
- "type": "string",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))?"
- },
- "eTag": {
- "type": "string"
- },
- "hitCount": {
- "type": "integer"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],400:[function(require,module,exports){
-module.exports={
- "$id": "browser.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "name",
- "version"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "version": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],401:[function(require,module,exports){
-module.exports={
- "$id": "cache.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "properties": {
- "beforeRequest": {
- "oneOf": [
- { "type": "null" },
- { "$ref": "beforeRequest.json#" }
- ]
- },
- "afterRequest": {
- "oneOf": [
- { "type": "null" },
- { "$ref": "afterRequest.json#" }
- ]
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],402:[function(require,module,exports){
-module.exports={
- "$id": "content.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "size",
- "mimeType"
- ],
- "properties": {
- "size": {
- "type": "integer"
- },
- "compression": {
- "type": "integer"
- },
- "mimeType": {
- "type": "string"
- },
- "text": {
- "type": "string"
- },
- "encoding": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],403:[function(require,module,exports){
-module.exports={
- "$id": "cookie.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "name",
- "value"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "value": {
- "type": "string"
- },
- "path": {
- "type": "string"
- },
- "domain": {
- "type": "string"
- },
- "expires": {
- "type": ["string", "null"],
- "format": "date-time"
- },
- "httpOnly": {
- "type": "boolean"
- },
- "secure": {
- "type": "boolean"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],404:[function(require,module,exports){
-module.exports={
- "$id": "creator.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "name",
- "version"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "version": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],405:[function(require,module,exports){
-module.exports={
- "$id": "entry.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "optional": true,
- "required": [
- "startedDateTime",
- "time",
- "request",
- "response",
- "cache",
- "timings"
- ],
- "properties": {
- "pageref": {
- "type": "string"
- },
- "startedDateTime": {
- "type": "string",
- "format": "date-time",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
- },
- "time": {
- "type": "number",
- "min": 0
- },
- "request": {
- "$ref": "request.json#"
- },
- "response": {
- "$ref": "response.json#"
- },
- "cache": {
- "$ref": "cache.json#"
- },
- "timings": {
- "$ref": "timings.json#"
- },
- "serverIPAddress": {
- "type": "string",
- "oneOf": [
- { "format": "ipv4" },
- { "format": "ipv6" }
- ]
- },
- "connection": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],406:[function(require,module,exports){
-module.exports={
- "$id": "har.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "log"
- ],
- "properties": {
- "log": {
- "$ref": "log.json#"
- }
- }
-}
-
-},{}],407:[function(require,module,exports){
-module.exports={
- "$id": "header.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "name",
- "value"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "value": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],408:[function(require,module,exports){
-'use strict'
-
-module.exports = {
- afterRequest: require('./afterRequest.json'),
- beforeRequest: require('./beforeRequest.json'),
- browser: require('./browser.json'),
- cache: require('./cache.json'),
- content: require('./content.json'),
- cookie: require('./cookie.json'),
- creator: require('./creator.json'),
- entry: require('./entry.json'),
- har: require('./har.json'),
- header: require('./header.json'),
- log: require('./log.json'),
- page: require('./page.json'),
- pageTimings: require('./pageTimings.json'),
- postData: require('./postData.json'),
- query: require('./query.json'),
- request: require('./request.json'),
- response: require('./response.json'),
- timings: require('./timings.json')
-}
-
-},{"./afterRequest.json":398,"./beforeRequest.json":399,"./browser.json":400,"./cache.json":401,"./content.json":402,"./cookie.json":403,"./creator.json":404,"./entry.json":405,"./har.json":406,"./header.json":407,"./log.json":409,"./page.json":410,"./pageTimings.json":411,"./postData.json":412,"./query.json":413,"./request.json":414,"./response.json":415,"./timings.json":416}],409:[function(require,module,exports){
-module.exports={
- "$id": "log.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "version",
- "creator",
- "entries"
- ],
- "properties": {
- "version": {
- "type": "string"
- },
- "creator": {
- "$ref": "creator.json#"
- },
- "browser": {
- "$ref": "browser.json#"
- },
- "pages": {
- "type": "array",
- "items": {
- "$ref": "page.json#"
- }
- },
- "entries": {
- "type": "array",
- "items": {
- "$ref": "entry.json#"
- }
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],410:[function(require,module,exports){
-module.exports={
- "$id": "page.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "optional": true,
- "required": [
- "startedDateTime",
- "id",
- "title",
- "pageTimings"
- ],
- "properties": {
- "startedDateTime": {
- "type": "string",
- "format": "date-time",
- "pattern": "^(\\d{4})(-)?(\\d\\d)(-)?(\\d\\d)(T)?(\\d\\d)(:)?(\\d\\d)(:)?(\\d\\d)(\\.\\d+)?(Z|([+-])(\\d\\d)(:)?(\\d\\d))"
- },
- "id": {
- "type": "string",
- "unique": true
- },
- "title": {
- "type": "string"
- },
- "pageTimings": {
- "$ref": "pageTimings.json#"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],411:[function(require,module,exports){
-module.exports={
- "$id": "pageTimings.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "properties": {
- "onContentLoad": {
- "type": "number",
- "min": -1
- },
- "onLoad": {
- "type": "number",
- "min": -1
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],412:[function(require,module,exports){
-module.exports={
- "$id": "postData.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "optional": true,
- "required": [
- "mimeType"
- ],
- "properties": {
- "mimeType": {
- "type": "string"
- },
- "text": {
- "type": "string"
- },
- "params": {
- "type": "array",
- "required": [
- "name"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "value": {
- "type": "string"
- },
- "fileName": {
- "type": "string"
- },
- "contentType": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],413:[function(require,module,exports){
-module.exports={
- "$id": "query.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "name",
- "value"
- ],
- "properties": {
- "name": {
- "type": "string"
- },
- "value": {
- "type": "string"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],414:[function(require,module,exports){
-module.exports={
- "$id": "request.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "method",
- "url",
- "httpVersion",
- "cookies",
- "headers",
- "queryString",
- "headersSize",
- "bodySize"
- ],
- "properties": {
- "method": {
- "type": "string"
- },
- "url": {
- "type": "string",
- "format": "uri"
- },
- "httpVersion": {
- "type": "string"
- },
- "cookies": {
- "type": "array",
- "items": {
- "$ref": "cookie.json#"
- }
- },
- "headers": {
- "type": "array",
- "items": {
- "$ref": "header.json#"
- }
- },
- "queryString": {
- "type": "array",
- "items": {
- "$ref": "query.json#"
- }
- },
- "postData": {
- "$ref": "postData.json#"
- },
- "headersSize": {
- "type": "integer"
- },
- "bodySize": {
- "type": "integer"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],415:[function(require,module,exports){
-module.exports={
- "$id": "response.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "type": "object",
- "required": [
- "status",
- "statusText",
- "httpVersion",
- "cookies",
- "headers",
- "content",
- "redirectURL",
- "headersSize",
- "bodySize"
- ],
- "properties": {
- "status": {
- "type": "integer"
- },
- "statusText": {
- "type": "string"
- },
- "httpVersion": {
- "type": "string"
- },
- "cookies": {
- "type": "array",
- "items": {
- "$ref": "cookie.json#"
- }
- },
- "headers": {
- "type": "array",
- "items": {
- "$ref": "header.json#"
- }
- },
- "content": {
- "$ref": "content.json#"
- },
- "redirectURL": {
- "type": "string"
- },
- "headersSize": {
- "type": "integer"
- },
- "bodySize": {
- "type": "integer"
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],416:[function(require,module,exports){
-module.exports={
- "$id": "timings.json#",
- "$schema": "http://json-schema.org/draft-06/schema#",
- "required": [
- "send",
- "wait",
- "receive"
- ],
- "properties": {
- "dns": {
- "type": "number",
- "min": -1
- },
- "connect": {
- "type": "number",
- "min": -1
- },
- "blocked": {
- "type": "number",
- "min": -1
- },
- "send": {
- "type": "number",
- "min": -1
- },
- "wait": {
- "type": "number",
- "min": -1
- },
- "receive": {
- "type": "number",
- "min": -1
- },
- "ssl": {
- "type": "number",
- "min": -1
- },
- "comment": {
- "type": "string"
- }
- }
-}
-
-},{}],417:[function(require,module,exports){
-function HARError (errors) {
- var message = 'validation failed'
-
- this.name = 'HARError'
- this.message = message
- this.errors = errors
-
- if (typeof Error.captureStackTrace === 'function') {
- Error.captureStackTrace(this, this.constructor)
- } else {
- this.stack = (new Error(message)).stack
- }
-}
-
-HARError.prototype = Error.prototype
-
-module.exports = HARError
-
-},{}],418:[function(require,module,exports){
-var Ajv = require('ajv')
-var HARError = require('./error')
-var schemas = require('har-schema')
-
-var ajv
-
-function createAjvInstance () {
- var ajv = new Ajv({
- allErrors: true
- })
- ajv.addMetaSchema(require('ajv/lib/refs/json-schema-draft-06.json'))
- ajv.addSchema(schemas)
-
- return ajv
-}
-
-function validate (name, data) {
- data = data || {}
-
- // validator config
- ajv = ajv || createAjvInstance()
-
- var validate = ajv.getSchema(name + '.json')
-
- return new Promise(function (resolve, reject) {
- var valid = validate(data)
-
- !valid ? reject(new HARError(validate.errors)) : resolve(data)
- })
-}
-
-exports.afterRequest = function (data) {
- return validate('afterRequest', data)
-}
-
-exports.beforeRequest = function (data) {
- return validate('beforeRequest', data)
-}
-
-exports.browser = function (data) {
- return validate('browser', data)
-}
-
-exports.cache = function (data) {
- return validate('cache', data)
-}
-
-exports.content = function (data) {
- return validate('content', data)
-}
-
-exports.cookie = function (data) {
- return validate('cookie', data)
-}
-
-exports.creator = function (data) {
- return validate('creator', data)
-}
-
-exports.entry = function (data) {
- return validate('entry', data)
-}
-
-exports.har = function (data) {
- return validate('har', data)
-}
-
-exports.header = function (data) {
- return validate('header', data)
-}
-
-exports.log = function (data) {
- return validate('log', data)
-}
-
-exports.page = function (data) {
- return validate('page', data)
-}
-
-exports.pageTimings = function (data) {
- return validate('pageTimings', data)
-}
-
-exports.postData = function (data) {
- return validate('postData', data)
-}
-
-exports.query = function (data) {
- return validate('query', data)
-}
-
-exports.request = function (data) {
- return validate('request', data)
-}
-
-exports.response = function (data) {
- return validate('response', data)
-}
-
-exports.timings = function (data) {
- return validate('timings', data)
-}
-
-},{"./error":417,"ajv":8,"ajv/lib/refs/json-schema-draft-06.json":49,"har-schema":408}],419:[function(require,module,exports){
+},{"./bucket":286}],290:[function(require,module,exports){
(function (Buffer){
/* global Blob File */
@@ -61630,14 +41187,14 @@ function hasBinary (obj) {
}
}).call(this,require("buffer").Buffer)
-},{"buffer":217,"isarray":420}],420:[function(require,module,exports){
+},{"buffer":181,"isarray":291}],291:[function(require,module,exports){
var toString = {}.toString;
module.exports = Array.isArray || function (arr) {
return toString.call(arr) == '[object Array]';
};
-},{}],421:[function(require,module,exports){
+},{}],292:[function(require,module,exports){
/**
* Module exports.
@@ -61656,14 +41213,7 @@ try {
module.exports = false;
}
-},{}],422:[function(require,module,exports){
-'use strict';
-
-var bind = require('function-bind');
-
-module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty);
-
-},{"function-bind":386}],423:[function(require,module,exports){
+},{}],293:[function(require,module,exports){
'use strict'
var Buffer = require('safe-buffer').Buffer
var Transform = require('stream').Transform
@@ -61760,7 +41310,7 @@ HashBase.prototype._digest = function () {
module.exports = HashBase
-},{"inherits":453,"safe-buffer":1593,"stream":1715}],424:[function(require,module,exports){
+},{"inherits":317,"safe-buffer":1371,"stream":1459}],294:[function(require,module,exports){
var hash = exports;
hash.utils = require('./hash/utils');
@@ -61777,7 +41327,7 @@ hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;
-},{"./hash/common":425,"./hash/hmac":426,"./hash/ripemd":427,"./hash/sha":428,"./hash/utils":435}],425:[function(require,module,exports){
+},{"./hash/common":295,"./hash/hmac":296,"./hash/ripemd":297,"./hash/sha":298,"./hash/utils":305}],295:[function(require,module,exports){
'use strict';
var utils = require('./utils');
@@ -61871,7 +41421,7 @@ BlockHash.prototype._pad = function pad() {
return res;
};
-},{"./utils":435,"minimalistic-assert":1303}],426:[function(require,module,exports){
+},{"./utils":305,"minimalistic-assert":1129}],296:[function(require,module,exports){
'use strict';
var utils = require('./utils');
@@ -61920,7 +41470,7 @@ Hmac.prototype.digest = function digest(enc) {
return this.outer.digest(enc);
};
-},{"./utils":435,"minimalistic-assert":1303}],427:[function(require,module,exports){
+},{"./utils":305,"minimalistic-assert":1129}],297:[function(require,module,exports){
'use strict';
var utils = require('./utils');
@@ -62068,7 +41618,7 @@ var sh = [
8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
];
-},{"./common":425,"./utils":435}],428:[function(require,module,exports){
+},{"./common":295,"./utils":305}],298:[function(require,module,exports){
'use strict';
exports.sha1 = require('./sha/1');
@@ -62077,7 +41627,7 @@ exports.sha256 = require('./sha/256');
exports.sha384 = require('./sha/384');
exports.sha512 = require('./sha/512');
-},{"./sha/1":429,"./sha/224":430,"./sha/256":431,"./sha/384":432,"./sha/512":433}],429:[function(require,module,exports){
+},{"./sha/1":299,"./sha/224":300,"./sha/256":301,"./sha/384":302,"./sha/512":303}],299:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62153,7 +41703,7 @@ SHA1.prototype._digest = function digest(enc) {
return utils.split32(this.h, 'big');
};
-},{"../common":425,"../utils":435,"./common":434}],430:[function(require,module,exports){
+},{"../common":295,"../utils":305,"./common":304}],300:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62185,7 +41735,7 @@ SHA224.prototype._digest = function digest(enc) {
};
-},{"../utils":435,"./256":431}],431:[function(require,module,exports){
+},{"../utils":305,"./256":301}],301:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62292,7 +41842,7 @@ SHA256.prototype._digest = function digest(enc) {
return utils.split32(this.h, 'big');
};
-},{"../common":425,"../utils":435,"./common":434,"minimalistic-assert":1303}],432:[function(require,module,exports){
+},{"../common":295,"../utils":305,"./common":304,"minimalistic-assert":1129}],302:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62329,7 +41879,7 @@ SHA384.prototype._digest = function digest(enc) {
return utils.split32(this.h.slice(0, 12), 'big');
};
-},{"../utils":435,"./512":433}],433:[function(require,module,exports){
+},{"../utils":305,"./512":303}],303:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62661,7 +42211,7 @@ function g1_512_lo(xh, xl) {
return r;
}
-},{"../common":425,"../utils":435,"minimalistic-assert":1303}],434:[function(require,module,exports){
+},{"../common":295,"../utils":305,"minimalistic-assert":1129}],304:[function(require,module,exports){
'use strict';
var utils = require('../utils');
@@ -62712,7 +42262,7 @@ function g1_256(x) {
}
exports.g1_256 = g1_256;
-},{"../utils":435}],435:[function(require,module,exports){
+},{"../utils":305}],305:[function(require,module,exports){
'use strict';
var assert = require('minimalistic-assert');
@@ -62992,7 +42542,7 @@ function shr64_lo(ah, al, num) {
}
exports.shr64_lo = shr64_lo;
-},{"inherits":453,"minimalistic-assert":1303}],436:[function(require,module,exports){
+},{"inherits":317,"minimalistic-assert":1129}],306:[function(require,module,exports){
module.exports = function (max) {
if (!max) throw Error('hashlru must have a max value, of type number, greater than 0')
@@ -63045,10 +42595,10 @@ module.exports = function (max) {
-},{}],437:[function(require,module,exports){
+},{}],307:[function(require,module,exports){
module.exports = require('./lib/heap');
-},{"./lib/heap":438}],438:[function(require,module,exports){
+},{"./lib/heap":308}],308:[function(require,module,exports){
// Generated by CoffeeScript 1.8.0
(function() {
var Heap, defaultCmp, floor, heapify, heappop, heappush, heappushpop, heapreplace, insort, min, nlargest, nsmallest, updateItem, _siftdown, _siftup;
@@ -63073,9 +42623,9 @@ module.exports = require('./lib/heap');
/*
Insert item x in list a, and keep it sorted assuming a is sorted.
-
+
If x is already in a, insert it to the right of the rightmost x.
-
+
Optional args lo (default 0) and hi (default a.length) bound the slice
of a to be searched.
*/
@@ -63142,7 +42692,7 @@ module.exports = require('./lib/heap');
/*
Pop and return the current smallest value, and add the new item.
-
+
This is more efficient than heappop() followed by heappush(), and can be
more appropriate when using a fixed size heap. Note that the value
returned may be larger than item! That constrains reasonable use of
@@ -63425,7 +42975,7 @@ module.exports = require('./lib/heap');
}).call(this);
-},{}],439:[function(require,module,exports){
+},{}],309:[function(require,module,exports){
(function (process,global){
/*
* [hi-base32]{@link https://github.com/emn178/hi-base32}
@@ -63880,7 +43430,7 @@ module.exports = require('./lib/heap');
})();
}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
-},{"_process":1438}],440:[function(require,module,exports){
+},{"_process":1258}],310:[function(require,module,exports){
'use strict';
var hash = require('hash.js');
@@ -63995,966 +43545,7 @@ HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
return utils.encode(res, enc);
};
-},{"hash.js":424,"minimalistic-assert":1303,"minimalistic-crypto-utils":1304}],441:[function(require,module,exports){
-// Copyright 2015 Joyent, Inc.
-
-var parser = require('./parser');
-var signer = require('./signer');
-var verify = require('./verify');
-var utils = require('./utils');
-
-
-
-///--- API
-
-module.exports = {
-
- parse: parser.parseRequest,
- parseRequest: parser.parseRequest,
-
- sign: signer.signRequest,
- signRequest: signer.signRequest,
- createSigner: signer.createSigner,
- isSigner: signer.isSigner,
-
- sshKeyToPEM: utils.sshKeyToPEM,
- sshKeyFingerprint: utils.fingerprint,
- pemToRsaSSHKey: utils.pemToRsaSSHKey,
-
- verify: verify.verifySignature,
- verifySignature: verify.verifySignature,
- verifyHMAC: verify.verifyHMAC
-};
-
-},{"./parser":442,"./signer":443,"./utils":444,"./verify":445}],442:[function(require,module,exports){
-// Copyright 2012 Joyent, Inc. All rights reserved.
-
-var assert = require('assert-plus');
-var util = require('util');
-var utils = require('./utils');
-
-
-
-///--- Globals
-
-var HASH_ALGOS = utils.HASH_ALGOS;
-var PK_ALGOS = utils.PK_ALGOS;
-var HttpSignatureError = utils.HttpSignatureError;
-var InvalidAlgorithmError = utils.InvalidAlgorithmError;
-var validateAlgorithm = utils.validateAlgorithm;
-
-var State = {
- New: 0,
- Params: 1
-};
-
-var ParamsState = {
- Name: 0,
- Quote: 1,
- Value: 2,
- Comma: 3
-};
-
-
-///--- Specific Errors
-
-
-function ExpiredRequestError(message) {
- HttpSignatureError.call(this, message, ExpiredRequestError);
-}
-util.inherits(ExpiredRequestError, HttpSignatureError);
-
-
-function InvalidHeaderError(message) {
- HttpSignatureError.call(this, message, InvalidHeaderError);
-}
-util.inherits(InvalidHeaderError, HttpSignatureError);
-
-
-function InvalidParamsError(message) {
- HttpSignatureError.call(this, message, InvalidParamsError);
-}
-util.inherits(InvalidParamsError, HttpSignatureError);
-
-
-function MissingHeaderError(message) {
- HttpSignatureError.call(this, message, MissingHeaderError);
-}
-util.inherits(MissingHeaderError, HttpSignatureError);
-
-function StrictParsingError(message) {
- HttpSignatureError.call(this, message, StrictParsingError);
-}
-util.inherits(StrictParsingError, HttpSignatureError);
-
-///--- Exported API
-
-module.exports = {
-
- /**
- * Parses the 'Authorization' header out of an http.ServerRequest object.
- *
- * Note that this API will fully validate the Authorization header, and throw
- * on any error. It will not however check the signature, or the keyId format
- * as those are specific to your environment. You can use the options object
- * to pass in extra constraints.
- *
- * As a response object you can expect this:
- *
- * {
- * "scheme": "Signature",
- * "params": {
- * "keyId": "foo",
- * "algorithm": "rsa-sha256",
- * "headers": [
- * "date" or "x-date",
- * "digest"
- * ],
- * "signature": "base64"
- * },
- * "signingString": "ready to be passed to crypto.verify()"
- * }
- *
- * @param {Object} request an http.ServerRequest.
- * @param {Object} options an optional options object with:
- * - clockSkew: allowed clock skew in seconds (default 300).
- * - headers: required header names (def: date or x-date)
- * - algorithms: algorithms to support (default: all).
- * - strict: should enforce latest spec parsing
- * (default: false).
- * @return {Object} parsed out object (see above).
- * @throws {TypeError} on invalid input.
- * @throws {InvalidHeaderError} on an invalid Authorization header error.
- * @throws {InvalidParamsError} if the params in the scheme are invalid.
- * @throws {MissingHeaderError} if the params indicate a header not present,
- * either in the request headers from the params,
- * or not in the params from a required header
- * in options.
- * @throws {StrictParsingError} if old attributes are used in strict parsing
- * mode.
- * @throws {ExpiredRequestError} if the value of date or x-date exceeds skew.
- */
- parseRequest: function parseRequest(request, options) {
- assert.object(request, 'request');
- assert.object(request.headers, 'request.headers');
- if (options === undefined) {
- options = {};
- }
- if (options.headers === undefined) {
- options.headers = [request.headers['x-date'] ? 'x-date' : 'date'];
- }
- assert.object(options, 'options');
- assert.arrayOfString(options.headers, 'options.headers');
- assert.optionalFinite(options.clockSkew, 'options.clockSkew');
-
- var authzHeaderName = options.authorizationHeaderName || 'authorization';
-
- if (!request.headers[authzHeaderName]) {
- throw new MissingHeaderError('no ' + authzHeaderName + ' header ' +
- 'present in the request');
- }
-
- options.clockSkew = options.clockSkew || 300;
-
-
- var i = 0;
- var state = State.New;
- var substate = ParamsState.Name;
- var tmpName = '';
- var tmpValue = '';
-
- var parsed = {
- scheme: '',
- params: {},
- signingString: ''
- };
-
- var authz = request.headers[authzHeaderName];
- for (i = 0; i < authz.length; i++) {
- var c = authz.charAt(i);
-
- switch (Number(state)) {
-
- case State.New:
- if (c !== ' ') parsed.scheme += c;
- else state = State.Params;
- break;
-
- case State.Params:
- switch (Number(substate)) {
-
- case ParamsState.Name:
- var code = c.charCodeAt(0);
- // restricted name of A-Z / a-z
- if ((code >= 0x41 && code <= 0x5a) || // A-Z
- (code >= 0x61 && code <= 0x7a)) { // a-z
- tmpName += c;
- } else if (c === '=') {
- if (tmpName.length === 0)
- throw new InvalidHeaderError('bad param format');
- substate = ParamsState.Quote;
- } else {
- throw new InvalidHeaderError('bad param format');
- }
- break;
-
- case ParamsState.Quote:
- if (c === '"') {
- tmpValue = '';
- substate = ParamsState.Value;
- } else {
- throw new InvalidHeaderError('bad param format');
- }
- break;
-
- case ParamsState.Value:
- if (c === '"') {
- parsed.params[tmpName] = tmpValue;
- substate = ParamsState.Comma;
- } else {
- tmpValue += c;
- }
- break;
-
- case ParamsState.Comma:
- if (c === ',') {
- tmpName = '';
- substate = ParamsState.Name;
- } else {
- throw new InvalidHeaderError('bad param format');
- }
- break;
-
- default:
- throw new Error('Invalid substate');
- }
- break;
-
- default:
- throw new Error('Invalid substate');
- }
-
- }
-
- if (!parsed.params.headers || parsed.params.headers === '') {
- if (request.headers['x-date']) {
- parsed.params.headers = ['x-date'];
- } else {
- parsed.params.headers = ['date'];
- }
- } else {
- parsed.params.headers = parsed.params.headers.split(' ');
- }
-
- // Minimally validate the parsed object
- if (!parsed.scheme || parsed.scheme !== 'Signature')
- throw new InvalidHeaderError('scheme was not "Signature"');
-
- if (!parsed.params.keyId)
- throw new InvalidHeaderError('keyId was not specified');
-
- if (!parsed.params.algorithm)
- throw new InvalidHeaderError('algorithm was not specified');
-
- if (!parsed.params.signature)
- throw new InvalidHeaderError('signature was not specified');
-
- // Check the algorithm against the official list
- parsed.params.algorithm = parsed.params.algorithm.toLowerCase();
- try {
- validateAlgorithm(parsed.params.algorithm);
- } catch (e) {
- if (e instanceof InvalidAlgorithmError)
- throw (new InvalidParamsError(parsed.params.algorithm + ' is not ' +
- 'supported'));
- else
- throw (e);
- }
-
- // Build the signingString
- for (i = 0; i < parsed.params.headers.length; i++) {
- var h = parsed.params.headers[i].toLowerCase();
- parsed.params.headers[i] = h;
-
- if (h === 'request-line') {
- if (!options.strict) {
- /*
- * We allow headers from the older spec drafts if strict parsing isn't
- * specified in options.
- */
- parsed.signingString +=
- request.method + ' ' + request.url + ' HTTP/' + request.httpVersion;
- } else {
- /* Strict parsing doesn't allow older draft headers. */
- throw (new StrictParsingError('request-line is not a valid header ' +
- 'with strict parsing enabled.'));
- }
- } else if (h === '(request-target)') {
- parsed.signingString +=
- '(request-target): ' + request.method.toLowerCase() + ' ' +
- request.url;
- } else {
- var value = request.headers[h];
- if (value === undefined)
- throw new MissingHeaderError(h + ' was not in the request');
- parsed.signingString += h + ': ' + value;
- }
-
- if ((i + 1) < parsed.params.headers.length)
- parsed.signingString += '\n';
- }
-
- // Check against the constraints
- var date;
- if (request.headers.date || request.headers['x-date']) {
- if (request.headers['x-date']) {
- date = new Date(request.headers['x-date']);
- } else {
- date = new Date(request.headers.date);
- }
- var now = new Date();
- var skew = Math.abs(now.getTime() - date.getTime());
-
- if (skew > options.clockSkew * 1000) {
- throw new ExpiredRequestError('clock skew of ' +
- (skew / 1000) +
- 's was greater than ' +
- options.clockSkew + 's');
- }
- }
-
- options.headers.forEach(function (hdr) {
- // Remember that we already checked any headers in the params
- // were in the request, so if this passes we're good.
- if (parsed.params.headers.indexOf(hdr.toLowerCase()) < 0)
- throw new MissingHeaderError(hdr + ' was not a signed header');
- });
-
- if (options.algorithms) {
- if (options.algorithms.indexOf(parsed.params.algorithm) === -1)
- throw new InvalidParamsError(parsed.params.algorithm +
- ' is not a supported algorithm');
- }
-
- parsed.algorithm = parsed.params.algorithm.toUpperCase();
- parsed.keyId = parsed.params.keyId;
- return parsed;
- }
-
-};
-
-},{"./utils":444,"assert-plus":77,"util":1776}],443:[function(require,module,exports){
-(function (Buffer){
-// Copyright 2012 Joyent, Inc. All rights reserved.
-
-var assert = require('assert-plus');
-var crypto = require('crypto');
-var http = require('http');
-var util = require('util');
-var sshpk = require('sshpk');
-var jsprim = require('jsprim');
-var utils = require('./utils');
-
-var sprintf = require('util').format;
-
-var HASH_ALGOS = utils.HASH_ALGOS;
-var PK_ALGOS = utils.PK_ALGOS;
-var InvalidAlgorithmError = utils.InvalidAlgorithmError;
-var HttpSignatureError = utils.HttpSignatureError;
-var validateAlgorithm = utils.validateAlgorithm;
-
-///--- Globals
-
-var AUTHZ_FMT =
- 'Signature keyId="%s",algorithm="%s",headers="%s",signature="%s"';
-
-///--- Specific Errors
-
-function MissingHeaderError(message) {
- HttpSignatureError.call(this, message, MissingHeaderError);
-}
-util.inherits(MissingHeaderError, HttpSignatureError);
-
-function StrictParsingError(message) {
- HttpSignatureError.call(this, message, StrictParsingError);
-}
-util.inherits(StrictParsingError, HttpSignatureError);
-
-/* See createSigner() */
-function RequestSigner(options) {
- assert.object(options, 'options');
-
- var alg = [];
- if (options.algorithm !== undefined) {
- assert.string(options.algorithm, 'options.algorithm');
- alg = validateAlgorithm(options.algorithm);
- }
- this.rs_alg = alg;
-
- /*
- * RequestSigners come in two varieties: ones with an rs_signFunc, and ones
- * with an rs_signer.
- *
- * rs_signFunc-based RequestSigners have to build up their entire signing
- * string within the rs_lines array and give it to rs_signFunc as a single
- * concat'd blob. rs_signer-based RequestSigners can add a line at a time to
- * their signing state by using rs_signer.update(), thus only needing to
- * buffer the hash function state and one line at a time.
- */
- if (options.sign !== undefined) {
- assert.func(options.sign, 'options.sign');
- this.rs_signFunc = options.sign;
-
- } else if (alg[0] === 'hmac' && options.key !== undefined) {
- assert.string(options.keyId, 'options.keyId');
- this.rs_keyId = options.keyId;
-
- if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
- throw (new TypeError('options.key for HMAC must be a string or Buffer'));
-
- /*
- * Make an rs_signer for HMACs, not a rs_signFunc -- HMACs digest their
- * data in chunks rather than requiring it all to be given in one go
- * at the end, so they are more similar to signers than signFuncs.
- */
- this.rs_signer = crypto.createHmac(alg[1].toUpperCase(), options.key);
- this.rs_signer.sign = function () {
- var digest = this.digest('base64');
- return ({
- hashAlgorithm: alg[1],
- toString: function () { return (digest); }
- });
- };
-
- } else if (options.key !== undefined) {
- var key = options.key;
- if (typeof (key) === 'string' || Buffer.isBuffer(key))
- key = sshpk.parsePrivateKey(key);
-
- assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
- 'options.key must be a sshpk.PrivateKey');
- this.rs_key = key;
-
- assert.string(options.keyId, 'options.keyId');
- this.rs_keyId = options.keyId;
-
- if (!PK_ALGOS[key.type]) {
- throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
- 'keys are not supported'));
- }
-
- if (alg[0] !== undefined && key.type !== alg[0]) {
- throw (new InvalidAlgorithmError('options.key must be a ' +
- alg[0].toUpperCase() + ' key, was given a ' +
- key.type.toUpperCase() + ' key instead'));
- }
-
- this.rs_signer = key.createSign(alg[1]);
-
- } else {
- throw (new TypeError('options.sign (func) or options.key is required'));
- }
-
- this.rs_headers = [];
- this.rs_lines = [];
-}
-
-/**
- * Adds a header to be signed, with its value, into this signer.
- *
- * @param {String} header
- * @param {String} value
- * @return {String} value written
- */
-RequestSigner.prototype.writeHeader = function (header, value) {
- assert.string(header, 'header');
- header = header.toLowerCase();
- assert.string(value, 'value');
-
- this.rs_headers.push(header);
-
- if (this.rs_signFunc) {
- this.rs_lines.push(header + ': ' + value);
-
- } else {
- var line = header + ': ' + value;
- if (this.rs_headers.length > 0)
- line = '\n' + line;
- this.rs_signer.update(line);
- }
-
- return (value);
-};
-
-/**
- * Adds a default Date header, returning its value.
- *
- * @return {String}
- */
-RequestSigner.prototype.writeDateHeader = function () {
- return (this.writeHeader('date', jsprim.rfc1123(new Date())));
-};
-
-/**
- * Adds the request target line to be signed.
- *
- * @param {String} method, HTTP method (e.g. 'get', 'post', 'put')
- * @param {String} path
- */
-RequestSigner.prototype.writeTarget = function (method, path) {
- assert.string(method, 'method');
- assert.string(path, 'path');
- method = method.toLowerCase();
- this.writeHeader('(request-target)', method + ' ' + path);
-};
-
-/**
- * Calculate the value for the Authorization header on this request
- * asynchronously.
- *
- * @param {Func} callback (err, authz)
- */
-RequestSigner.prototype.sign = function (cb) {
- assert.func(cb, 'callback');
-
- if (this.rs_headers.length < 1)
- throw (new Error('At least one header must be signed'));
-
- var alg, authz;
- if (this.rs_signFunc) {
- var data = this.rs_lines.join('\n');
- var self = this;
- this.rs_signFunc(data, function (err, sig) {
- if (err) {
- cb(err);
- return;
- }
- try {
- assert.object(sig, 'signature');
- assert.string(sig.keyId, 'signature.keyId');
- assert.string(sig.algorithm, 'signature.algorithm');
- assert.string(sig.signature, 'signature.signature');
- alg = validateAlgorithm(sig.algorithm);
-
- authz = sprintf(AUTHZ_FMT,
- sig.keyId,
- sig.algorithm,
- self.rs_headers.join(' '),
- sig.signature);
- } catch (e) {
- cb(e);
- return;
- }
- cb(null, authz);
- });
-
- } else {
- try {
- var sigObj = this.rs_signer.sign();
- } catch (e) {
- cb(e);
- return;
- }
- alg = (this.rs_alg[0] || this.rs_key.type) + '-' + sigObj.hashAlgorithm;
- var signature = sigObj.toString();
- authz = sprintf(AUTHZ_FMT,
- this.rs_keyId,
- alg,
- this.rs_headers.join(' '),
- signature);
- cb(null, authz);
- }
-};
-
-///--- Exported API
-
-module.exports = {
- /**
- * Identifies whether a given object is a request signer or not.
- *
- * @param {Object} object, the object to identify
- * @returns {Boolean}
- */
- isSigner: function (obj) {
- if (typeof (obj) === 'object' && obj instanceof RequestSigner)
- return (true);
- return (false);
- },
-
- /**
- * Creates a request signer, used to asynchronously build a signature
- * for a request (does not have to be an http.ClientRequest).
- *
- * @param {Object} options, either:
- * - {String} keyId
- * - {String|Buffer} key
- * - {String} algorithm (optional, required for HMAC)
- * or:
- * - {Func} sign (data, cb)
- * @return {RequestSigner}
- */
- createSigner: function createSigner(options) {
- return (new RequestSigner(options));
- },
-
- /**
- * Adds an 'Authorization' header to an http.ClientRequest object.
- *
- * Note that this API will add a Date header if it's not already set. Any
- * other headers in the options.headers array MUST be present, or this
- * will throw.
- *
- * You shouldn't need to check the return type; it's just there if you want
- * to be pedantic.
- *
- * The optional flag indicates whether parsing should use strict enforcement
- * of the version draft-cavage-http-signatures-04 of the spec or beyond.
- * The default is to be loose and support
- * older versions for compatibility.
- *
- * @param {Object} request an instance of http.ClientRequest.
- * @param {Object} options signing parameters object:
- * - {String} keyId required.
- * - {String} key required (either a PEM or HMAC key).
- * - {Array} headers optional; defaults to ['date'].
- * - {String} algorithm optional (unless key is HMAC);
- * default is the same as the sshpk default
- * signing algorithm for the type of key given
- * - {String} httpVersion optional; defaults to '1.1'.
- * - {Boolean} strict optional; defaults to 'false'.
- * @return {Boolean} true if Authorization (and optionally Date) were added.
- * @throws {TypeError} on bad parameter types (input).
- * @throws {InvalidAlgorithmError} if algorithm was bad or incompatible with
- * the given key.
- * @throws {sshpk.KeyParseError} if key was bad.
- * @throws {MissingHeaderError} if a header to be signed was specified but
- * was not present.
- */
- signRequest: function signRequest(request, options) {
- assert.object(request, 'request');
- assert.object(options, 'options');
- assert.optionalString(options.algorithm, 'options.algorithm');
- assert.string(options.keyId, 'options.keyId');
- assert.optionalArrayOfString(options.headers, 'options.headers');
- assert.optionalString(options.httpVersion, 'options.httpVersion');
-
- if (!request.getHeader('Date'))
- request.setHeader('Date', jsprim.rfc1123(new Date()));
- if (!options.headers)
- options.headers = ['date'];
- if (!options.httpVersion)
- options.httpVersion = '1.1';
-
- var alg = [];
- if (options.algorithm) {
- options.algorithm = options.algorithm.toLowerCase();
- alg = validateAlgorithm(options.algorithm);
- }
-
- var i;
- var stringToSign = '';
- for (i = 0; i < options.headers.length; i++) {
- if (typeof (options.headers[i]) !== 'string')
- throw new TypeError('options.headers must be an array of Strings');
-
- var h = options.headers[i].toLowerCase();
-
- if (h === 'request-line') {
- if (!options.strict) {
- /**
- * We allow headers from the older spec drafts if strict parsing isn't
- * specified in options.
- */
- stringToSign +=
- request.method + ' ' + request.path + ' HTTP/' +
- options.httpVersion;
- } else {
- /* Strict parsing doesn't allow older draft headers. */
- throw (new StrictParsingError('request-line is not a valid header ' +
- 'with strict parsing enabled.'));
- }
- } else if (h === '(request-target)') {
- stringToSign +=
- '(request-target): ' + request.method.toLowerCase() + ' ' +
- request.path;
- } else {
- var value = request.getHeader(h);
- if (value === undefined || value === '') {
- throw new MissingHeaderError(h + ' was not in the request');
- }
- stringToSign += h + ': ' + value;
- }
-
- if ((i + 1) < options.headers.length)
- stringToSign += '\n';
- }
-
- /* This is just for unit tests. */
- if (request.hasOwnProperty('_stringToSign')) {
- request._stringToSign = stringToSign;
- }
-
- var signature;
- if (alg[0] === 'hmac') {
- if (typeof (options.key) !== 'string' && !Buffer.isBuffer(options.key))
- throw (new TypeError('options.key must be a string or Buffer'));
-
- var hmac = crypto.createHmac(alg[1].toUpperCase(), options.key);
- hmac.update(stringToSign);
- signature = hmac.digest('base64');
-
- } else {
- var key = options.key;
- if (typeof (key) === 'string' || Buffer.isBuffer(key))
- key = sshpk.parsePrivateKey(options.key);
-
- assert.ok(sshpk.PrivateKey.isPrivateKey(key, [1, 2]),
- 'options.key must be a sshpk.PrivateKey');
-
- if (!PK_ALGOS[key.type]) {
- throw (new InvalidAlgorithmError(key.type.toUpperCase() + ' type ' +
- 'keys are not supported'));
- }
-
- if (alg[0] !== undefined && key.type !== alg[0]) {
- throw (new InvalidAlgorithmError('options.key must be a ' +
- alg[0].toUpperCase() + ' key, was given a ' +
- key.type.toUpperCase() + ' key instead'));
- }
-
- var signer = key.createSign(alg[1]);
- signer.update(stringToSign);
- var sigObj = signer.sign();
- if (!HASH_ALGOS[sigObj.hashAlgorithm]) {
- throw (new InvalidAlgorithmError(sigObj.hashAlgorithm.toUpperCase() +
- ' is not a supported hash algorithm'));
- }
- options.algorithm = key.type + '-' + sigObj.hashAlgorithm;
- signature = sigObj.toString();
- assert.notStrictEqual(signature, '', 'empty signature produced');
- }
-
- var authzHeaderName = options.authorizationHeaderName || 'Authorization';
-
- request.setHeader(authzHeaderName, sprintf(AUTHZ_FMT,
- options.keyId,
- options.algorithm,
- options.headers.join(' '),
- signature));
-
- return true;
- }
-
-};
-
-}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
-},{"../../is-buffer/index.js":766,"./utils":444,"assert-plus":77,"crypto":236,"http":1716,"jsprim":829,"sshpk":1708,"util":1776}],444:[function(require,module,exports){
-// Copyright 2012 Joyent, Inc. All rights reserved.
-
-var assert = require('assert-plus');
-var sshpk = require('sshpk');
-var util = require('util');
-
-var HASH_ALGOS = {
- 'sha1': true,
- 'sha256': true,
- 'sha512': true
-};
-
-var PK_ALGOS = {
- 'rsa': true,
- 'dsa': true,
- 'ecdsa': true
-};
-
-function HttpSignatureError(message, caller) {
- if (Error.captureStackTrace)
- Error.captureStackTrace(this, caller || HttpSignatureError);
-
- this.message = message;
- this.name = caller.name;
-}
-util.inherits(HttpSignatureError, Error);
-
-function InvalidAlgorithmError(message) {
- HttpSignatureError.call(this, message, InvalidAlgorithmError);
-}
-util.inherits(InvalidAlgorithmError, HttpSignatureError);
-
-function validateAlgorithm(algorithm) {
- var alg = algorithm.toLowerCase().split('-');
-
- if (alg.length !== 2) {
- throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' is not a ' +
- 'valid algorithm'));
- }
-
- if (alg[0] !== 'hmac' && !PK_ALGOS[alg[0]]) {
- throw (new InvalidAlgorithmError(alg[0].toUpperCase() + ' type keys ' +
- 'are not supported'));
- }
-
- if (!HASH_ALGOS[alg[1]]) {
- throw (new InvalidAlgorithmError(alg[1].toUpperCase() + ' is not a ' +
- 'supported hash algorithm'));
- }
-
- return (alg);
-}
-
-///--- API
-
-module.exports = {
-
- HASH_ALGOS: HASH_ALGOS,
- PK_ALGOS: PK_ALGOS,
-
- HttpSignatureError: HttpSignatureError,
- InvalidAlgorithmError: InvalidAlgorithmError,
-
- validateAlgorithm: validateAlgorithm,
-
- /**
- * Converts an OpenSSH public key (rsa only) to a PKCS#8 PEM file.
- *
- * The intent of this module is to interoperate with OpenSSL only,
- * specifically the node crypto module's `verify` method.
- *
- * @param {String} key an OpenSSH public key.
- * @return {String} PEM encoded form of the RSA public key.
- * @throws {TypeError} on bad input.
- * @throws {Error} on invalid ssh key formatted data.
- */
- sshKeyToPEM: function sshKeyToPEM(key) {
- assert.string(key, 'ssh_key');
-
- var k = sshpk.parseKey(key, 'ssh');
- return (k.toString('pem'));
- },
-
-
- /**
- * Generates an OpenSSH fingerprint from an ssh public key.
- *
- * @param {String} key an OpenSSH public key.
- * @return {String} key fingerprint.
- * @throws {TypeError} on bad input.
- * @throws {Error} if what you passed doesn't look like an ssh public key.
- */
- fingerprint: function fingerprint(key) {
- assert.string(key, 'ssh_key');
-
- var k = sshpk.parseKey(key, 'ssh');
- return (k.fingerprint('md5').toString('hex'));
- },
-
- /**
- * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
- *
- * The reverse of the above function.
- */
- pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
- assert.equal('string', typeof (pem), 'typeof pem');
-
- var k = sshpk.parseKey(pem, 'pem');
- k.comment = comment;
- return (k.toString('ssh'));
- }
-};
-
-},{"assert-plus":77,"sshpk":1708,"util":1776}],445:[function(require,module,exports){
-(function (Buffer){
-// Copyright 2015 Joyent, Inc.
-
-var assert = require('assert-plus');
-var crypto = require('crypto');
-var sshpk = require('sshpk');
-var utils = require('./utils');
-
-var HASH_ALGOS = utils.HASH_ALGOS;
-var PK_ALGOS = utils.PK_ALGOS;
-var InvalidAlgorithmError = utils.InvalidAlgorithmError;
-var HttpSignatureError = utils.HttpSignatureError;
-var validateAlgorithm = utils.validateAlgorithm;
-
-///--- Exported API
-
-module.exports = {
- /**
- * Verify RSA/DSA signature against public key. You are expected to pass in
- * an object that was returned from `parse()`.
- *
- * @param {Object} parsedSignature the object you got from `parse`.
- * @param {String} pubkey RSA/DSA private key PEM.
- * @return {Boolean} true if valid, false otherwise.
- * @throws {TypeError} if you pass in bad arguments.
- * @throws {InvalidAlgorithmError}
- */
- verifySignature: function verifySignature(parsedSignature, pubkey) {
- assert.object(parsedSignature, 'parsedSignature');
- if (typeof (pubkey) === 'string' || Buffer.isBuffer(pubkey))
- pubkey = sshpk.parseKey(pubkey);
- assert.ok(sshpk.Key.isKey(pubkey, [1, 1]), 'pubkey must be a sshpk.Key');
-
- var alg = validateAlgorithm(parsedSignature.algorithm);
- if (alg[0] === 'hmac' || alg[0] !== pubkey.type)
- return (false);
-
- var v = pubkey.createVerify(alg[1]);
- v.update(parsedSignature.signingString);
- return (v.verify(parsedSignature.params.signature, 'base64'));
- },
-
- /**
- * Verify HMAC against shared secret. You are expected to pass in an object
- * that was returned from `parse()`.
- *
- * @param {Object} parsedSignature the object you got from `parse`.
- * @param {String} secret HMAC shared secret.
- * @return {Boolean} true if valid, false otherwise.
- * @throws {TypeError} if you pass in bad arguments.
- * @throws {InvalidAlgorithmError}
- */
- verifyHMAC: function verifyHMAC(parsedSignature, secret) {
- assert.object(parsedSignature, 'parsedHMAC');
- assert.string(secret, 'secret');
-
- var alg = validateAlgorithm(parsedSignature.algorithm);
- if (alg[0] !== 'hmac')
- return (false);
-
- var hashAlg = alg[1].toUpperCase();
-
- var hmac = crypto.createHmac(hashAlg, secret);
- hmac.update(parsedSignature.signingString);
-
- /*
- * Now double-hash to avoid leaking timing information - there's
- * no easy constant-time compare in JS, so we use this approach
- * instead. See for more info:
- * https://www.isecpartners.com/blog/2011/february/double-hmac-
- * verification.aspx
- */
- var h1 = crypto.createHmac(hashAlg, secret);
- h1.update(hmac.digest());
- h1 = h1.digest();
- var h2 = crypto.createHmac(hashAlg, secret);
- h2.update(new Buffer(parsedSignature.params.signature, 'base64'));
- h2 = h2.digest();
-
- /* Node 0.8 returns strings from .digest(). */
- if (typeof (h1) === 'string')
- return (h1 === h2);
- /* And node 0.10 lacks the .equals() method on Buffers. */
- if (Buffer.isBuffer(h1) && !h1.equals)
- return (h1.toString('binary') === h2.toString('binary'));
-
- return (h1.equals(h2));
- }
-};
-
-}).call(this,require("buffer").Buffer)
-},{"./utils":444,"assert-plus":77,"buffer":217,"crypto":236,"sshpk":1708}],446:[function(require,module,exports){
+},{"hash.js":294,"minimalistic-assert":1129,"minimalistic-crypto-utils":1130}],311:[function(require,module,exports){
var http = require('http')
var url = require('url')
@@ -64987,7 +43578,7 @@ function validateParams (params) {
return params
}
-},{"http":1716,"url":1769}],447:[function(require,module,exports){
+},{"http":1475,"url":1507}],312:[function(require,module,exports){
'use strict'
const whole = /^((\d+(\.\d+)*)(ns|ms|us|µs|m|s|h))+$/
@@ -65025,7 +43616,7 @@ module.exports = function (time) {
}, 0)
}
-},{}],448:[function(require,module,exports){
+},{}],313:[function(require,module,exports){
/**
* Copyright (c) 2016 Tim Kuijsten
*
@@ -65163,900 +43754,9 @@ function idbReadableStream(db, storeName, opts) {
module.exports = idbReadableStream
-},{"stream":1715,"xtend":1860}],449:[function(require,module,exports){
-/* This file is generated from the Unicode IDNA table, using
- the build-unicode-tables.py script. Please edit that
- script instead of this file. */
-
-/* istanbul ignore next */
-(function (root, factory) {
- if (typeof define === 'function' && define.amd) {
- define([], function () { return factory(); });
- } else if (typeof exports === 'object') {
- module.exports = factory();
- } else {
- root.uts46_map = factory();
- }
-}(this, function () {
-var blocks = [
- new Uint32Array([2157250,2157314,2157378,2157442,2157506,2157570,2157634,0,2157698,2157762,2157826,2157890,2157954,0,2158018,0]),
- new Uint32Array([2179041,6291456,2179073,6291456,2179105,6291456,2179137,6291456,2179169,6291456,2179201,6291456,2179233,6291456,2179265,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064]),
- new Uint32Array([0,2113729,2197345,2197377,2113825,2197409,2197441,2113921,2197473,2114017,2197505,2197537,2197569,2197601,2197633,2197665]),
- new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672,23068672,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672,23068672,0,0,0,0,23068672]),
- new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064]),
- new Uint32Array([2196001,2196033,2196065,2196097,2196129,2196161,2196193,2196225,2196257,2196289,2196321,2196353,2196385,2196417,2196449,2196481]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,0,0,0,0,0]),
- new Uint32Array([2097281,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,2105889,2097185,2097697,2135777,2097633,2097441]),
- new Uint32Array([2177025,6291456,2177057,6291456,2177089,6291456,2177121,6291456,2177153,6291456,2177185,6291456,2177217,6291456,2177249,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456]),
- new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456]),
- new Uint32Array([2134435,2134531,2134627,2134723,2134723,2134819,2134819,2134915,2134915,2135011,2105987,2135107,2135203,2135299,2131587,2135395]),
- new Uint32Array([0,0,0,0,0,0,0,6291456,2168673,2169249,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354,2147906,2147970,2148034,2148098,2148162,2148226,2148290,2148354]),
- new Uint32Array([2125219,2125315,2152834,2152898,2125411,2152962,2153026,2125506,2125507,2125603,2153090,2153154,2153218,2153282,2153346,2105348]),
- new Uint32Array([2203393,6291456,2203425,6291456,2203457,6291456,2203489,6291456,6291456,6291456,6291456,2203521,6291456,2181281,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,23068672,6291456,2145538,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,6291456]),
- new Uint32Array([2139426,2160834,2160898,2160962,2134242,2161026,2161090,2161154,2161218,2161282,2161346,2161410,2138658,2161474,2161538,2134722]),
- new Uint32Array([2119939,2124930,2125026,2106658,2125218,2128962,2129058,2129154,2129250,2129346,2129442,2108866,2108770,2150466,2150530,2150594]),
- new Uint32Array([2201601,6291456,2201633,6291456,2201665,6291456,2201697,6291456,2201729,6291456,2201761,6291456,2201793,6291456,2201825,6291456]),
- new Uint32Array([2193537,2193569,2193601,2193633,2193665,2193697,2193729,2193761,2193793,2193825,2193857,2193889,2193921,2193953,2193985,2194017]),
- new Uint32Array([6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2190561,6291456,2190593,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2190625,6291456,2190657,6291456,23068672]),
- new Uint32Array([2215905,2215937,2215969,2216001,2216033,2216065,2216097,2216129,2216161,2216193,2216225,2216257,2105441,2216289,2216321,2216353]),
- new Uint32Array([23068672,18884130,23068672,23068672,23068672,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2191233,2191265,2191297,2191329,2191361,2191393,2191425,2117377,2191457,2191489,2191521,2191553,2191585,2191617,2191649,2117953]),
- new Uint32Array([2132227,2132323,2132419,2132419,2132515,2132515,2132611,2132707,2132707,2132803,2132899,2132899,2132995,2132995,2133091,2133187]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,0,0]),
- new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10609889,10610785,10609921,10610817,2222241]),
- new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]),
- new Uint32Array([2219969,2157121,2157441,2157505,2157889,2157953,2220001,2158465,2158529,10575617,2156994,2157058,2129923,2130019,2157122,2157186]),
- new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]),
- new Uint32Array([2185249,6291456,2185281,6291456,2185313,6291456,2185345,6291456,2185377,6291456,2185409,6291456,2185441,6291456,2185473,6291456]),
- new Uint32Array([0,0,0,0,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,6291456,0]),
- new Uint32Array([2183361,6291456,2183393,6291456,2183425,6291456,2183457,6291456,2183489,6291456,2183521,6291456,2183553,6291456,2183585,6291456]),
- new Uint32Array([2192161,2192193,2192225,2192257,2192289,2192321,2192353,2192385,2192417,2192449,2192481,2192513,2192545,2192577,2192609,2192641]),
- new Uint32Array([2212001,2212033,2212065,2212097,2212129,2212161,2212193,2212225,2212257,2212289,2212321,2212353,2212385,2212417,2212449,2207265]),
- new Uint32Array([2249825,2249857,2249889,2249921,2249954,2250018,2250082,2250145,2250177,2250209,2250241,2250274,2250337,2250370,2250433,2250465]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147905,2147969,2148033,2148097,2148161,2148225,2148289,2148353]),
- new Uint32Array([10485857,6291456,2197217,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,23068672,23068672]),
- new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([2180353,2180385,2144033,2180417,2180449,2180481,2180513,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,10610209,10610465,10610241,10610753,10609857]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]),
- new Uint32Array([2223842,2223906,2223970,2224034,2224098,2224162,2224226,2224290,2224354,2224418,2224482,2224546,2224610,2224674,2224738,2224802]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]),
- new Uint32Array([23068672,23068672,23068672,18923650,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,18923714,23068672,23068672]),
- new Uint32Array([2126179,2125538,2126275,2126371,2126467,2125634,2126563,2105603,2105604,2125346,2126659,2126755,2126851,2098179,2098181,2098182]),
- new Uint32Array([2227426,2227490,2227554,2227618,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2192353,2240642,2240642,2240705,2240737,2240737,2240769,2240802,2240866,2240929,2240961,2240993,2241025,2241057,2241089,2241121]),
- new Uint32Array([6291456,2170881,2170913,2170945,6291456,2170977,6291456,2171009,2171041,6291456,6291456,6291456,2171073,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2132226,2132514,2163586,2132610,2160386,2133090,2133186,2160450,2160514,2160578,2133570,2106178,2160642,2133858,2160706,2160770]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10532162,10532226,10532290,10532354,10532418,10532482,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]),
- new Uint32Array([2098209,2108353,2108193,2108481,2170241,2111713,2105473,2105569,2105601,2112289,2112481,2098305,2108321,0,0,0]),
- new Uint32Array([2209121,2209153,2209185,2209217,2209249,2209281,2209313,2209345,2209377,2209409,2209441,2209473,2207265,2209505,2209537,2209569]),
- new Uint32Array([2189025,6291456,2189057,6291456,2189089,6291456,2189121,6291456,2189153,6291456,2189185,6291456,2189217,6291456,2189249,6291456]),
- new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2165764,2140004]),
- new Uint32Array([2215105,6291456,2215137,6291456,6291456,2215169,2215201,6291456,6291456,6291456,2215233,2215265,2215297,2215329,2215361,2215393]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,6291456,6291456,6291456,23068672,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([10505091,10505187,10505283,10505379,10505475,10505571,10505667,10505763,10505859,10505955,10506051,10506147,10506243,10506339,10506435,10506531]),
- new Uint32Array([2229730,2229794,2229858,2229922,2229986,2230050,2230114,2230178,2230242,2230306,2230370,2230434,2230498,2230562,2230626,2230690]),
- new Uint32Array([2105505,2098241,2108353,2108417,2105825,0,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]),
- new Uint32Array([6291456,6291456,6291456,6291456,10502115,10502178,10502211,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]),
- new Uint32Array([2190305,6291456,2190337,6291456,2190369,6291456,2190401,6291456,2190433,6291456,2190465,6291456,2190497,6291456,2190529,6291456]),
- new Uint32Array([2173793,2173985,2174017,6291456,2173761,2173697,6291456,2174689,6291456,2174017,2174721,6291456,6291456,2174753,2174785,2174817]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609,2100033]),
- new Uint32Array([2132898,2163842,2163906,2133282,2132034,2131938,2137410,2132802,2132706,2164866,2133282,2160578,2165186,2165186,6291456,6291456]),
- new Uint32Array([10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059,10501155,10501251,10501347,10501443]),
- new Uint32Array([2163458,2130978,2131074,2131266,2131362,2163522,2160130,2132066,2131010,2131106,2106018,2131618,2131298,2132034,2131938,2137410]),
- new Uint32Array([2212961,2116993,2212993,2213025,2213057,2213089,2213121,2213153,2213185,2213217,2213249,2209633,2213281,2213313,2213345,2213377]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([2113729,2113825,2113921,2114017,2114113,2114209,2114305,2114401,2114497,2114593,2114689,2114785,2114881,2114977,2115073,2115169]),
- new Uint32Array([2238177,2238209,2238241,2238273,2238305,2238337,2238337,2217537,2238369,2238401,2238433,2238465,2215649,2238497,2238529,2238561]),
- new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]),
- new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0]),
- new Uint32Array([6291456,0,6291456,2145026,0,6291456,2145090,0,6291456,6291456,0,0,23068672,0,23068672,23068672]),
- new Uint32Array([2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129,2100289]),
- new Uint32Array([6291456,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0]),
- new Uint32Array([2187681,2187713,2187745,2187777,2187809,2187841,2187873,2187905,2187937,2187969,2188001,2188033,2188065,2188097,2188129,2188161]),
- new Uint32Array([0,10554498,10554562,10554626,10554690,10554754,10554818,10554882,10554946,10555010,10555074,6291456,6291456,0,0,0]),
- new Uint32Array([2235170,2235234,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0]),
- new Uint32Array([2181153,6291456,2188897,6291456,6291456,2188929,6291456,6291456,6291456,6291456,6291456,6291456,2111905,2100865,2188961,2188993]),
- new Uint32Array([2100833,2100897,0,0,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,2112289]),
- new Uint32Array([6291456,2172833,6291456,2172865,2172897,2172929,2172961,6291456,2172993,6291456,2173025,6291456,2173057,6291456,2173089,6291456]),
- new Uint32Array([6291456,0,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,2190721]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456]),
- new Uint32Array([2184993,6291456,2185025,6291456,2185057,6291456,2185089,6291456,2185121,6291456,2185153,6291456,2185185,6291456,2185217,6291456]),
- new Uint32Array([2115265,2115361,2115457,2115553,2115649,2115745,2115841,2115937,2116033,2116129,2116225,2116321,2150658,2150722,2200225,6291456]),
- new Uint32Array([2168321,6291456,2168353,6291456,2168385,6291456,2168417,6291456,2168449,6291456,2168481,6291456,2168513,6291456,2168545,6291456]),
- new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,0,6291456,0,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,2186625,0,0,6291456,6291456,2186657,2186689,2186721,2173505,0,10496067,10496163,10496259]),
- new Uint32Array([2178785,6291456,2178817,6291456,2178849,6291456,2178881,6291456,2178913,6291456,2178945,6291456,2178977,6291456,2179009,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]),
- new Uint32Array([2097152,0,0,0,2097152,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,0,2197857,2197889,2197921,2197953,2197985,2198017,0,0,2198049,2198081,2198113,2198145,2198177,2198209]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2098209,2167297,2111137,6291456]),
- new Uint32Array([2171393,6291456,2171425,6291456,2171457,6291456,2171489,6291456,2171521,6291456,2171553,6291456,2171585,6291456,2171617,6291456]),
- new Uint32Array([2206753,2206785,2195457,2206817,2206849,2206881,2206913,2197153,2197153,2206945,2117857,2206977,2207009,2207041,2207073,2207105]),
- new Uint32Array([0,0,0,0,0,0,0,23068672,0,0,0,0,2144834,2144898,0,2144962]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672]),
- new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,0,2105505,2098241]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,2202049,6291456,2202081,6291456,2202113,6291456,2202145,6291456,2202177,6291456,2202209,6291456,2202241,6291456]),
- new Uint32Array([10501155,10501251,10501347,10501443,10501539,10501635,10501731,10501827,10501923,10502019,2141731,2105505,2098177,2155586,2166530,0]),
- new Uint32Array([2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441]),
- new Uint32Array([2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330,2146882,2146946,2147010,2147074,2147138,2147202,2147266,2147330]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([10502307,10502403,10502499,10502595,10502691,10502787,10502883,10502979,10503075,10503171,10503267,10503363,10503459,10503555,10503651,10503747]),
- new Uint32Array([2179937,2179969,2180001,2180033,2156545,2180065,2156577,2180097,2180129,2180161,2180193,2180225,2180257,2180289,2156737,2180321]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,0,0,6291456,0,0,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]),
- new Uint32Array([2227682,2227746,2227810,2227874,2227938,2228002,2228066,2228130,2228194,2228258,2228322,2228386,2228450,2228514,2228578,2228642]),
- new Uint32Array([2105601,2169121,2108193,2170049,2181025,2181057,2112481,2108321,2108289,2181089,2170497,2100865,2181121,2173601,2173633,2173665]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180641,6291456,6291456,6291456]),
- new Uint32Array([0,6291456,6291456,6291456,0,6291456,0,6291456,0,0,6291456,6291456,0,6291456,6291456,6291456]),
- new Uint32Array([2178273,6291456,2178305,6291456,2178337,6291456,2178369,6291456,2178401,6291456,2178433,6291456,2178465,6291456,2178497,6291456]),
- new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,14680064,14680064,14680064,14680064,14680064,14680064]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]),
- new Uint32Array([2237377,2237409,2236225,2237441,2237473,2217441,2215521,2215553,2217473,2237505,2237537,2209697,2237569,2215585,2237601,2237633]),
- new Uint32Array([2221985,2165601,2165601,2165665,2165665,2222017,2222017,2165729,2165729,2158913,2158913,2158913,2158913,2097281,2097281,2105921]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2149634,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2176897,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2176929,6291456,2176961,6291456,2176993,6291456]),
- new Uint32Array([2172641,6291456,2172673,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2172705,2172737,6291456,2172769,2172801,6291456]),
- new Uint32Array([2099173,2104196,2121667,2099395,2121763,2152258,2152322,2098946,2152386,2121859,2121955,2099333,2122051,2104324,2099493,2122147]),
- new Uint32Array([6291456,6291456,6291456,2145794,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2145858,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,0,0,6291456,0]),
- new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,0,2097505,2105889,2097185,2097697,2135777,2097633,2097441]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2239074,2239138,2239201,2239233,2239265,2239297,2239329,2239361,0,2239393,2239425,2239425,2239458,2239521,2239553,2209569]),
- new Uint32Array([14680064,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,6291456,23068672]),
- new Uint32Array([2108321,2108289,2113153,2098209,2180897,2180929,2180961,2111137,2098241,2108353,2170241,2170273,2180993,2105825,6291456,2105473]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146114,6291456,6291456,6291456,0,0,0]),
- new Uint32Array([2105921,2105921,2105921,2222049,2222049,2130977,2130977,2130977,2130977,2160065,2160065,2160065,2160065,2097729,2097729,2097729]),
- new Uint32Array([2218145,2214785,2207937,2218177,2218209,2192993,2210113,2212769,2218241,2218273,2216129,2218305,2216161,2218337,2218369,2218401]),
- new Uint32Array([0,0,0,2156546,2156610,2156674,2156738,2156802,0,0,0,0,0,2156866,23068672,2156930]),
- new Uint32Array([23068672,23068672,23068672,0,0,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]),
- new Uint32Array([2213409,2213441,2213473,2213505,2213537,2213569,2213601,2213633,2213665,2195681,2213697,2213729,2213761,2213793,2213825,2213857]),
- new Uint32Array([2100033,2099233,2122017,2200673,2098113,2121537,2103201,2200705,2104033,2121857,2121953,2122401,2099649,2099969,2123009,2100129]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2201857,6291456,2201889,6291456,2201921,6291456,2201953,6291456,2201985,6291456,2202017,6291456,2176193,2176257,23068672,23068672]),
- new Uint32Array([6291456,6291456,23068672,23068672,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2188193,2188225,2188257,2188289,2188321,2188353,2188385,2188417,2188449,2188481,2188513,2188545,2188577,2188609,2188641,0]),
- new Uint32Array([10554529,2221089,0,10502113,10562017,10537921,10538049,2221121,2221153,0,0,0,0,0,0,0]),
- new Uint32Array([2213889,2213921,2213953,2213985,2214017,2214049,2214081,2194177,2214113,2214145,2214177,2214209,2214241,2214273,2214305,2214337]),
- new Uint32Array([2166978,2167042,2099169,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2180545,6291456,6291456,6291456]),
- new Uint32Array([10518915,10519011,10519107,10519203,2162242,2162306,2159554,2162370,2159362,2159618,2105922,2162434,2159746,2162498,2159810,2159874]),
- new Uint32Array([2161730,2161794,2135586,2161858,2161922,2137186,2131810,2160290,2135170,2161986,2137954,2162050,2162114,2162178,10518723,10518819]),
- new Uint32Array([10506627,10506723,10506819,10506915,10507011,10507107,10507203,10507299,10507395,10507491,10507587,10507683,10507779,10507875,10507971,10508067]),
- new Uint32Array([6291456,23068672,23068672,23068672,0,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0]),
- new Uint32Array([2175873,2175905,2175937,2175969,2176001,2176033,2176065,2176097,2176129,2176161,2176193,2176225,2176257,2176289,2176321,2176353]),
- new Uint32Array([2140006,2140198,2140390,2140582,2140774,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,23068672,23068672,23068672]),
- new Uint32Array([2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241]),
- new Uint32Array([0,23068672,0,0,0,0,0,0,0,2145154,2145218,2145282,6291456,0,2145346,0]),
- new Uint32Array([0,0,0,0,10531458,10495395,2148545,2143201,2173473,2148865,2173505,0,2173537,0,2173569,2149121]),
- new Uint32Array([10537282,10495683,2148738,2148802,2148866,0,6291456,2148930,2186593,2173473,2148737,2148865,2148802,10495779,10495875,10495971]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2215425,2215457,2215489,2215521,2215553,2215585,2215617,2215649,2215681,2215713,2215745,2215777,2192033,2215809,2215841,2215873]),
- new Uint32Array([2242049,2242081,2242113,2242145,2242177,2242209,2242241,2242273,2215937,2242305,2242338,2242401,2242433,2242465,2242497,2216001]),
- new Uint32Array([10554529,2221089,0,0,10562017,10502113,10538049,10537921,2221185,10489601,10489697,10609889,10609921,2141729,2141793,10610273]),
- new Uint32Array([2141923,2142019,2142115,2142211,2142307,2142403,2142499,2142595,2142691,0,0,0,0,0,0,0]),
- new Uint32Array([0,2221185,2221217,10609857,10609857,10489601,10489697,10609889,10609921,2141729,2141793,2221345,2221377,2221409,2221441,2187105]),
- new Uint32Array([6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18923970,23068672,23068672,23068672,0,6291456,6291456]),
- new Uint32Array([2183105,6291456,2183137,6291456,2183169,6291456,2183201,6291456,2183233,6291456,2183265,6291456,2183297,6291456,2183329,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]),
- new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]),
- new Uint32Array([2134434,2134818,2097666,2097186,2097474,2097698,2105986,2131586,2132450,2131874,2131778,2135970,2135778,2161602,2136162,2161666]),
- new Uint32Array([2236865,2236897,2236930,2236993,2237025,2235681,2237058,2237121,2237153,2237185,2237217,2217281,2237250,2191233,2237313,2237345]),
- new Uint32Array([2190049,6291456,2190081,6291456,2190113,6291456,2190145,6291456,2190177,6291456,2190209,6291456,2190241,6291456,2190273,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2101922,2102050,2102178,2102306,10498755,10498851,10498947,10499043,10499139,10499235,10499331,10499427,10499523,10489604,10489732,10489860]),
- new Uint32Array([2166914,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]),
- new Uint32Array([2181601,2170561,2181633,2181665,2170753,2181697,2172897,2170881,2181729,2170913,2172929,2113441,2181761,2181793,2171009,2173761]),
- new Uint32Array([0,2105921,2097729,2106081,0,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]),
- new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0]),
- new Uint32Array([2248001,2248033,2248066,2248130,2248193,2248226,2248289,2248322,2248385,2248417,2216673,2248450,2248514,2248577,2248610,2248673]),
- new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,0,0,0]),
- new Uint32Array([2169729,6291456,2169761,6291456,2169793,6291456,2169825,6291456,2169857,2169889,6291456,2169921,6291456,2143329,6291456,2098305]),
- new Uint32Array([2162178,2163202,2163266,2135170,2136226,2161986,2137954,2159426,2159490,2163330,2159554,2163394,2159682,2139522,2136450,2159746]),
- new Uint32Array([2173953,2173985,0,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2174209,2174241,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,4271169,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2174273]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,6291456,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,2190785,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2189793,6291456,2189825,6291456,2189857,6291456,2189889,6291456,2189921,6291456,2189953,6291456,2189985,6291456,2190017,6291456]),
- new Uint32Array([2105601,2112289,2108193,2112481,2112577,0,2098305,2108321,2108289,2100865,2113153,2108481,2113345,0,2098209,2111137]),
- new Uint32Array([2172129,6291456,2172161,6291456,2172193,6291456,2172225,6291456,2172257,6291456,2172289,6291456,2172321,6291456,2172353,6291456]),
- new Uint32Array([2214753,6291456,2214785,6291456,6291456,2214817,2214849,2214881,2214913,2214945,2214977,2215009,2215041,2215073,2194401,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([0,0,0,0,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([10610305,10610337,10575617,2221761,10610401,10610433,10502177,0,10610465,10610497,10610529,10610561,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,0,0,0,0,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2187105,2187137,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2199393,2199425,2199457,2199489,2199521,2199553,2199585,2199617,2199649,2199681,2199713,2199745,2199777,2199809,2199841,0]),
- new Uint32Array([2217249,2217281,2217313,2217345,2217377,2217409,2217441,2217473,2215617,2217505,2217537,2217569,2214753,2217601,2217633,2217665]),
- new Uint32Array([2170273,2170305,6291456,2170337,2170369,6291456,2170401,2170433,2170465,6291456,6291456,6291456,2170497,2170529,6291456,2170561]),
- new Uint32Array([2188673,6291456,2188705,2188737,2188769,6291456,6291456,2188801,6291456,2188833,6291456,2188865,6291456,2180929,2181505,2180897]),
- new Uint32Array([10489988,10490116,10490244,10490372,10490500,10490628,10490756,10490884,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2147393,2147457,2147521,2147585,2147649,2147713,2147777,2147841]),
- new Uint32Array([23068672,23068672,0,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]),
- new Uint32Array([2241153,2241185,2241217,2215809,2241250,2241313,2241345,2241377,2217921,2241377,2241409,2215873,2241441,2241473,2241505,2241537]),
- new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2220417,2220417,2220449,2220449,2220481,2220481,2220513,2220513,2220545,2220545,2220577,2220577,2220609,2220609,2220641,2220641]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2144002,0,6291456,6291456,0,0,6291456,6291456,6291456]),
- new Uint32Array([2167105,2167137,2167169,2167201,2167233,2167265,2167297,2167329,2167361,2167393,2167425,2167457,2167489,2167521,2167553,2167585]),
- new Uint32Array([10575521,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]),
- new Uint32Array([2234146,2234210,2234274,2234338,2234402,2234466,2234530,2234594,2234658,2234722,2234786,2234850,2234914,2234978,2235042,2235106]),
- new Uint32Array([0,0,0,0,0,0,0,2180577,0,0,0,0,0,2180609,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456]),
- new Uint32Array([2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2242529,2242561,2242593,2242625,2242657,2242689,2242721,2242753,2207937,2218177,2242785,2242817,2242849,2242882,2242945,2242977]),
- new Uint32Array([2118049,2105345,2118241,2105441,2118433,2118529,2118625,2118721,2118817,2200257,2200289,2191809,2200321,2200353,2200385,2200417]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]),
- new Uint32Array([2185505,6291456,2185537,6291456,2185569,6291456,2185601,6291456,2185633,6291456,2185665,6291456,2185697,6291456,2185729,6291456]),
- new Uint32Array([2231970,2232034,2232098,2232162,2232226,2232290,2232354,2232418,2232482,2232546,2232610,2232674,2232738,2232802,2232866,2232930]),
- new Uint32Array([2218625,2246402,2246466,2246530,2246594,2246657,2246689,2246689,2218657,2219681,2246721,2246753,2246785,2246818,2246881,2208481]),
- new Uint32Array([2197025,2197057,2197089,2197121,2197153,2197185,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2219137,2216961,2219169,2219201,2219233,2219265,2219297,2217025,2215041,2219329,2217057,2219361,2217089,2219393,2197153,2219426]),
- new Uint32Array([23068672,23068672,23068672,0,0,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,0,0]),
- new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713]),
- new Uint32Array([2243522,2243585,2243617,2243649,2243681,2210113,2243713,2243746,2243810,2243874,2243937,2243970,2244033,2244065,2244097,2244129]),
- new Uint32Array([2178017,6291456,2178049,6291456,2178081,6291456,2178113,6291456,2178145,6291456,2178177,6291456,2178209,6291456,2178241,6291456]),
- new Uint32Array([10553858,2165314,10518722,6291456,10518818,0,10518914,2130690,10519010,2130786,10519106,2130882,10519202,2165378,10554050,2165506]),
- new Uint32Array([0,0,2135491,2135587,2135683,2135779,2135875,2135971,2135971,2136067,2136163,2136259,2136355,2136355,2136451,2136547]),
- new Uint32Array([23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2220033,2220033,2220065,2220065,2220065,2220065,2220097,2220097,2220097,2220097,2220129,2220129,2220129,2220129,2220161,2220161]),
- new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2100897,2100898,2100899,2150018,2100865,2100866,2100867,2100868,2150082,2108481,2109858,2109859,2105569,2105505,2098241,2105601]),
- new Uint32Array([2097217,2097505,2097505,2097505,2097505,2165570,2165570,2165634,2165634,2165698,2165698,2097858,2097858,0,0,2097152]),
- new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,23068672,23068672]),
- new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([10503843,10503939,10504035,10504131,10504227,10504323,10504419,10504515,10504611,10504707,10504803,10504899,10504995,10491140,10491268,0]),
- new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,2235297,2220769,2235329,2235361]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2222401,2222433,2222465,10531394,2222497,2222529,2222561,0,2222593,2222625,2222657,2222689,2222721,2222753,2222785,0]),
- new Uint32Array([2184481,6291456,2184513,6291456,2184545,6291456,2184577,6291456,2184609,6291456,2184641,6291456,2184673,6291456,2184705,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2105570,2156034,2126947,2156098,2153666,2127043,2127139,2156162,0,2127235,2156226,2156290,2156354,2156418,2127331,2127427]),
- new Uint32Array([2215905,2207041,2153185,2241569,2241601,2241633,2241665,2241697,2241730,2241793,2241825,2241857,2241889,2241921,2241954,2242017]),
- new Uint32Array([2203777,6291456,2203809,6291456,2203841,6291456,2203873,6291456,2203905,6291456,2173121,2180993,2181249,2203937,2181313,0]),
- new Uint32Array([2168577,6291456,2168609,6291456,2168641,6291456,2168673,6291456,2168705,6291456,2168737,6291456,2168769,6291456,2168801,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,0,0]),
- new Uint32Array([2210113,2195521,2210145,2210177,2210209,2210241,2210273,2210305,2210337,2210369,2210401,2210433,2210465,2210497,2210529,2210561]),
- new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]),
- new Uint32Array([2228706,2228770,2228834,2228898,2228962,2229026,2229090,2229154,2229218,2229282,2229346,2229410,2229474,2229538,2229602,2229666]),
- new Uint32Array([23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,18874368,18874368,18874368,0,0]),
- new Uint32Array([2133089,2133281,2133281,2133281,2133281,2160577,2160577,2160577,2160577,2097441,2097441,2097441,2097441,2133857,2133857,2133857]),
- new Uint32Array([6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089]),
- new Uint32Array([2178529,6291456,2178561,6291456,2178593,6291456,2178625,6291456,2178657,6291456,2178689,6291456,2178721,6291456,2178753,6291456]),
- new Uint32Array([2221025,2221025,2221057,2221057,2159329,2159329,2159329,2159329,2097217,2097217,2158914,2158914,2158978,2158978,2159042,2159042]),
- new Uint32Array([2208161,2208193,2208225,2208257,2194433,2208289,2208321,2208353,2208385,2208417,2208449,2208481,2208513,2208545,2208577,2208609]),
- new Uint32Array([2169217,6291456,2169249,6291456,2169281,6291456,2169313,6291456,2169345,6291456,2169377,6291456,2169409,6291456,2169441,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456]),
- new Uint32Array([2133187,2133283,2133283,2133379,2133475,2133571,2133667,2133667,2133763,2133859,2133955,2134051,2134147,2134147,2134243,2134339]),
- new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,0]),
- new Uint32Array([2193089,2193121,2193153,2193185,2117665,2117569,2193217,2193249,2193281,2193313,2193345,2193377,2193409,2193441,2193473,2193505]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2184225,6291456,2184257,6291456,2184289,6291456,2184321,6291456,2184353,6291456,2184385,6291456,2184417,6291456,2184449,6291456]),
- new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2100833,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2200801,2200833,2200865,0]),
- new Uint32Array([23068672,23068672,23068672,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0]),
- new Uint32Array([2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2181153,2105505,2181185,2167617,2180993]),
- new Uint32Array([2160002,2160066,2160130,2160194,2160258,2132066,2131010,2131106,2106018,2131618,2160322,2131298,2132034,2131938,2137410,2132226]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,6291456]),
- new Uint32Array([2183617,6291456,2183649,6291456,2183681,6291456,2183713,6291456,2183745,6291456,2183777,6291456,2183809,6291456,2183841,6291456]),
- new Uint32Array([0,6291456,6291456,0,6291456,0,0,6291456,6291456,0,6291456,0,0,6291456,0,0]),
- new Uint32Array([2250977,2251009,2251041,2251073,2195009,2251106,2251169,2251201,2251233,2251265,2251297,2251330,2251394,2251457,2251489,2251521]),
- new Uint32Array([2205729,2205761,2205793,2205825,2205857,2205889,2205921,2205953,2205985,2206017,2206049,2206081,2206113,2206145,2206177,2206209]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2143170,2168993,6291456,2169025,6291456,2169057,6291456,2169089,6291456,2143234,2169121,6291456,2169153,6291456,2169185,6291456]),
- new Uint32Array([23068672,23068672,2190689,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2248706,2248769,2248801,2248833,2248865,2248897,2248929,2248962,2249026,2249090,2249154,2240705,2249217,2249249,2249281,2249313]),
- new Uint32Array([10485857,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10495394,6291456,2098209,6291456,6291456,2097152,6291456,10531394]),
- new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,0]),
- new Uint32Array([14680064,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]),
- new Uint32Array([6291456,2186977,6291456,6291456,6291456,6291456,6291456,10537858,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2209601,2209633,2209665,2209697,2209729,2209761,2209793,2209825,2209857,2209889,2209921,2209953,2209985,2210017,2210049,2210081]),
- new Uint32Array([10501539,10501635,10501731,10501827,10501923,10502019,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905]),
- new Uint32Array([2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([6291456,6291456,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2194561,2194593,2194625,2119777,2119873,2194657,2194689,2194721,2194753,2194785,2194817,2194849,2194881,2194913,2194945,2194977]),
- new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569]),
- new Uint32Array([2222818,2222882,2222946,2223010,2223074,2223138,2223202,2223266,2223330,2223394,2223458,2223522,2223586,2223650,2223714,2223778]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672]),
- new Uint32Array([0,2179553,2179585,2179617,2179649,2144001,2179681,2179713,2179745,2179777,2179809,2156705,2179841,2156833,2179873,2179905]),
- new Uint32Array([6291456,23068672,6291456,2145602,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,6291456,0,0]),
- new Uint32Array([2196513,2196545,2196577,2196609,2196641,2196673,2196705,2196737,2196769,2196801,2196833,2196865,2196897,2196929,2196961,2196993]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2177281,6291456,2177313,6291456,2177345,6291456,2177377,6291456,2177409,6291456,2177441,6291456,2177473,6291456,2177505,6291456]),
- new Uint32Array([2187137,2221473,2221505,2221537,2221569,6291456,6291456,10610209,10610241,10537986,10537986,10537986,10537986,10609857,10609857,10609857]),
- new Uint32Array([2243009,2243041,2216033,2243074,2243137,2243169,2243201,2219617,2243233,2243265,2243297,2243329,2243362,2243425,2243457,2243489]),
- new Uint32Array([10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,10485857,2097152,4194304,4194304,0,0]),
- new Uint32Array([2143042,6291456,2143106,2143106,2168833,6291456,2168865,6291456,6291456,2168897,6291456,2168929,6291456,2168961,6291456,2143170]),
- new Uint32Array([6291456,6291456,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2204193,2204225,2204257,2204289,2204321,2204353,2204385,2204417,2204449,2204481,2204513,2204545,2204577,2204609,2204641,2204673]),
- new Uint32Array([2202753,6291456,2202785,6291456,2202817,6291456,2202849,6291456,2202881,6291456,2202913,6291456,2202945,6291456,2202977,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321]),
- new Uint32Array([2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842,2147394,2147458,2147522,2147586,2147650,2147714,2147778,2147842]),
- new Uint32Array([2253313,2253346,2253409,2253441,2253473,2253505,2253537,2253569,2253601,2253634,2219393,2253697,2253729,2253761,2253793,2253825]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([2162562,2162626,2131362,2162690,2159938,2160002,2162754,2162818,2160130,2162882,2160194,2160258,2160834,2160898,2161026,2161090]),
- new Uint32Array([2175361,2175393,2175425,2175457,2175489,2175521,2175553,2175585,2175617,2175649,2175681,2175713,2175745,2175777,2175809,2175841]),
- new Uint32Array([2253858,2253921,2253954,2254018,2254082,2196737,2254145,2196865,2254177,2254209,2254241,2254273,2197025,2254306,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2202113,2204129,2188705,2204161]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953]),
- new Uint32Array([2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209]),
- new Uint32Array([2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,0,2108417,0,2111713,2100897,2111905]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0]),
- new Uint32Array([2175425,2175489,2175809,2175905,2175937,2175937,2176193,2176417,2180865,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,2143298,2143298,2143298,2143362,2143362,2143362,2143426,2143426,2143426,2171105,6291456,2171137]),
- new Uint32Array([2120162,2120258,2151618,2151682,2151746,2151810,2151874,2151938,2152002,2120035,2120131,2120227,2152066,2120323,2152130,2120419]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2195361,2142433,2236065,2236097,2236129,2236161,2118241,2117473,2236193,2236225,2236257,2236289,0,0,0,0]),
- new Uint32Array([2189281,6291456,2189313,6291456,2189345,6291456,2189377,6291456,2189409,6291456,2189441,6291456,2189473,6291456,2189505,6291456]),
- new Uint32Array([6291456,6291456,2145922,6291456,6291456,6291456,6291456,2145986,6291456,6291456,6291456,6291456,2146050,6291456,6291456,6291456]),
- new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10502113,10562017,10610401,10502177,10610433,10538049]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,2186401,0,2186433,0,2186465,0,2186497]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,23068672,23068672,23068672]),
- new Uint32Array([0,0,2198241,2198273,2198305,2198337,2198369,2198401,0,0,2198433,2198465,2198497,0,0,0]),
- new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,0,23068672,23068672,23068672,23068672,23068672,23068672,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]),
- new Uint32Array([0,2105921,2097729,0,2097377,0,0,2106017,2133281,2097505,2105889,0,2097697,2135777,2097633,2097441]),
- new Uint32Array([2197889,2197921,2197953,2197985,2198017,2198049,2198081,2198113,2198145,2198177,2198209,2198241,2198273,2198305,2198337,2198369]),
- new Uint32Array([2132514,2132610,2160386,2133090,2133186,2160450,2160514,2133282,2160578,2133570,2106178,2160642,2133858,2160706,2160770,2134146]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0,0,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,23068672,23068672,6291456,23068672,23068672,6291456,23068672,0,0,0,0,0,0,0,0]),
- new Uint32Array([2184737,6291456,2184769,6291456,2184801,6291456,2184833,6291456,2184865,6291456,2184897,6291456,2184929,6291456,2184961,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,6291456,6291456,6291456,0,6291456]),
- new Uint32Array([6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,23068672,23068672,23068672,6291456,23068672,23068672,23068672,23068672,23068672,0,0]),
- new Uint32Array([6291456,6291456,6291456,2186753,6291456,6291456,6291456,6291456,2186785,2186817,2186849,2173569,2186881,10496355,10495395,10575521]),
- new Uint32Array([0,0,2097729,0,0,0,0,2106017,0,2097505,0,2097185,0,2135777,2097633,2097441]),
- new Uint32Array([2189537,6291456,2189569,6291456,2189601,6291456,2189633,6291456,2189665,6291456,2189697,6291456,2189729,6291456,2189761,6291456]),
- new Uint32Array([2202497,6291456,2202529,6291456,2202561,6291456,2202593,6291456,2202625,6291456,2202657,6291456,2202689,6291456,2202721,6291456]),
- new Uint32Array([2245217,2218369,2245249,2245282,2245345,2245377,2245410,2245474,2245537,2245569,2245601,2245633,2245665,2245665,2245697,2245729]),
- new Uint32Array([6291456,0,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,23068672,6291456,23068672,6291456,6291456,6291456,6291456,23068672,23068672]),
- new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2097281,2105921,2097729,2106081,2097377,2097601,2162337,2106017,2133281,2097505,0,2097185,2097697,2135777,2097633,2097441]),
- new Uint32Array([2176641,6291456,2176673,6291456,2176705,6291456,2176737,6291456,2176769,6291456,2176801,6291456,2176833,6291456,2176865,6291456]),
- new Uint32Array([2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2174369,2174369,0,0,2100833,2100737]),
- new Uint32Array([2116513,2190817,2190849,2190881,2190913,2190945,2116609,2190977,2191009,2191041,2191073,2117185,2191105,2191137,2191169,2191201]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456]),
- new Uint32Array([0,0,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456]),
- new Uint32Array([2167617,2167649,2167681,2167713,2167745,2167777,2167809,6291456,2167841,2167873,2167905,2167937,2167969,2168001,2168033,4240130]),
- new Uint32Array([2165122,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122,2134562,2132162,2132834,2136866]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2186209,2186241,2186273,2186305,2186337,2186369,0,0]),
- new Uint32Array([2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,14680064,14680064,14680064,14680064,14680064]),
- new Uint32Array([0,0,23068672,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]),
- new Uint32Array([0,10537921,10610689,10610273,10610497,10610529,10610305,10610721,10489601,10489697,10610337,10575617,10554529,2221761,2197217,10496577]),
- new Uint32Array([2105473,2105569,2105601,2112289,0,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]),
- new Uint32Array([2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481]),
- new Uint32Array([2125346,2153410,2153474,2127394,2153538,2153602,2153666,2153730,2105507,2105476,2153794,2153858,2153922,2153986,2154050,2105794]),
- new Uint32Array([2200449,2119681,2200481,2153313,2199873,2199905,2199937,2200513,2200545,2200577,2200609,2119105,2119201,2119297,2119393,2119489]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2175777,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2222273,2197217,2221473,2221505,2221089,2222305,2200865,2099681,2104481,2222337,2099905,2120737,2222369,2103713,2100225,2098785]),
- new Uint32Array([2201377,6291456,2201409,6291456,2201441,6291456,2201473,6291456,2201505,6291456,2201537,6291456,2201569,6291456,6291456,23068672]),
- new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]),
- new Uint32Array([2200897,6291456,2200929,6291456,2200961,6291456,2200993,6291456,2201025,6291456,2180865,6291456,2201057,6291456,2201089,6291456]),
- new Uint32Array([0,0,0,0,0,23068672,23068672,0,6291456,6291456,6291456,0,0,0,0,0]),
- new Uint32Array([2161154,2161410,2138658,2161474,2161538,2097666,2097186,2097474,2162946,2132450,2163010,2163074,2136162,2163138,2161666,2161730]),
- new Uint32Array([2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953]),
- new Uint32Array([0,0,0,0,0,0,23068672,23068672,0,0,0,0,2145410,2145474,0,6291456]),
- new Uint32Array([2244161,2216065,2212769,2244193,2244225,2244257,2244290,2244353,2244385,2244417,2244449,2218273,2244481,2244514,2244577,2244609]),
- new Uint32Array([2125730,2125699,2125795,2125891,2125987,2154114,2154178,2154242,2154306,2154370,2154434,2154498,2126082,2126178,2126274,2126083]),
- new Uint32Array([2237665,2237697,2237697,2237697,2237730,2237793,2237825,2237857,2237890,2237953,2237985,2238017,2238049,2238081,2238113,2238145]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150146,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,0,0,23068672,23068672,23068672,0,0]),
- new Uint32Array([2214369,2238593,2238625,2238657,2238689,2238721,2238753,2238785,2238817,2238850,2238913,2238945,2238977,2235457,2239009,2239041]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([2252066,2252130,2252193,2252225,2252257,2252290,2252353,2252385,2252417,2252449,2252481,2252513,2252545,2252578,2252641,2252673]),
- new Uint32Array([2197697,2114113,2114209,2197729,2197761,2114305,2197793,2114401,2114497,2197825,2114593,2114689,2114785,2114881,2114977,2197857]),
- new Uint32Array([2224866,2224930,2224994,2225058,2225122,2225186,2225250,2225314,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2219490,2219554,2219617,2219649,2219681,2219714,2219778,2219842,2219905,2219937,0,0,0,0,0,0]),
- new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]),
- new Uint32Array([2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]),
- new Uint32Array([2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665]),
- new Uint32Array([2220161,2220161,2220193,2220193,2220193,2220193,2220225,2220225,2220225,2220225,2220257,2220257,2220257,2220257,2220289,2220289]),
- new Uint32Array([2192673,2192705,2192737,2192769,2192801,2192833,2192865,2118049,2192897,2117473,2117761,2192929,2192961,2192993,2193025,2193057]),
- new Uint32Array([2179297,6291456,2179329,6291456,2179361,6291456,2179393,6291456,2179425,6291456,2179457,6291456,2179489,6291456,2179521,6291456]),
- new Uint32Array([6291456,6291456,6291456,23068672,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2235745,2235777,2193633,2235809,2235841,2235873,2235905,2235937,2235969,2116513,2116705,2236001,2200513,2199905,2200545,2236033]),
- new Uint32Array([2113153,2108481,2113345,2113441,2232993,2233025,0,0,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761]),
- new Uint32Array([2170593,6291456,2170625,6291456,2170657,6291456,2170689,2170721,6291456,2170753,6291456,6291456,2170785,6291456,2170817,2170849]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2166786,2166850,0,0,0,0]),
- new Uint32Array([23068672,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,10575617,2187041,10502177,10489601,10489697,0]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2134562,2132162,2132834,2136866,2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058]),
- new Uint32Array([6291456,6291456,2098337,2101441,10531458,2153473,6291456,6291456,10531522,2100737,2108193,6291456,2106499,2106595,2106691,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2233122,2233186,2233250,2233314,2233378,2233442,2233506,2233570,2233634,2233698,2233762,2233826,2233890,2233954,2234018,2234082]),
- new Uint32Array([23068672,6291456,23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2205217,2205249,2205281,2205313,2205345,2205377,2205409,2205441,2205473,2205505,2205537,2205569,2205601,2205633,2205665,2205697]),
- new Uint32Array([6291456,0,6291456,0,0,0,6291456,6291456,6291456,6291456,0,0,23068672,6291456,23068672,23068672]),
- new Uint32Array([2173601,2173761,2174081,2173569,2174241,2174113,2173953,6291456,2174305,6291456,2174337,6291456,2174369,6291456,2174401,6291456]),
- new Uint32Array([6291456,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([2152450,2152514,2099653,2104452,2099813,2122243,2099973,2152578,2122339,2122435,2122531,2122627,2122723,2104580,2122819,2152642]),
- new Uint32Array([2236385,2236417,2236449,2236482,2236545,2215425,2236577,2236609,2236641,2236673,2215457,2236705,2236737,2236770,2215489,2236833]),
- new Uint32Array([2163394,2159746,2163458,2131362,2163522,2160130,2163778,2132226,2163842,2132898,2163906,2161410,2138658,2097666,2136162,2163650]),
- new Uint32Array([2218721,2246913,2246946,2216385,2247010,2247074,2215009,2247137,2247169,2216481,2247201,2247233,2247266,2247330,2247330,0]),
- new Uint32Array([2129730,2129762,2129858,2129731,2129827,2156482,2156482,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,0,0,0,0,6291456,0,0]),
- new Uint32Array([2203969,2204001,2181377,2204033,2204065,6291456,2204097,6291456,0,0,0,0,0,0,0,0]),
- new Uint32Array([2169473,6291456,2169505,6291456,2169537,6291456,2169569,6291456,2169601,6291456,2169633,6291456,2169665,6291456,2169697,6291456]),
- new Uint32Array([2141542,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2220801,2220801,2220801,2220801,2220833,2220833,2220865,2220865,2220865,2220865,2220897,2220897,2220897,2220897,2139873,2139873]),
- new Uint32Array([0,0,0,0,0,23068672,23068672,0,0,0,0,0,0,0,6291456,0]),
- new Uint32Array([2214849,2218433,2218465,2218497,2218529,2218561,2214881,2218593,2218625,2218657,2218689,2218721,2218753,2216545,2218785,2218817]),
- new Uint32Array([23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,0,0,0,6291456]),
- new Uint32Array([2136482,2164610,2164674,2164738,2164802,2132802,2132706,2164866,2132898,2164930,2164994,2165058,2165122,2132802,2132706,2164866]),
- new Uint32Array([2207649,2207681,2207713,2207745,2207777,2207809,2207841,2207873,2207905,2207937,2207969,2208001,2208033,2208065,2208097,2208129]),
- new Uint32Array([2123683,2105092,2152706,2123779,2105220,2152770,2100453,2098755,2123906,2124002,2124098,2124194,2124290,2124386,2124482,2124578]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,0,0,0,0,0,0,0,10485857]),
- new Uint32Array([6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([10508163,10508259,10508355,10508451,2200129,2200161,2192737,2200193,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2203553,6291456,2203585,6291456,6291456,6291456,2203617,6291456,2203649,6291456,2203681,6291456,2203713,6291456,2203745,6291456]),
- new Uint32Array([18884449,18884065,23068672,18884417,18884034,18921185,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,18874368]),
- new Uint32Array([2247393,2247426,2247489,2247521,2247553,2247586,2247649,2247681,2247713,2247745,2247777,2247810,2247873,2247905,2247937,2247969]),
- new Uint32Array([6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,23068672]),
- new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,2160577,2133857,2235297,0,2235329,0]),
- new Uint32Array([2182593,6291456,2182625,6291456,2182657,6291456,2182689,6291456,2182721,6291456,2182753,6291456,2182785,6291456,2182817,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102402,2102403,6291456,2110050]),
- new Uint32Array([2149890,2108323,2149954,6291456,2113441,6291456,2149057,6291456,2113441,6291456,2105473,2167265,2111137,2105505,6291456,2108353]),
- new Uint32Array([2219105,2219137,2195233,2251554,2251617,2251649,2251681,2251713,2251746,2251810,2251873,2251905,2251937,2251970,2252033,2219169]),
- new Uint32Array([2203009,6291456,2203041,6291456,2203073,6291456,2203105,6291456,2203137,6291456,2203169,6291456,2203201,6291456,2203233,6291456]),
- new Uint32Array([2128195,2128291,2128387,2128483,2128579,2128675,2128771,2128867,2128963,2129059,2129155,2129251,2129347,2129443,2129539,2129635]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2140964,2141156,2140966,2141158,2141350]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2225378,2225442,2225506,2225570,2225634,2225698,2225762,2225826,2225890,2225954,2226018,2226082,2226146,2226210,2226274,2226338]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137,2105505,2098241,2108353,2108417]),
- new Uint32Array([2108353,2108417,0,2105601,2108193,2157121,2157313,2157377,2157441,2100897,6291456,2108419,2173953,2173633,2173633,2173953]),
- new Uint32Array([2111713,2173121,2111905,2098177,2173153,2173185,2173217,2113153,2113345,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,2190753]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,2197249,6291456,2117377,2197281,2197313,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,0,0,0,0,0,0,23068672,0,0,0,0,0,6291456,6291456,6291456]),
- new Uint32Array([2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100833,2100737,2098337,2101441,2101569,2101697,2101825,2101953]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0]),
- new Uint32Array([0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,23068672]),
- new Uint32Array([2173281,6291456,2173313,6291456,2173345,6291456,2173377,6291456,0,0,10532546,6291456,6291456,6291456,10562017,2173441]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,0,0]),
- new Uint32Array([23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2159426,2159490,2159554,2159362,2159618,2159682,2139522,2136450,2159746,2159810,2159874,2130978,2131074,2131266,2131362,2159938]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2203233,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2203265,6291456,2203297,6291456,2203329,2203361,6291456]),
- new Uint32Array([6291456,6291456,2148418,2148482,2148546,0,6291456,2148610,2186529,2186561,2148417,2148545,2148482,10495778,2143969,10495778]),
- new Uint32Array([2134146,2139426,2160962,2134242,2161218,2161282,2161346,2161410,2138658,2134722,2134434,2134818,2097666,2097346,2097698,2105986]),
- new Uint32Array([2198881,2198913,2198945,2198977,2199009,2199041,2199073,2199105,2199137,2199169,2199201,2199233,2199265,2199297,2199329,2199361]),
- new Uint32Array([0,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]),
- new Uint32Array([10610561,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193]),
- new Uint32Array([2183873,6291456,2183905,6291456,2183937,6291456,2183969,6291456,2184001,6291456,2184033,6291456,2184065,6291456,2184097,6291456]),
- new Uint32Array([2244642,2244706,2244769,2244801,2218305,2244833,2244865,2244897,2244929,2244961,2244993,2245026,2245089,2245122,2245185,0]),
- new Uint32Array([6291456,6291456,2116513,2116609,2116705,2116801,2199873,2199905,2199937,2199969,2190913,2200001,2200033,2200065,2200097,2191009]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2180673,2180705,2180737,2180769,2180801,2180833,0,0]),
- new Uint32Array([2098081,2099521,2099105,2120705,2098369,2120801,2103361,2097985,2098433,2121377,2121473,2099169,2099873,2098401,2099393,2152609]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2150402]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,2145666,2145730,6291456,6291456]),
- new Uint32Array([2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665]),
- new Uint32Array([2187073,6291456,6291456,6291456,6291456,2098241,2098241,2108353,2100897,2111905,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2102404,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,2100612,6291456,6291456,6291456,6291456,6291456,6291456,6291456,10485857]),
- new Uint32Array([2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889]),
- new Uint32Array([2217697,2217729,2217761,2217793,2217825,2217857,2217889,2217921,2217953,2215873,2217985,2215905,2218017,2218049,2218081,2218113]),
- new Uint32Array([2211233,2218849,2216673,2218881,2218913,2218945,2218977,2219009,2216833,2219041,2215137,2219073,2216865,2209505,2219105,2216897]),
- new Uint32Array([2240097,2240129,2240161,2240193,2240225,2240257,2240289,2240321,2240353,2240386,2240449,2240481,2240513,2240545,2207905,2240578]),
- new Uint32Array([6291456,6291456,2202273,6291456,2202305,6291456,2202337,6291456,2202369,6291456,2202401,6291456,2202433,6291456,2202465,6291456]),
- new Uint32Array([0,23068672,23068672,18923394,23068672,18923458,18923522,18884099,18923586,18884195,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2201121,6291456,2201153,6291456,2201185,6291456,2201217,6291456,2201249,6291456,2201281,6291456,2201313,6291456,2201345,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,6291456]),
- new Uint32Array([2211041,2211073,2211105,2211137,2211169,2211201,2211233,2211265,2211297,2211329,2211361,2211393,2211425,2211457,2211489,2211521]),
- new Uint32Array([2181825,6291456,2181857,6291456,2181889,6291456,2181921,6291456,2181953,6291456,2181985,6291456,2182017,6291456,2182049,6291456]),
- new Uint32Array([2162337,2097633,2097633,2097633,2097633,2132705,2132705,2132705,2132705,2097153,2097153,2097153,2097153,2133089,2133089,2133089]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,2148545,6291456,2173473,6291456,2148865,6291456,2173505,6291456,2173537,6291456,2173569,6291456,2149121,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,0,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]),
- new Uint32Array([2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2207137,2207169,2207201,2207233,2207265,2207297,2207329,2207361,2207393,2207425,2207457,2207489,2207521,2207553,2207585,2207617]),
- new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,23068672,23068672,0,0,0,0,0,0]),
- new Uint32Array([2198401,2198433,2198465,2198497,0,2198529,2198561,2198593,2198625,2198657,2198689,2198721,2198753,2198785,2198817,2198849]),
- new Uint32Array([2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0,0]),
- new Uint32Array([2216385,2118721,2216417,2216449,2216481,2216513,2216545,2211233,2216577,2216609,2216641,2216673,2216705,2216737,2216737,2216769]),
- new Uint32Array([2216801,2216833,2216865,2216897,2216929,2216961,2216993,2215169,2217025,2217057,2217089,2217121,2217154,2217217,0,0]),
- new Uint32Array([2210593,2191809,2210625,2210657,2210689,2210721,2210753,2210785,2210817,2210849,2191297,2210881,2210913,2210945,2210977,2211009]),
- new Uint32Array([0,0,2105825,0,0,2111905,2105473,0,0,2112289,2108193,2112481,2112577,0,2098305,2108321]),
- new Uint32Array([0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,2097153,2134241,0,2132705,0,0,2131297,0,2133089,0,2133857,0,2220769,0,2235361]),
- new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,6291456,6291456,14680064]),
- new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]),
- new Uint32Array([2171873,6291456,2171905,6291456,2171937,6291456,2171969,6291456,2172001,6291456,2172033,6291456,2172065,6291456,2172097,6291456]),
- new Uint32Array([2220929,2220929,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2133857,2134145,2134145,2134145,2134145,2134241,2134241,2134241,2134241,2105889,2105889,2105889,2105889,2097185,2097185,2097185]),
- new Uint32Array([2173697,2173761,2173793,2174113,2173985,2173953,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,10499619,10499715,10499811,10499907]),
- new Uint32Array([0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,0,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,0,23068672,23068672,23068672,0,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,6291456,23068672,23068672]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,2144322,2144386,2144450,2144514,2144578,2144642,2144706,2144770]),
- new Uint32Array([23068672,23068672,23068672,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456]),
- new Uint32Array([2113153,2108481,2113345,2113441,2098209,2111137,0,2098241,2108353,2108417,2105825,0,0,2111905,2105473,2105569]),
- new Uint32Array([2236321,2236353,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2152194,2121283,2103684,2103812,2097986,2098533,2097990,2098693,2098595,2098853,2099013,2103940,2121379,2121475,2121571,2104068]),
- new Uint32Array([2206241,2206273,2206305,2206337,2206369,2206401,2206433,2206465,2206497,2206529,2206561,2206593,2206625,2206657,2206689,2206721]),
- new Uint32Array([6291456,6291456,6291456,6291456,16777216,16777216,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,23068672,23068672,10538818,10538882,6291456,6291456,2150338]),
- new Uint32Array([6291456,6291456,6291456,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2214369,2214401,2214433,2214465,2214497,2214529,2214561,2214593,2194977,2214625,2195073,2214657,2214689,2214721,6291456,6291456]),
- new Uint32Array([2097152,2097152,2097152,2097152,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2182081,6291456,2182113,6291456,2182145,6291456,2182177,6291456,2182209,6291456,2182241,6291456,2182273,6291456,2182305,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2146881,2146945,2147009,2147073,2147137,2147201,2147265,2147329]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,23068672,23068672]),
- new Uint32Array([0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2122915,2123011,2123107,2104708,2123203,2123299,2123395,2100133,2104836,2100290,2100293,2104962,2104964,2098052,2123491,2123587]),
- new Uint32Array([23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456]),
- new Uint32Array([6291456,2171169,6291456,2171201,6291456,2171233,6291456,2171265,6291456,2171297,6291456,2171329,6291456,6291456,2171361,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,0,2148994,2149058,2149122,0,6291456,2149186,2186945,2173537,2148993,2149121,2149058,10531458,10496066,0]),
- new Uint32Array([2195009,2195041,2195073,2195105,2195137,2195169,2195201,2195233,2195265,2195297,2195329,2195361,2195393,2195425,2195457,2195489]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,0,0,6291456,6291456]),
- new Uint32Array([2182849,6291456,2182881,6291456,2182913,6291456,2182945,6291456,2182977,6291456,2183009,6291456,2183041,6291456,2183073,6291456]),
- new Uint32Array([2211553,2210081,2211585,2211617,2211649,2211681,2211713,2211745,2211777,2211809,2209569,2211841,2211873,2211905,2211937,2211969]),
- new Uint32Array([2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2166594,2127298,2166658,2142978,2141827,2166722]),
- new Uint32Array([2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233057,2148481,2173601,2173633,2173665,2173697,2173729]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,0,0,2185761,2185793,2185825,2185857,2185889,2185921,0,0]),
- new Uint32Array([6291456,2148481,2173601,2173633,2173665,2173697,2173729,2148801,2173761,2143969,2173793,2173825,2153473,2173857,2173889,2173921]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,6291456]),
- new Uint32Array([0,0,0,2220961,2220961,2220961,2220961,2144193,2144193,2159201,2159201,2159265,2159265,2144194,2220993,2220993]),
- new Uint32Array([2192641,2235393,2235425,2152257,2116609,2235457,2235489,2200065,2235521,2235553,2235585,2212449,2235617,2235649,2235681,2235713]),
- new Uint32Array([2194049,2194081,2194113,2194145,2194177,2194209,2194241,2194273,2194305,2194337,2194369,2194401,2194433,2194465,2194497,2194529]),
- new Uint32Array([2196673,2208641,2208673,2208705,2208737,2208769,2208801,2208833,2208865,2208897,2208929,2208961,2208993,2209025,2209057,2209089]),
- new Uint32Array([2191681,2191713,2191745,2191777,2153281,2191809,2191841,2191873,2191905,2191937,2191969,2192001,2192033,2192065,2192097,2192129]),
- new Uint32Array([2230946,2231010,2231074,2231138,2231202,2231266,2231330,2231394,2231458,2231522,2231586,2231650,2231714,2231778,2231842,2231906]),
- new Uint32Array([14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064,14680064]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,2185953,2185985,2186017,2186049,2186081,2186113,2186145,2186177]),
- new Uint32Array([2139811,2139907,2097284,2105860,2105988,2106116,2106244,2097444,2097604,2097155,10485778,10486344,2106372,6291456,0,0]),
- new Uint32Array([2110051,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,0,0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2172385,6291456,2172417,6291456,2172449,6291456,2172481,6291456,2172513,6291456,2172545,6291456,2172577,6291456,2172609,6291456]),
- new Uint32Array([0,0,23068672,23068672,6291456,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2249345,2249377,2249409,2249441,2249473,2249505,2249537,2249570,2210209,2249633,2249665,2249697,2249729,2249761,2249793,2216769]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,6291456,6291456,6291456,6291456]),
- new Uint32Array([2187169,2187201,2187233,2187265,2187297,2187329,2187361,2187393,2187425,2187457,2187489,2187521,2187553,2187585,2187617,2187649]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([0,0,0,6291456,6291456,0,0,0,6291456,6291456,6291456,0,0,0,6291456,6291456]),
- new Uint32Array([2182337,6291456,2182369,6291456,2182401,6291456,2182433,6291456,2182465,6291456,2182497,6291456,2182529,6291456,2182561,6291456]),
- new Uint32Array([2138179,2138275,2138371,2138467,2134243,2134435,2138563,2138659,2138755,2138851,2138947,2139043,2138947,2138755,2139139,2139235]),
- new Uint32Array([23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]),
- new Uint32Array([0,0,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2250498,2250562,2250625,2250657,2208321,2250689,2250721,2250753,2250785,2250817,2250849,2218945,2250881,2250913,2250945,0]),
- new Uint32Array([2170369,2105569,2098305,2108481,2173249,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456]),
- new Uint32Array([2100897,2111905,2105473,2105569,2105601,0,2108193,0,0,0,2098305,2108321,2108289,2100865,2113153,2108481]),
- new Uint32Array([2100897,2100897,2105569,2105569,6291456,2112289,2149826,6291456,6291456,2112481,2112577,2098177,2098177,2098177,6291456,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,6291456,6291456,6291456]),
- new Uint32Array([6291456,2169953,2169985,6291456,2170017,6291456,2170049,2170081,6291456,2170113,2170145,2170177,6291456,6291456,2170209,2170241]),
- new Uint32Array([6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([0,0,0,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2220641,2220641,2220673,2220673,2220673,2220673,2220705,2220705,2220705,2220705,2220737,2220737,2220737,2220737,2220769,2220769]),
- new Uint32Array([2127650,2127746,2127842,2127938,2128034,2128130,2128226,2128322,2128418,2127523,2127619,2127715,2127811,2127907,2128003,2128099]),
- new Uint32Array([2143969,2173793,2173825,2153473,2173857,2173889,2173921,2173953,2173985,2173761,2174017,2174049,2174081,2174113,2174145,2174177]),
- new Uint32Array([0,0,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([2204705,2204737,2204769,2204801,2204833,2204865,2204897,2204929,2204961,2204993,2205025,2205057,2205089,2205121,2205153,2205185]),
- new Uint32Array([2176385,6291456,2176417,6291456,2176449,6291456,2176481,6291456,2176513,6291456,2176545,6291456,2176577,6291456,2176609,6291456]),
- new Uint32Array([2195521,2195553,2195585,2195617,2195649,2195681,2117857,2195713,2195745,2195777,2195809,2195841,2195873,2195905,2195937,2195969]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,6291456,6291456]),
- new Uint32Array([2173921,2173953,2173985,2174017,2174017,2174049,2174081,2174113,2174145,2174177,2149057,2233089,2173697,2173761,2173793,2174113]),
- new Uint32Array([2131586,2132450,2135970,2135778,2161602,2136162,2163650,2161794,2135586,2163714,2137186,2131810,2160290,2135170,2097506,2159554]),
- new Uint32Array([2134145,2097153,2134241,2105953,2132705,2130977,2160065,2131297,2162049,2133089,2160577,2133857,0,0,0,0]),
- new Uint32Array([2116513,2116609,2116705,2116801,2116897,2116993,2117089,2117185,2117281,2117377,2117473,2117569,2117665,2117761,2117857,2117953]),
- new Uint32Array([2100737,2098337,2101441,2101569,2101697,2101825,2101953,2102081,2102209,2100802,2101154,2101282,2101410,2101538,2101666,2101794]),
- new Uint32Array([2100289,2098657,2098049,2200737,2123489,2123681,2200769,2098625,2100321,2098145,2100449,2098017,2098753,2098977,2150241,2150305]),
- new Uint32Array([6291456,6291456,6291456,0,6291456,6291456,6291456,6291456,6291456,2109955,6291456,6291456,0,0,0,0]),
- new Uint32Array([18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368,18874368]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,6291456,0,6291456,0,0]),
- new Uint32Array([2130979,2131075,2131075,2131171,2131267,2131363,2131459,2131555,2131651,2131651,2131747,2131843,2131939,2132035,2132131,2132227]),
- new Uint32Array([0,2177793,6291456,2177825,6291456,2177857,6291456,2177889,6291456,2177921,6291456,2177953,6291456,2177985,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672]),
- new Uint32Array([6291456,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2113345,0,2098209,2111137,2105505,2098241,2108353,2108417,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289]),
- new Uint32Array([2136643,2136739,2136835,2136931,2137027,2137123,2137219,2137315,2137411,2137507,2137603,2137699,2137795,2137891,2137987,2138083]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0]),
- new Uint32Array([2174433,6291456,2174465,6291456,2174497,6291456,2174529,6291456,2174561,6291456,2174593,6291456,2174625,6291456,2174657,6291456]),
- new Uint32Array([0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441]),
- new Uint32Array([10496547,10496643,2105505,2149698,6291456,10496739,10496835,2170273,6291456,2149762,2105825,2111713,2111713,2111713,2111713,2168673]),
- new Uint32Array([6291456,2143490,2143490,2143490,2171649,6291456,2171681,2171713,2171745,6291456,2171777,6291456,2171809,6291456,2171841,6291456]),
- new Uint32Array([2159106,2159106,2159170,2159170,2159234,2159234,2159298,2159298,2159298,2159362,2159362,2159362,2106401,2106401,2106401,2106401]),
- new Uint32Array([2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865,2113153,2108481,2113345,2113441,2098209,2111137]),
- new Uint32Array([2108417,2181217,2181249,2181281,2170433,2170401,2181313,2181345,2181377,2181409,2181441,2181473,2181505,2181537,2170529,2181569]),
- new Uint32Array([2218433,2245761,2245793,2245825,2245857,2245890,2245953,2245986,2209665,2246050,2246113,2246146,2246210,2246274,2246337,2246369]),
- new Uint32Array([2230754,2230818,2230882,0,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([6291456,0,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,0,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2184129,6291456,2184161,6291456,2184193,6291456,6291456,6291456,6291456,6291456,2146818,2183361,6291456,6291456,2142978,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2135170,2097506,2130691,2130787,2130883,2163970,2164034,2164098,2164162,2164226,2164290,2164354,2164418,2164482,2164546,2133122]),
- new Uint32Array([2108515,2108611,2100740,2108707,2108803,2108899,2108995,2109091,2109187,2109283,2109379,2109475,2109571,2109667,2109763,2100738]),
- new Uint32Array([2102788,2102916,2103044,2120515,2103172,2120611,2120707,2098373,2103300,2120803,2120899,2120995,2103428,2103556,2121091,2121187]),
- new Uint32Array([2158082,2158146,0,2158210,2158274,0,2158338,2158402,2158466,2129922,2158530,2158594,2158658,2158722,2158786,2158850]),
- new Uint32Array([10499619,10499715,10499811,10499907,10500003,10500099,10500195,10500291,10500387,10500483,10500579,10500675,10500771,10500867,10500963,10501059]),
- new Uint32Array([2239585,2239618,2239681,2239713,0,2191969,2239745,2239777,2192033,2239809,2239841,2239874,2239937,2239970,2240033,2240065]),
- new Uint32Array([2252705,2252738,2252801,2252833,2252865,2252897,2252930,2252994,2253057,2253089,2253121,2253154,2253217,2253250,2219361,2219361]),
- new Uint32Array([2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,2108193,2112481,2112577,2098177,2098305,2108321,2108289,2100865]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,10538050,10538114,10538178,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([2226402,2226466,2226530,2226594,2226658,2226722,2226786,2226850,2226914,2226978,2227042,2227106,2227170,2227234,2227298,2227362]),
- new Uint32Array([23068672,6291456,6291456,6291456,6291456,2144066,2144130,2144194,2144258,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,23068672,23068672,23068672,6291456,23068672,23068672]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0]),
- new Uint32Array([2124674,2124770,2123875,2123971,2124067,2124163,2124259,2124355,2124451,2124547,2124643,2124739,2124835,2124931,2125027,2125123]),
- new Uint32Array([2168065,6291456,2168097,6291456,2168129,6291456,2168161,6291456,2168193,6291456,2168225,6291456,2168257,6291456,2168289,6291456]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0]),
- new Uint32Array([23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,2100610,2100611,6291456,2107842,2107843,6291456,6291456,6291456,6291456,10537922,6291456,10537986,6291456]),
- new Uint32Array([2174849,2174881,2174913,2174945,2174977,2175009,2175041,2175073,2175105,2175137,2175169,2175201,2175233,2175265,2175297,2175329]),
- new Uint32Array([2154562,2154626,2154690,2154754,2141858,2154818,2154882,2127298,2154946,2127298,2155010,2155074,2155138,2155202,2155266,2155202]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456,6291456,6291456,6291456,6291456,23068672,0]),
- new Uint32Array([2200641,2150786,2150850,2150914,2150978,2151042,2106562,2151106,2150562,2151170,2151234,2151298,2151362,2151426,2151490,2151554]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,23068672,0,0,0,0,0,0,0,0,6291456,6291456]),
- new Uint32Array([2220289,2220289,2220321,2220321,2220321,2220321,2220353,2220353,2220353,2220353,2220385,2220385,2220385,2220385,2220417,2220417]),
- new Uint32Array([2155330,2155394,0,2155458,2155522,2155586,2105732,0,2155650,2155714,2155778,2125314,2155842,2155906,2126274,2155970]),
- new Uint32Array([23068672,23068672,23068672,23068672,23068672,6291456,6291456,23068672,23068672,6291456,23068672,23068672,23068672,23068672,6291456,6291456]),
- new Uint32Array([6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,6291456,0,0,0,0,0,0]),
- new Uint32Array([2097729,2106017,2106017,2106017,2106017,2131297,2131297,2131297,2131297,2106081,2106081,2162049,2162049,2105953,2105953,2162337]),
- new Uint32Array([2097185,2097697,2097697,2097697,2097697,2135777,2135777,2135777,2135777,2097377,2097377,2097377,2097377,2097601,2097601,2097217]),
- new Uint32Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,23068672]),
- new Uint32Array([2139331,2139427,2139523,2139043,2133571,2132611,2139619,2139715,0,0,0,0,0,0,0,0]),
- new Uint32Array([2174113,2174145,2100897,2098177,2108289,2100865,2173601,2173633,2173985,2174113,2174145,6291456,6291456,6291456,6291456,6291456]),
- new Uint32Array([6291456,6291456,23068672,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456,23068672,6291456,6291456,6291456,6291456]),
- new Uint32Array([23068672,23068672,18923778,23068672,23068672,23068672,23068672,18923842,23068672,23068672,23068672,23068672,18923906,23068672,23068672,23068672]),
- new Uint32Array([2134145,2097153,2134241,0,2132705,2130977,2160065,2131297,0,2133089,0,2133857,0,0,0,0]),
- new Uint32Array([6291456,6291456,6291456,6291456,0,0,0,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2177537,6291456,2177569,6291456,2177601,6291456,2177633,6291456,2177665,6291456,2177697,6291456,2177729,6291456,2177761,6291456]),
- new Uint32Array([2212481,2212513,2212545,2212577,2197121,2212609,2212641,2212673,2212705,2212737,2212769,2212801,2212833,2212865,2212897,2212929]),
- new Uint32Array([6291456,6291456,23068672,23068672,23068672,6291456,6291456,0,0,0,0,0,0,0,0,0]),
- new Uint32Array([2098241,2108353,2170209,2105825,2111713,2100897,2111905,2105473,2105569,2105601,2112289,6291456,2108193,2172417,2112481,2098177]),
- new Uint32Array([6291456,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,23068672,6291456,6291456]),
-];
-var blockIdxes = new Uint16Array([616,616,565,147,161,411,330,2,131,131,328,454,241,408,86,86,696,113,285,350,325,301,473,214,639,232,447,64,369,598,124,672,567,223,621,154,107,86,86,86,86,86,86,505,86,68,634,86,218,218,218,218,486,218,218,513,188,608,216,86,217,463,668,85,700,360,184,86,86,86,647,402,153,10,346,718,662,260,145,298,117,1,443,342,138,54,563,86,240,572,218,70,387,86,118,460,641,602,86,86,306,218,86,692,86,86,86,86,86,162,707,86,458,26,86,218,638,86,86,86,86,86,65,449,86,86,306,183,86,58,391,667,86,157,131,131,131,131,86,433,131,406,31,218,247,86,86,693,218,581,351,86,438,295,69,462,45,126,173,650,14,295,69,97,168,187,641,78,523,390,69,108,287,664,173,219,83,295,69,108,431,426,173,694,412,115,628,52,257,398,641,118,501,121,69,579,151,423,173,620,464,121,69,382,151,476,173,27,53,121,86,594,578,226,173,86,632,130,86,96,228,268,641,622,563,86,86,21,148,650,131,131,321,43,144,343,381,531,131,131,178,20,86,399,156,375,164,541,30,60,715,198,92,118,131,131,86,86,306,407,86,280,457,196,488,358,131,131,244,86,86,143,86,86,86,86,86,667,563,86,86,86,86,86,86,86,86,86,86,86,86,86,336,363,86,86,336,86,86,380,678,67,86,86,86,678,86,86,86,512,86,307,86,708,86,86,86,86,86,528,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,563,307,86,86,86,86,86,104,450,337,86,720,86,32,450,397,86,86,86,587,218,558,708,708,293,708,86,86,86,86,86,694,205,86,8,86,86,86,86,549,86,667,697,697,679,86,458,460,86,86,650,86,708,543,86,86,86,245,86,86,86,140,218,127,708,708,458,197,131,131,131,131,500,86,86,483,251,86,306,510,515,86,722,86,86,86,65,201,86,86,483,580,470,86,86,86,368,131,131,131,694,114,110,555,86,86,123,721,163,142,713,418,86,317,675,209,218,218,218,371,545,592,629,490,603,199,46,320,525,680,310,279,388,111,42,252,593,607,235,617,410,377,50,548,135,356,17,520,189,116,392,600,349,332,482,699,690,535,119,106,451,71,152,667,131,218,218,265,671,637,492,504,533,683,269,269,658,86,86,86,86,86,86,86,86,86,491,619,86,86,6,86,86,86,86,86,86,86,86,86,86,86,229,86,86,86,86,86,86,86,86,86,86,86,86,667,86,86,171,131,118,131,656,206,234,571,89,334,670,246,311,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,534,86,86,86,86,86,86,82,86,86,86,86,86,430,86,86,86,86,86,86,86,86,86,599,86,324,86,470,69,640,264,131,626,101,174,86,86,667,233,105,73,374,394,221,204,84,28,326,86,86,471,86,86,86,109,573,86,171,200,200,200,200,218,218,86,86,86,86,460,131,131,131,86,506,86,86,86,86,86,220,404,34,614,47,442,305,25,612,338,601,648,7,344,255,131,131,51,86,312,507,563,86,86,86,86,588,86,86,86,86,86,530,511,86,458,3,435,384,556,522,230,527,86,118,86,86,717,86,137,273,79,181,484,23,93,112,655,249,417,703,370,87,98,313,684,585,155,465,596,481,695,18,416,428,61,701,706,282,643,495,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,86,86,86,171,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,650,131,422,542,420,263,24,172,86,86,86,86,86,566,86,86,132,540,395,353,494,519,19,485,284,472,131,131,131,16,714,86,211,708,86,86,86,694,698,86,86,483,704,708,218,272,86,86,120,86,159,478,86,307,247,86,86,663,597,459,627,667,86,86,277,455,39,302,86,250,86,86,86,271,99,452,306,281,329,400,200,86,86,362,549,352,646,461,323,586,86,86,4,708,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,717,86,518,86,86,650,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,125,554,480,300,613,72,333,288,561,544,604,48,719,91,169,176,590,224,76,191,29,559,560,231,537,166,477,538,256,437,131,131,469,167,40,0,685,266,441,705,239,642,475,568,640,610,299,673,517,318,385,22,202,180,179,359,424,215,90,66,521,653,467,682,453,409,479,88,131,661,35,303,15,262,666,630,712,131,131,618,659,175,218,195,347,193,227,261,150,165,709,546,294,569,710,270,413,376,524,55,242,38,419,529,170,657,3,304,122,379,278,131,651,86,67,576,458,458,131,131,86,86,86,86,86,86,86,118,309,86,86,547,86,86,86,86,667,650,664,131,131,86,86,56,131,131,131,131,131,131,131,131,86,307,86,86,86,664,238,650,86,86,717,86,118,86,86,315,86,59,86,86,574,549,131,131,340,57,436,86,86,86,86,86,86,458,708,499,691,62,86,650,86,86,694,86,86,86,319,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,86,549,694,131,131,131,131,131,131,131,131,131,77,86,86,139,86,502,86,86,86,667,595,131,131,131,86,12,86,13,86,609,131,131,131,131,86,86,86,625,86,669,86,86,182,129,86,5,694,104,86,86,86,86,131,131,86,86,386,171,86,86,86,345,86,324,86,589,86,213,36,131,131,131,131,131,86,86,86,86,104,131,131,131,141,290,80,677,86,86,86,267,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,515,86,86,33,136,669,86,711,515,86,86,550,640,86,104,708,515,86,159,372,717,86,86,444,515,86,86,663,37,86,563,460,86,390,624,702,131,131,131,131,389,59,708,86,86,341,208,708,635,295,69,108,431,508,100,190,131,131,131,131,131,131,131,131,86,86,86,649,516,660,131,131,86,86,86,218,631,708,131,131,131,131,131,131,131,131,131,131,86,86,341,575,238,514,131,131,86,86,86,218,291,708,307,131,86,86,306,367,708,131,131,131,86,378,697,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,615,253,86,86,86,292,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,104,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,69,86,341,553,549,86,307,86,86,645,275,455,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,708,131,131,131,131,131,131,86,86,86,86,86,86,667,460,86,86,86,86,86,86,86,86,86,86,86,86,717,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,104,86,667,459,131,131,131,131,131,131,86,458,225,86,86,86,516,549,11,390,405,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,460,44,218,197,711,515,131,131,131,131,664,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,118,307,104,286,591,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,681,86,86,75,185,314,582,86,358,496,474,86,104,131,86,86,86,86,146,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,171,86,640,131,131,131,131,131,131,131,131,246,503,689,339,674,81,258,415,439,128,562,366,414,246,503,689,583,222,557,316,636,665,186,355,95,670,246,503,689,339,674,557,258,415,439,186,355,95,670,246,503,689,446,644,536,652,331,532,335,440,274,421,297,570,74,425,364,425,606,552,403,509,134,365,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,218,218,218,498,218,218,577,627,551,497,572,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,553,354,236,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,296,455,131,131,456,243,103,86,41,459,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,9,276,158,716,393,564,383,489,401,654,210,654,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,650,86,86,86,86,86,86,717,667,563,563,563,86,549,102,686,133,246,605,86,448,86,86,207,307,131,131,131,641,86,177,611,445,373,194,584,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,307,171,86,86,86,86,86,86,86,717,86,86,86,86,86,460,131,131,650,86,86,86,694,708,86,86,694,86,458,131,131,131,131,131,131,667,694,289,650,667,131,131,86,640,131,131,664,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,460,86,86,86,86,86,86,86,86,86,86,86,86,86,458,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,466,203,149,429,94,432,160,687,539,63,237,283,192,248,348,259,427,526,396,676,254,468,487,212,327,623,49,633,322,493,434,688,357,361,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131]);
-var mappingStr = "صلى الله عليه وسلمجل جلالهキロメートルrad∕s2エスクードキログラムキロワットグラムトンクルゼイロサンチームパーセントピアストルファラッドブッシェルヘクタールマンションミリバールレントゲン′′′′1⁄10viii(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)∫∫∫∫(오전)(오후)アパートアルファアンペアイニングエーカーカラットカロリーキュリーギルダークローネサイクルシリングバーレルフィートポイントマイクロミクロンメガトンリットルルーブル株式会社kcalm∕s2c∕kgاكبرمحمدصلعمرسولریال1⁄41⁄23⁄4 ̈́ྲཱྀླཱྀ ̈͂ ̓̀ ̓́ ̓͂ ̔̀ ̔́ ̔͂ ̈̀‵‵‵a/ca/sc/oc/utelfax1⁄71⁄91⁄32⁄31⁄52⁄53⁄54⁄51⁄65⁄61⁄83⁄85⁄87⁄8xii0⁄3∮∮∮(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)::====(ᄀ)(ᄂ)(ᄃ)(ᄅ)(ᄆ)(ᄇ)(ᄉ)(ᄋ)(ᄌ)(ᄎ)(ᄏ)(ᄐ)(ᄑ)(ᄒ)(가)(나)(다)(라)(마)(바)(사)(아)(자)(차)(카)(타)(파)(하)(주)(一)(二)(三)(四)(五)(六)(七)(八)(九)(十)(月)(火)(水)(木)(金)(土)(日)(株)(有)(社)(名)(特)(財)(祝)(労)(代)(呼)(学)(監)(企)(資)(協)(祭)(休)(自)(至)pte10月11月12月ergltdアールインチウォンオンスオームカイリガロンガンマギニーケースコルナコーポセンチダースノットハイツパーツピクルフランペニヒヘルツペンスページベータボルトポンドホールホーンマイルマッハマルクヤードヤールユアンルピー10点11点12点13点14点15点16点17点18点19点20点21点22点23点24点hpabardm2dm3khzmhzghzthzmm2cm2km2mm3cm3km3kpampagpalogmilmolppmv∕ma∕m10日11日12日13日14日15日16日17日18日19日20日21日22日23日24日25日26日27日28日29日30日31日galffifflשּׁשּׂ ٌّ ٍّ َّ ُّ ِّ ّٰـَّـُّـِّتجمتحجتحمتخمتمجتمحتمخجمححميحمىسحجسجحسجىسمحسمجسممصححصممشحمشجيشمخشممضحىضخمطمحطممطميعجمعممعمىغممغميغمىفخمقمحقمملحملحيلحىلججلخملمحمحجمحيمجحمجممخممجخهمجهممنحمنحىنجمنجىنمينمىيممبخيتجيتجىتخيتخىتميتمىجميجحىجمىسخىصحيشحيضحيلجيلمييحييجييميمميقمينحيعميكمينجحمخيلجمكممجحيحجيمجيفميبحيسخينجيصلےقلے𝅘𝅥𝅮𝅘𝅥𝅯𝅘𝅥𝅰𝅘𝅥𝅱𝅘𝅥𝅲𝆹𝅥𝅮𝆺𝅥𝅮𝆹𝅥𝅯𝆺𝅥𝅯〔s〕ppv〔本〕〔三〕〔二〕〔安〕〔点〕〔打〕〔盗〕〔勝〕〔敗〕 ̄ ́ ̧ssi̇ijl·ʼndžljnjdz ̆ ̇ ̊ ̨ ̃ ̋ ιեւاٴوٴۇٴيٴक़ख़ग़ज़ड़ढ़फ़य़ড়ঢ়য়ਲ਼ਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ଡ଼ଢ଼ําໍາຫນຫມགྷཌྷདྷབྷཛྷཀྵཱཱིུྲྀླྀྒྷྜྷྡྷྦྷྫྷྐྵaʾἀιἁιἂιἃιἄιἅιἆιἇιἠιἡιἢιἣιἤιἥιἦιἧιὠιὡιὢιὣιὤιὥιὦιὧιὰιαιάιᾶι ͂ὴιηιήιῆιὼιωιώιῶι ̳!! ̅???!!?rs°c°fnosmtmivix⫝̸ ゙ ゚よりコト333435참고주의363738394042444546474849503月4月5月6月7月8月9月hgevギガデシドルナノピコビルペソホンリラレムdaauovpciu平成昭和大正明治naμakakbmbgbpfnfμfμgmgμlmldlklfmnmμmpsnsμsmsnvμvkvpwnwμwmwkwkωmωbqcccddbgyhainkkktlnlxphprsrsvwbstմնմեմիվնմխיִײַשׁשׂאַאָאּבּגּדּהּוּזּטּיּךּכּלּמּנּסּףּפּצּקּרּתּוֹבֿכֿפֿאלئائەئوئۇئۆئۈئېئىئجئحئمئيبجبمبىبيتىتيثجثمثىثيخحضجضمطحظمغجفجفحفىفيقحقىقيكاكجكحكخكلكىكينخنىنيهجهىهييىذٰرٰىٰئرئزئنبزبنترتزتنثرثزثنمانرنزننيريزئخئهبهتهصخنههٰثهسهشهطىطيعىعيغىغيسىسيشىشيصىصيضىضيشخشرسرصرضراً ًـًـّ ْـْلآلألإ𝅗𝅥0,1,2,3,4,5,6,7,8,9,wzhvsdwcmcmddjほかココàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįĵķĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷÿźżɓƃƅɔƈɖɗƌǝəɛƒɠɣɩɨƙɯɲɵơƣƥʀƨʃƭʈưʊʋƴƶʒƹƽǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǵƕƿǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟƞȣȥȧȩȫȭȯȱȳⱥȼƚⱦɂƀʉʌɇɉɋɍɏɦɹɻʁʕͱͳʹͷ;ϳέίόύβγδεζθκλνξοπρστυφχψϊϋϗϙϛϝϟϡϣϥϧϩϫϭϯϸϻͻͼͽѐёђѓєѕіїјљњћќѝўџабвгдежзийклмнопрстуфхцчшщъыьэюяѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯաբգդզէըթժլծկհձղճյշոչպջռստրցփքօֆ་ⴧⴭნᏰᏱᏲᏳᏴᏵꙋɐɑᴂɜᴖᴗᴝᴥɒɕɟɡɥɪᵻʝɭᶅʟɱɰɳɴɸʂƫᴜʐʑḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἐἑἒἓἔἕἰἱἲἳἴἵἶἷὀὁὂὃὄὅὑὓὕὗᾰᾱὲΐῐῑὶΰῠῡὺῥ`ὸ‐+−∑〈〉ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡɫᵽɽⱨⱪⱬⱳⱶȿɀⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⳳⵡ母龟丨丶丿乙亅亠人儿入冂冖冫几凵刀力勹匕匚匸卜卩厂厶又口囗士夂夊夕女子宀寸小尢尸屮山巛工己巾干幺广廴廾弋弓彐彡彳心戈戶手支攴文斗斤方无曰欠止歹殳毋比毛氏气爪父爻爿片牙牛犬玄玉瓜瓦甘生用田疋疒癶白皮皿目矛矢石示禸禾穴立竹米糸缶网羊羽老而耒耳聿肉臣臼舌舛舟艮色艸虍虫血行衣襾見角言谷豆豕豸貝赤走足身車辛辰辵邑酉釆里長門阜隶隹雨靑非面革韋韭音頁風飛食首香馬骨高髟鬥鬯鬲鬼魚鳥鹵鹿麥麻黃黍黑黹黽鼎鼓鼠鼻齊齒龍龜龠.〒卄卅ᄁᆪᆬᆭᄄᆰᆱᆲᆳᆴᆵᄚᄈᄡᄊ짜ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᄔᄕᇇᇈᇌᇎᇓᇗᇙᄜᇝᇟᄝᄞᄠᄢᄣᄧᄩᄫᄬᄭᄮᄯᄲᄶᅀᅇᅌᇱᇲᅗᅘᅙᆄᆅᆈᆑᆒᆔᆞᆡ上中下甲丙丁天地問幼箏우秘男適優印注項写左右医宗夜テヌモヨヰヱヲꙁꙃꙅꙇꙉꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼᵹꝿꞁꞃꞅꞇꞌꞑꞓꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩɬʞʇꭓꞵꞷꬷꭒᎠᎡᎢᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯ豈更賈滑串句契喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛蘭鸞嵐濫藍襤拉臘蠟廊朗浪狼郎來冷勞擄櫓爐盧蘆虜路露魯鷺碌祿綠菉錄論壟弄籠聾牢磊賂雷壘屢樓淚漏累縷陋勒肋凜凌稜綾菱陵讀拏諾丹寧怒率異北磻便復不泌數索參塞省葉說殺沈拾若掠略亮兩凉梁糧良諒量勵呂廬旅濾礪閭驪麗黎曆歷轢年憐戀撚漣煉璉秊練聯輦蓮連鍊列劣咽烈裂廉念捻殮簾獵令囹嶺怜玲瑩羚聆鈴零靈領例禮醴隸惡了僚寮尿料燎療蓼遼暈阮劉杻柳流溜琉留硫紐類戮陸倫崙淪輪律慄栗隆利吏履易李梨泥理痢罹裏裡離匿溺吝燐璘藺隣鱗麟林淋臨笠粒狀炙識什茶刺切度拓糖宅洞暴輻降廓兀嗀塚晴凞猪益礼神祥福靖精蘒諸逸都飯飼館鶴郞隷侮僧免勉勤卑喝嘆器塀墨層悔慨憎懲敏既暑梅海渚漢煮爫琢碑祉祈祐祖禍禎穀突節縉繁署者臭艹著褐視謁謹賓贈辶難響頻恵𤋮舘並况全侀充冀勇勺啕喙嗢墳奄奔婢嬨廒廙彩徭惘慎愈慠戴揄搜摒敖望杖滛滋瀞瞧爵犯瑱甆画瘝瘟盛直睊着磌窱类絛缾荒華蝹襁覆調請諭變輸遲醙鉶陼韛頋鬒𢡊𢡄𣏕㮝䀘䀹𥉉𥳐𧻓齃龎עםٱٻپڀٺٿٹڤڦڄڃچڇڍڌڎڈژڑکگڳڱںڻۀہھۓڭۋۅۉ、〖〗—–_{}【】《》「」『』[]#&*-<>\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀";
-
-function mapChar(codePoint) {
- if (codePoint >= 0x30000) {
- // High planes are special cased.
- if (codePoint >= 0xE0100 && codePoint <= 0xE01EF)
- return 18874368;
- return 0;
- }
- return blocks[blockIdxes[codePoint >> 4]][codePoint & 15];
-}
-
-return {
- mapStr: mappingStr,
- mapChar: mapChar
-};
-}));
-
-},{}],450:[function(require,module,exports){
-(function(root, factory) {
- /* istanbul ignore next */
- if (typeof define === 'function' && define.amd) {
- define(['punycode', './idna-map'], function(punycode, idna_map) {
- return factory(punycode, idna_map);
- });
- }
- else if (typeof exports === 'object') {
- module.exports = factory(require('punycode'), require('./idna-map'));
- }
- else {
- root.uts46 = factory(root.punycode, root.idna_map);
- }
-}(this, function(punycode, idna_map) {
-
- function mapLabel(label, useStd3ASCII, transitional) {
- var mapped = [];
- var chars = punycode.ucs2.decode(label);
- for (var i = 0; i < chars.length; i++) {
- var cp = chars[i];
- var ch = punycode.ucs2.encode([chars[i]]);
- var composite = idna_map.mapChar(cp);
- var flags = (composite >> 23);
- var kind = (composite >> 21) & 3;
- var index = (composite >> 5) & 0xffff;
- var length = composite & 0x1f;
- var value = idna_map.mapStr.substr(index, length);
- if (kind === 0 || (useStd3ASCII && (flags & 1))) {
- throw new Error("Illegal char " + ch);
- }
- else if (kind === 1) {
- mapped.push(value);
- }
- else if (kind === 2) {
- mapped.push(transitional ? value : ch);
- }
- /* istanbul ignore next */
- else if (kind === 3) {
- mapped.push(ch);
- }
- }
-
- var newLabel = mapped.join("").normalize("NFC");
- return newLabel;
- }
-
- function process(domain, transitional, useStd3ASCII) {
- /* istanbul ignore if */
- if (useStd3ASCII === undefined)
- useStd3ASCII = false;
- var mappedIDNA = mapLabel(domain, useStd3ASCII, transitional);
-
- // Step 3. Break
- var labels = mappedIDNA.split(".");
-
- // Step 4. Convert/Validate
- labels = labels.map(function(label) {
- if (label.startsWith("xn--")) {
- label = punycode.decode(label.substring(4));
- validateLabel(label, useStd3ASCII, false);
- }
- else {
- validateLabel(label, useStd3ASCII, transitional);
- }
- return label;
- });
-
- return labels.join(".");
- }
-
- function validateLabel(label, useStd3ASCII, transitional) {
- // 2. The label must not contain a U+002D HYPHEN-MINUS character in both the
- // third position and fourth positions.
- if (label[2] === '-' && label[3] === '-')
- throw new Error("Failed to validate " + label);
-
- // 3. The label must neither begin nor end with a U+002D HYPHEN-MINUS
- // character.
- if (label.startsWith('-') || label.endsWith('-'))
- throw new Error("Failed to validate " + label);
-
- // 4. The label must not contain a U+002E ( . ) FULL STOP.
- // this should nerver happen as label is chunked internally by this character
- /* istanbul ignore if */
- if (label.includes('.'))
- throw new Error("Failed to validate " + label);
-
- if (mapLabel(label, useStd3ASCII, transitional) !== label)
- throw new Error("Failed to validate " + label);
-
- // 5. The label must not begin with a combining mark, that is:
- // General_Category=Mark.
- var ch = label.codePointAt(0);
- if (idna_map.mapChar(ch) & (0x2 << 23))
- throw new Error("Label contains illegal character: " + ch);
- }
-
- function toAscii(domain, options) {
- if (options === undefined)
- options = {};
- var transitional = 'transitional' in options ? options.transitional : true;
- var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false;
- var verifyDnsLength = 'verifyDnsLength' in options ? options.verifyDnsLength : false;
- var labels = process(domain, transitional, useStd3ASCII).split('.');
- var asciiLabels = labels.map(punycode.toASCII);
- var asciiString = asciiLabels.join('.');
- var i;
- if (verifyDnsLength) {
- if (asciiString.length < 1 || asciiString.length > 253) {
- throw new Error("DNS name has wrong length: " + asciiString);
- }
- for (i = 0; i < asciiLabels.length; i++) {//for .. of replacement
- var label = asciiLabels[i];
- if (label.length < 1 || label.length > 63)
- throw new Error("DNS label has wrong length: " + label);
- }
- }
- return asciiString;
- }
-
- function toUnicode(domain, options) {
- if (options === undefined)
- options = {};
- var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false;
- return process(domain, false, useStd3ASCII);
- }
-
- return {
- toUnicode: toUnicode,
- toAscii: toAscii,
- };
-}));
-
-},{"./idna-map":449,"punycode":1538}],451:[function(require,module,exports){
+},{"stream":1459,"xtend":314}],314:[function(require,module,exports){
+arguments[4][7][0].apply(exports,arguments)
+},{"dup":7}],315:[function(require,module,exports){
exports.read = function (buffer, offset, isLE, mLen, nBytes) {
var e, m
var eLen = (nBytes * 8) - mLen - 1
@@ -66142,7 +43842,7 @@ exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
buffer[offset + i - d] |= s * 128
}
-},{}],452:[function(require,module,exports){
+},{}],316:[function(require,module,exports){
var indexOf = [].indexOf;
@@ -66153,36 +43853,9 @@ module.exports = function(arr, obj){
}
return -1;
};
-},{}],453:[function(require,module,exports){
-if (typeof Object.create === 'function') {
- // implementation from standard node.js 'util' module
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- ctor.prototype = Object.create(superCtor.prototype, {
- constructor: {
- value: ctor,
- enumerable: false,
- writable: true,
- configurable: true
- }
- })
- }
- };
-} else {
- // old school shim for old browsers
- module.exports = function inherits(ctor, superCtor) {
- if (superCtor) {
- ctor.super_ = superCtor
- var TempCtor = function () {}
- TempCtor.prototype = superCtor.prototype
- ctor.prototype = new TempCtor()
- ctor.prototype.constructor = ctor
- }
- }
-}
-
-},{}],454:[function(require,module,exports){
+},{}],317:[function(require,module,exports){
+arguments[4][27][0].apply(exports,arguments)
+},{"dup":27}],318:[function(require,module,exports){
'use strict'
const defer = require('pull-defer/duplex')
@@ -66244,14 +43917,14 @@ module.exports = class Connection {
}
}
-},{"pull-defer/duplex":1466}],455:[function(require,module,exports){
+},{"pull-defer/duplex":1284}],319:[function(require,module,exports){
'use strict'
exports.Connection = require('./connection')
-},{"./connection":454}],456:[function(require,module,exports){
-arguments[4][249][0].apply(exports,arguments)
-},{"dup":249}],457:[function(require,module,exports){
+},{"./connection":318}],320:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],321:[function(require,module,exports){
'use strict'
const errcode = require('err-code')
@@ -66276,7 +43949,7 @@ module.exports.notFoundError = (err) => {
return errcode(err, 'ERR_NOT_FOUND')
}
-},{"err-code":456}],458:[function(require,module,exports){
+},{"err-code":320}],322:[function(require,module,exports){
/* @flow */
'use strict'
@@ -66346,7 +44019,7 @@ export type Order = (QueryResult, Callback>) =>
*/
-},{"./errors":457,"./key":459,"./memory":460,"./utils":461}],459:[function(require,module,exports){
+},{"./errors":321,"./key":323,"./memory":324,"./utils":325}],323:[function(require,module,exports){
(function (Buffer){
/* @flow */
'use strict'
@@ -66728,7 +44401,7 @@ const _Key = withIs(Key, { className: 'Key', symbolName: '@ipfs/interface-datast
module.exports = _Key
}).call(this,require("buffer").Buffer)
-},{"buffer":217,"class-is":224,"uuid/v4":1781}],460:[function(require,module,exports){
+},{"buffer":181,"class-is":187,"uuid/v4":1517}],324:[function(require,module,exports){
/* @flow */
'use strict'
@@ -66863,7 +44536,7 @@ class MemoryDatastore {
module.exports = MemoryDatastore
-},{"./errors":457,"./key":459,"./utils":461,"async/setImmediate":146,"pull-stream":1495}],461:[function(require,module,exports){
+},{"./errors":321,"./key":323,"./utils":325,"async/setImmediate":96,"pull-stream":1311}],325:[function(require,module,exports){
'use strict'
const pull = require('pull-stream')
@@ -66944,7 +44617,7 @@ exports.tmpdir = () => {
return path.join(os.tmpdir(), uuid())
}
-},{"os":1395,"path":1425,"pull-defer/source":1469,"pull-stream":1495,"uuid/v4":1781}],462:[function(require,module,exports){
+},{"os":1229,"path":1246,"pull-defer/source":1287,"pull-stream":1311,"uuid/v4":1517}],326:[function(require,module,exports){
'use strict';
const v4 = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])(?:\\.(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])){3}';
@@ -66970,7 +44643,7 @@ const ip = module.exports = opts => opts && opts.exact ?
ip.v4 = opts => opts && opts.exact ? new RegExp(`^${v4}$`) : new RegExp(v4, 'g');
ip.v6 = opts => opts && opts.exact ? new RegExp(`^${v6}$`) : new RegExp(v6, 'g');
-},{}],463:[function(require,module,exports){
+},{}],327:[function(require,module,exports){
'use strict';
var ip = exports;
@@ -67388,7 +45061,7 @@ ip.fromLong = function(ipl) {
(ipl & 255) );
};
-},{"buffer":217,"os":1395}],464:[function(require,module,exports){
+},{"buffer":181,"os":1229}],328:[function(require,module,exports){
;(function (globalObject) {
'use strict';
@@ -70301,11 +47974,19957 @@ ip.fromLong = function(ipl) {
}
})(this);
-},{}],465:[function(require,module,exports){
-arguments[4][247][0].apply(exports,arguments)
-},{"./common":466,"_process":1438,"dup":247}],466:[function(require,module,exports){
-arguments[4][248][0].apply(exports,arguments)
-},{"dup":248,"ms":468}],467:[function(require,module,exports){
+},{}],329:[function(require,module,exports){
+arguments[4][208][0].apply(exports,arguments)
+},{"./common":330,"_process":1258,"dup":208}],330:[function(require,module,exports){
+arguments[4][209][0].apply(exports,arguments)
+},{"dup":209,"ms":1136}],331:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const blake = require('blakejs')
+
+const toCallback = require('./utils').toCallback
+
+const minB = 0xb201
+const minS = 0xb241
+
+const blake2b = {
+ init: blake.blake2bInit,
+ update: blake.blake2bUpdate,
+ digest: blake.blake2bFinal
+}
+
+const blake2s = {
+ init: blake.blake2sInit,
+ update: blake.blake2sUpdate,
+ digest: blake.blake2sFinal
+}
+
+const makeB2Hash = (size, hf) => toCallback((buf) => {
+ const ctx = hf.init(size, null)
+ hf.update(ctx, buf)
+ return Buffer.from(hf.digest(ctx))
+})
+
+module.exports = (table) => {
+ for (let i = 0; i < 64; i++) {
+ table[minB + i] = makeB2Hash(i + 1, blake2b)
+ }
+ for (let i = 0; i < 32; i++) {
+ table[minS + i] = makeB2Hash(i + 1, blake2s)
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./utils":335,"blakejs":132,"buffer":181}],332:[function(require,module,exports){
+(function (Buffer){
+/* global self */
+
+'use strict'
+
+const nodeify = require('nodeify')
+
+const webCrypto = getWebCrypto()
+
+function getWebCrypto () {
+ if (self.crypto) {
+ return self.crypto.subtle || self.crypto.webkitSubtle
+ }
+
+ if (self.msCrypto) {
+ return self.msCrypto.subtle
+ }
+}
+
+function webCryptoHash (type) {
+ if (!webCrypto) {
+ throw new Error('Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context')
+ }
+
+ return (data, callback) => {
+ const res = webCrypto.digest({ name: type }, data)
+
+ if (typeof res.then !== 'function') { // IE11
+ res.onerror = () => {
+ callback(new Error(`hashing data using ${type}`))
+ }
+ res.oncomplete = (e) => {
+ callback(null, e.target.result)
+ }
+ return
+ }
+
+ nodeify(
+ res.then((raw) => Buffer.from(new Uint8Array(raw))),
+ callback
+ )
+ }
+}
+
+function sha1 (buf, callback) {
+ webCryptoHash('SHA-1')(buf, callback)
+}
+
+function sha2256 (buf, callback) {
+ webCryptoHash('SHA-256')(buf, callback)
+}
+
+function sha2512 (buf, callback) {
+ webCryptoHash('SHA-512')(buf, callback)
+}
+
+module.exports = {
+ sha1: sha1,
+ sha2256: sha2256,
+ sha2512: sha2512
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"nodeify":1225}],333:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const sha3 = require('js-sha3')
+const murmur3 = require('murmurhash3js')
+
+const utils = require('./utils')
+const sha = require('./crypto-sha1-2')
+
+const toCallback = utils.toCallback
+const toBuf = utils.toBuf
+const fromString = utils.fromString
+const fromNumberTo32BitBuf = utils.fromNumberTo32BitBuf
+
+const dblSha2256 = (buf, cb) => {
+ sha.sha2256(buf, (err, firstHash) => {
+ if (err) {
+ cb(err)
+ }
+ sha.sha2256((Buffer.from(firstHash)), cb)
+ })
+}
+
+module.exports = {
+ sha1: sha.sha1,
+ sha2256: sha.sha2256,
+ sha2512: sha.sha2512,
+ sha3512: toCallback(toBuf(sha3.sha3_512)),
+ sha3384: toCallback(toBuf(sha3.sha3_384)),
+ sha3256: toCallback(toBuf(sha3.sha3_256)),
+ sha3224: toCallback(toBuf(sha3.sha3_224)),
+ shake128: toCallback(toBuf(sha3.shake_128, 128)),
+ shake256: toCallback(toBuf(sha3.shake_256, 256)),
+ keccak224: toCallback(toBuf(sha3.keccak_224)),
+ keccak256: toCallback(toBuf(sha3.keccak_256)),
+ keccak384: toCallback(toBuf(sha3.keccak_384)),
+ keccak512: toCallback(toBuf(sha3.keccak_512)),
+ murmur3128: toCallback(toBuf(fromString(murmur3.x64.hash128))),
+ murmur332: toCallback(fromNumberTo32BitBuf(fromString(murmur3.x86.hash32))),
+ addBlake: require('./blake'),
+ dblSha2256: dblSha2256
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./blake":331,"./crypto-sha1-2":332,"./utils":335,"buffer":181,"js-sha3":666,"murmurhash3js":1179}],334:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const multihash = require('multihashes')
+const crypto = require('./crypto')
+
+module.exports = Multihashing
+
+/**
+ * Hash the given `buf` using the algorithm specified
+ * by `func`.
+ *
+ * @param {Buffer} buf - The value to hash.
+ * @param {number|string} func - The algorithm to use.
+ * @param {number} [length] - Optionally trim the result to this length.
+ * @param {function(Error, Buffer)} callback
+ * @returns {undefined}
+ */
+function Multihashing (buf, func, length, callback) {
+ if (typeof length === 'function') {
+ callback = length
+ length = undefined
+ }
+
+ if (!callback) {
+ throw new Error('Missing callback')
+ }
+
+ Multihashing.digest(buf, func, length, (err, digest) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, multihash.encode(digest, func, length))
+ })
+}
+
+/**
+ * The `buffer` module for easy use in the browser.
+ *
+ * @type {Buffer}
+ */
+Multihashing.Buffer = Buffer // for browser things
+
+/**
+ * Expose multihash itself, to avoid silly double requires.
+ */
+Multihashing.multihash = multihash
+
+/**
+ * @param {Buffer} buf - The value to hash.
+ * @param {number|string} func - The algorithm to use.
+ * @param {number} [length] - Optionally trim the result to this length.
+ * @param {function(Error, Buffer)} callback
+ * @returns {undefined}
+ */
+Multihashing.digest = function (buf, func, length, callback) {
+ if (typeof length === 'function') {
+ callback = length
+ length = undefined
+ }
+
+ if (!callback) {
+ throw new Error('Missing callback')
+ }
+
+ let cb = callback
+ if (length) {
+ cb = (err, digest) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, digest.slice(0, length))
+ }
+ }
+
+ let hash
+ try {
+ hash = Multihashing.createHash(func)
+ } catch (err) {
+ return cb(err)
+ }
+
+ hash(buf, cb)
+}
+
+/**
+ * @param {string|number} func
+ *
+ * @returns {function} - The to `func` corresponding hash function.
+ */
+Multihashing.createHash = function (func) {
+ func = multihash.coerceCode(func)
+ if (!Multihashing.functions[func]) {
+ throw new Error('multihash function ' + func + ' not yet supported')
+ }
+
+ return Multihashing.functions[func]
+}
+
+/**
+ * Mapping of multihash codes to their hashing functions.
+ * @type {Object}
+ */
+Multihashing.functions = {
+ // sha1
+ 0x11: crypto.sha1,
+ // sha2-256
+ 0x12: crypto.sha2256,
+ // sha2-512
+ 0x13: crypto.sha2512,
+ // sha3-512
+ 0x14: crypto.sha3512,
+ // sha3-384
+ 0x15: crypto.sha3384,
+ // sha3-256
+ 0x16: crypto.sha3256,
+ // sha3-224
+ 0x17: crypto.sha3224,
+ // shake-128
+ 0x18: crypto.shake128,
+ // shake-256
+ 0x19: crypto.shake256,
+ // keccak-224
+ 0x1A: crypto.keccak224,
+ // keccak-256
+ 0x1B: crypto.keccak256,
+ // keccak-384
+ 0x1C: crypto.keccak384,
+ // keccak-512
+ 0x1D: crypto.keccak512,
+ // murmur3-128
+ 0x22: crypto.murmur3128,
+ // murmur3-32
+ 0x23: crypto.murmur332,
+ // dbl-sha2-256
+ 0x56: crypto.dblSha2256
+}
+
+// add blake functions
+crypto.addBlake(Multihashing.functions)
+
+}).call(this,require("buffer").Buffer)
+},{"./crypto":333,"buffer":181,"multihashes":1157}],335:[function(require,module,exports){
+(function (process,Buffer){
+'use strict'
+
+exports.toCallback = (doWork) => {
+ return function (input, callback) {
+ let res
+ try {
+ res = doWork(input)
+ } catch (err) {
+ process.nextTick(callback, err)
+ return
+ }
+
+ process.nextTick(callback, null, res)
+ }
+}
+
+exports.toBuf = (doWork, other) => (input) => {
+ let result = doWork(input, other)
+ return Buffer.from(result, 'hex')
+}
+
+exports.fromString = (doWork, other) => (_input) => {
+ const input = Buffer.isBuffer(_input) ? _input.toString() : _input
+ return doWork(input, other)
+}
+
+exports.fromNumberTo32BitBuf = (doWork, other) => (input) => {
+ let number = doWork(input, other)
+ const bytes = new Array(4)
+
+ for (let i = 0; i < 4; i++) {
+ bytes[i] = number & 0xff
+ number = number >> 8
+ }
+
+ return Buffer.from(bytes)
+}
+
+}).call(this,require('_process'),require("buffer").Buffer)
+},{"_process":1258,"buffer":181}],336:[function(require,module,exports){
+'use strict'
+
+const SECOND = 1000
+
+module.exports = {
+ maxProvidersPerRequest: 3,
+ providerRequestTimeout: 10 * SECOND,
+ hasBlockTimeout: 15 * SECOND,
+ provideTimeout: 15 * SECOND,
+ kMaxPriority: Math.pow(2, 31) - 1,
+ rebroadcastDelay: 10 * SECOND,
+ maxListeners: 1000
+}
+
+},{}],337:[function(require,module,exports){
+'use strict'
+
+const each = require('async/each')
+const eachSeries = require('async/eachSeries')
+const waterfall = require('async/waterfall')
+const nextTick = require('async/nextTick')
+
+const map = require('async/map')
+const debounce = require('just-debounce-it')
+
+const Message = require('../types/message')
+const Wantlist = require('../types/wantlist')
+const Ledger = require('./ledger')
+const { logger, groupBy, pullAllWith, uniqWith } = require('../utils')
+
+const MAX_MESSAGE_SIZE = 512 * 1024
+
+class DecisionEngine {
+ constructor (peerId, blockstore, network, stats) {
+ this._log = logger(peerId, 'engine')
+ this.blockstore = blockstore
+ this.network = network
+ this._stats = stats
+
+ // A list of of ledgers by their partner id
+ this.ledgerMap = new Map()
+ this._running = false
+
+ // List of tasks to be processed
+ this._tasks = []
+
+ this._outbox = debounce(this._processTasks.bind(this), 100)
+ }
+
+ _sendBlocks (peer, blocks, cb) {
+ // split into messges of max 512 * 1024 bytes
+ const total = blocks.reduce((acc, b) => {
+ return acc + b.data.byteLength
+ }, 0)
+
+ if (total < MAX_MESSAGE_SIZE) {
+ return this._sendSafeBlocks(peer, blocks, cb)
+ }
+
+ let size = 0
+ let batch = []
+ let outstanding = blocks.length
+
+ eachSeries(blocks, (b, cb) => {
+ outstanding--
+ batch.push(b)
+ size += b.data.byteLength
+
+ if (size >= MAX_MESSAGE_SIZE ||
+ // need to ensure the last remaining items get sent
+ outstanding === 0) {
+ size = 0
+ const nextBatch = batch.slice()
+ batch = []
+ this._sendSafeBlocks(peer, nextBatch, (err) => {
+ if (err) {
+ this._log('sendblock error: %s', err.message)
+ }
+ // not returning the error, so we send as much as we can
+ // as otherwise `eachSeries` would cancel
+ cb()
+ })
+ } else {
+ nextTick(cb)
+ }
+ }, cb)
+ }
+
+ _sendSafeBlocks (peer, blocks, cb) {
+ const msg = new Message(false)
+ blocks.forEach((b) => msg.addBlock(b))
+
+ this.network.sendMessage(peer, msg, cb)
+ }
+
+ _processTasks () {
+ if (!this._running || !this._tasks.length) {
+ return
+ }
+
+ const tasks = this._tasks
+ this._tasks = []
+ const entries = tasks.map((t) => t.entry)
+ const cids = entries.map((e) => e.cid)
+ const uniqCids = uniqWith((a, b) => a.equals(b), cids)
+ const groupedTasks = groupBy(task => task.target.toB58String(), tasks)
+
+ waterfall([
+ (callback) => map(uniqCids, (cid, cb) => {
+ this.blockstore.get(cid, cb)
+ }, callback),
+ (blocks, callback) => each(Object.values(groupedTasks), (tasks, cb) => {
+ // all tasks have the same target
+ const peer = tasks[0].target
+ const blockList = cids.map((cid) => {
+ return blocks.find(b => b.cid.equals(cid))
+ })
+
+ this._sendBlocks(peer, blockList, (err) => {
+ if (err) {
+ // `_sendBlocks` actually doesn't return any errors
+ this._log.error('should never happen: ', err)
+ } else {
+ blockList.forEach((block) => this.messageSent(peer, block))
+ }
+
+ cb()
+ })
+ }, callback)
+ ], (err) => {
+ this._tasks = []
+
+ if (err) {
+ this._log.error(err)
+ }
+ })
+ }
+
+ wantlistForPeer (peerId) {
+ const peerIdStr = peerId.toB58String()
+ if (!this.ledgerMap.has(peerIdStr)) {
+ return new Map()
+ }
+
+ return this.ledgerMap.get(peerIdStr).wantlist.sortedEntries()
+ }
+
+ ledgerForPeer (peerId) {
+ const peerIdStr = peerId.toB58String()
+
+ const ledger = this.ledgerMap.get(peerIdStr)
+ if (!ledger) {
+ return null
+ }
+ return {
+ peer: ledger.partner.toPrint(),
+ value: ledger.debtRatio(),
+ sent: ledger.accounting.bytesSent,
+ recv: ledger.accounting.bytesRecv,
+ exchanged: ledger.exchangeCount
+ }
+ }
+
+ peers () {
+ return Array.from(this.ledgerMap.values()).map((l) => l.partner)
+ }
+
+ receivedBlocks (cids) {
+ if (!cids.length) {
+ return
+ }
+ // Check all connected peers if they want the block we received
+ this.ledgerMap.forEach((ledger) => {
+ cids
+ .map((cid) => ledger.wantlistContains(cid))
+ .filter(Boolean)
+ .forEach((entry) => {
+ this._tasks.push({
+ entry: entry,
+ target: ledger.partner
+ })
+ })
+ })
+ this._outbox()
+ }
+
+ // Handle incoming messages
+ messageReceived (peerId, msg, cb) {
+ const ledger = this._findOrCreate(peerId)
+
+ if (msg.empty) {
+ return nextTick(cb)
+ }
+
+ // If the message was a full wantlist clear the current one
+ if (msg.full) {
+ ledger.wantlist = new Wantlist()
+ }
+
+ this._processBlocks(msg.blocks, ledger)
+
+ if (msg.wantlist.size === 0) {
+ return nextTick(cb)
+ }
+
+ let cancels = []
+ let wants = []
+ msg.wantlist.forEach((entry) => {
+ if (entry.cancel) {
+ ledger.cancelWant(entry.cid)
+ cancels.push(entry)
+ } else {
+ ledger.wants(entry.cid, entry.priority)
+ wants.push(entry)
+ }
+ })
+
+ this._cancelWants(ledger, peerId, cancels)
+ this._addWants(ledger, peerId, wants, cb)
+ }
+
+ _cancelWants (ledger, peerId, entries) {
+ const id = peerId.toB58String()
+
+ this._tasks = pullAllWith((t, e) => {
+ const sameTarget = t.target.toB58String() === id
+ const sameCid = t.entry.cid.equals(e.cid)
+ return sameTarget && sameCid
+ }, this._tasks, entries)
+ }
+
+ _addWants (ledger, peerId, entries, callback) {
+ each(entries, (entry, cb) => {
+ // If we already have the block, serve it
+ this.blockstore.has(entry.cid, (err, exists) => {
+ if (err) {
+ this._log.error('failed existence check')
+ } else if (exists) {
+ this._tasks.push({
+ entry: entry.entry,
+ target: peerId
+ })
+ }
+ cb()
+ })
+ }, () => {
+ this._outbox()
+ callback()
+ })
+ }
+
+ _processBlocks (blocks, ledger, callback) {
+ const cids = []
+ blocks.forEach((b, cidStr) => {
+ this._log('got block (%s bytes)', b.data.length)
+ ledger.receivedBytes(b.data.length)
+ cids.push(b.cid)
+ })
+
+ this.receivedBlocks(cids)
+ }
+
+ // Clear up all accounting things after message was sent
+ messageSent (peerId, block) {
+ const ledger = this._findOrCreate(peerId)
+ ledger.sentBytes(block ? block.data.length : 0)
+ if (block && block.cid) {
+ ledger.wantlist.remove(block.cid)
+ }
+ }
+
+ numBytesSentTo (peerId) {
+ return this._findOrCreate(peerId).accounting.bytesSent
+ }
+
+ numBytesReceivedFrom (peerId) {
+ return this._findOrCreate(peerId).accounting.bytesRecv
+ }
+
+ peerDisconnected (peerId) {
+ // if (this.ledgerMap.has(peerId.toB58String())) {
+ // this.ledgerMap.delete(peerId.toB58String())
+ // }
+ //
+ // TODO: figure out how to remove all other references
+ // in the peer request queue
+ }
+
+ _findOrCreate (peerId) {
+ const peerIdStr = peerId.toB58String()
+ if (this.ledgerMap.has(peerIdStr)) {
+ return this.ledgerMap.get(peerIdStr)
+ }
+
+ const l = new Ledger(peerId)
+
+ this.ledgerMap.set(peerIdStr, l)
+ if (this._stats) {
+ this._stats.push(peerIdStr, 'peerCount', 1)
+ }
+
+ return l
+ }
+
+ start (callback) {
+ this._running = true
+ nextTick(() => callback())
+ }
+
+ stop (callback) {
+ this._running = false
+ nextTick(() => callback())
+ }
+}
+
+module.exports = DecisionEngine
+
+},{"../types/message":345,"../types/wantlist":348,"../utils":349,"./ledger":338,"async/each":56,"async/eachSeries":61,"async/map":87,"async/nextTick":90,"async/waterfall":102,"just-debounce-it":668}],338:[function(require,module,exports){
+'use strict'
+
+const Wantlist = require('../types/wantlist')
+
+class Ledger {
+ constructor (peerId) {
+ this.partner = peerId
+ this.wantlist = new Wantlist()
+
+ this.exchangeCount = 0
+ this.sentToPeer = new Map()
+
+ this.accounting = {
+ bytesSent: 0,
+ bytesRecv: 0
+ }
+ }
+
+ sentBytes (n) {
+ this.exchangeCount++
+ this.lastExchange = (new Date()).getTime()
+ this.accounting.bytesSent += n
+ }
+
+ receivedBytes (n) {
+ this.exchangeCount++
+ this.lastExchange = (new Date()).getTime()
+ this.accounting.bytesRecv += n
+ }
+
+ wants (cid, priority) {
+ this.wantlist.add(cid, priority)
+ }
+
+ cancelWant (cid) {
+ this.wantlist.remove(cid)
+ }
+
+ wantlistContains (cid) {
+ return this.wantlist.contains(cid)
+ }
+
+ debtRatio () {
+ return (this.accounting.bytesSent / (this.accounting.bytesRecv + 1)) // +1 is to prevent division by zero
+ }
+}
+
+module.exports = Ledger
+
+},{"../types/wantlist":348}],339:[function(require,module,exports){
+'use strict'
+
+const waterfall = require('async/waterfall')
+const reject = require('async/reject')
+const each = require('async/each')
+const series = require('async/series')
+const map = require('async/map')
+const nextTick = require('async/nextTick')
+
+const WantManager = require('./want-manager')
+const Network = require('./network')
+const DecisionEngine = require('./decision-engine')
+const Notifications = require('./notifications')
+const logger = require('./utils').logger
+const Stats = require('./stats')
+
+const defaultOptions = {
+ statsEnabled: false,
+ statsComputeThrottleTimeout: 1000,
+ statsComputeThrottleMaxQueueSize: 1000
+}
+const statsKeys = [
+ 'blocksReceived',
+ 'dataReceived',
+ 'dupBlksReceived',
+ 'dupDataReceived',
+ 'blocksSent',
+ 'dataSent',
+ 'providesBufferLength',
+ 'wantListLength',
+ 'peerCount'
+]
+
+/**
+ * JavaScript implementation of the Bitswap 'data exchange' protocol
+ * used by IPFS.
+ *
+ * @param {Libp2p} libp2p
+ * @param {Blockstore} blockstore
+ */
+class Bitswap {
+ constructor (libp2p, blockstore, options) {
+ this._libp2p = libp2p
+ this._log = logger(this.peerInfo.id)
+
+ this._options = Object.assign({}, defaultOptions, options)
+
+ // stats
+ this._stats = new Stats(statsKeys, {
+ enabled: this._options.statsEnabled,
+ computeThrottleTimeout: this._options.statsComputeThrottleTimeout,
+ computeThrottleMaxQueueSize: this._options.statsComputeThrottleMaxQueueSize
+ })
+
+ // the network delivers messages
+ this.network = new Network(libp2p, this, {}, this._stats)
+
+ // local database
+ this.blockstore = blockstore
+
+ this.engine = new DecisionEngine(this.peerInfo.id, blockstore, this.network, this._stats)
+
+ // handle message sending
+ this.wm = new WantManager(this.peerInfo.id, this.network, this._stats)
+
+ this.notifications = new Notifications(this.peerInfo.id)
+ }
+
+ get peerInfo () {
+ return this._libp2p.peerInfo
+ }
+
+ // handle messages received through the network
+ _receiveMessage (peerId, incoming, callback) {
+ this.engine.messageReceived(peerId, incoming, (err) => {
+ if (err) {
+ // Only logging the issue to process as much as possible
+ // of the message. Currently `messageReceived` does not
+ // return any errors, but this could change in the future.
+ this._log('failed to receive message', incoming)
+ }
+
+ if (incoming.blocks.size === 0) {
+ return callback()
+ }
+
+ const blocks = Array.from(incoming.blocks.values())
+
+ // quickly send out cancels, reduces chances of duplicate block receives
+ const wanted = blocks
+ .filter((b) => this.wm.wantlist.contains(b.cid))
+ .map((b) => b.cid)
+
+ this.wm.cancelWants(wanted)
+
+ each(
+ blocks,
+ (b, cb) => {
+ const wasWanted = wanted.includes(b.cid)
+ this._handleReceivedBlock(peerId, b, wasWanted, cb)
+ },
+ callback
+ )
+ })
+ }
+
+ _handleReceivedBlock (peerId, block, wasWanted, callback) {
+ this._log('received block')
+
+ waterfall([
+ (cb) => this.blockstore.has(block.cid, cb),
+ (has, cb) => {
+ this._updateReceiveCounters(peerId.toB58String(), block, has)
+ if (has || !wasWanted) {
+ return nextTick(cb)
+ }
+
+ this._putBlock(block, cb)
+ }
+ ], callback)
+ }
+
+ _updateReceiveCounters (peerId, block, exists) {
+ this._stats.push(peerId, 'blocksReceived', 1)
+ this._stats.push(peerId, 'dataReceived', block.data.length)
+
+ if (exists) {
+ this._stats.push(peerId, 'dupBlksReceived', 1)
+ this._stats.push(peerId, 'dupDataReceived', block.data.length)
+ }
+ }
+
+ // handle errors on the receiving channel
+ _receiveError (err) {
+ this._log.error('ReceiveError: %s', err.message)
+ }
+
+ // handle new peers
+ _onPeerConnected (peerId) {
+ this.wm.connected(peerId)
+ }
+
+ // handle peers being disconnected
+ _onPeerDisconnected (peerId) {
+ this.wm.disconnected(peerId)
+ this.engine.peerDisconnected(peerId)
+ this._stats.disconnected(peerId)
+ }
+
+ _putBlock (block, callback) {
+ this.blockstore.put(block, (err) => {
+ if (err) {
+ return callback(err)
+ }
+
+ this.notifications.hasBlock(block)
+ this.network.provide(block.cid, (err) => {
+ if (err) {
+ this._log.error('Failed to provide: %s', err.message)
+ }
+ })
+
+ this.engine.receivedBlocks([block.cid])
+ callback()
+ })
+ }
+
+ enableStats () {
+ this._stats.enable()
+ }
+
+ disableStats () {
+ this._stats.disable()
+ }
+
+ /**
+ * Return the current wantlist for a given `peerId`
+ *
+ * @param {PeerId} peerId
+ * @returns {Wantlist}
+ */
+ wantlistForPeer (peerId) {
+ return this.engine.wantlistForPeer(peerId)
+ }
+
+ /**
+ * Return ledger information for a given `peerId`
+ *
+ * @param {PeerId} peerId
+ * @returns {?Object}
+ */
+ ledgerForPeer (peerId) {
+ return this.engine.ledgerForPeer(peerId)
+ }
+
+ /**
+ * Fetch a given block by cid. If the block is in the local
+ * blockstore it is returned, otherwise the block is added to the wantlist and returned once another node sends it to us.
+ *
+ * @param {CID} cid
+ * @param {function(Error, Block)} callback
+ * @returns {void}
+ */
+ get (cid, callback) {
+ this.getMany([cid], (err, blocks) => {
+ if (err) {
+ return callback(err)
+ }
+
+ if (blocks && blocks.length > 0) {
+ callback(null, blocks[0])
+ } else {
+ // when a unwant happens
+ callback()
+ }
+ })
+ }
+
+ /**
+ * Fetch a a list of blocks by cid. If the blocks are in the local
+ * blockstore they are returned, otherwise the blocks are added to the wantlist and returned once another node sends them to us.
+ *
+ * @param {Array} cids
+ * @param {function(Error, Blocks)} callback
+ * @returns {void}
+ */
+ getMany (cids, callback) {
+ let pendingStart = cids.length
+ const wantList = []
+ let promptedNetwork = false
+
+ const getFromOutside = (cid, cb) => {
+ wantList.push(cid)
+
+ this.notifications.wantBlock(
+ cid,
+ // called on block receive
+ (block) => {
+ this.wm.cancelWants([cid])
+ cb(null, block)
+ },
+ // called on unwant
+ () => {
+ this.wm.cancelWants([cid])
+ cb(null, undefined)
+ }
+ )
+
+ if (!pendingStart) {
+ this.wm.wantBlocks(wantList)
+ }
+ }
+
+ map(cids, (cid, cb) => {
+ waterfall(
+ [
+ (cb) => this.blockstore.has(cid, cb),
+ (has, cb) => {
+ pendingStart--
+ if (has) {
+ if (!pendingStart) {
+ this.wm.wantBlocks(wantList)
+ }
+ return this.blockstore.get(cid, cb)
+ }
+
+ if (!promptedNetwork) {
+ promptedNetwork = true
+ this.network.findAndConnect(cids[0], (err) => {
+ if (err) {
+ this._log.error(err)
+ }
+ })
+ }
+
+ // we don't have the block here
+ getFromOutside(cid, cb)
+ }
+ ],
+ cb)
+ }, callback)
+ }
+
+ // removes the given cids from the wantlist independent of any ref counts
+ unwant (cids) {
+ if (!Array.isArray(cids)) {
+ cids = [cids]
+ }
+
+ this.wm.unwantBlocks(cids)
+ cids.forEach((cid) => this.notifications.unwantBlock(cid))
+ }
+
+ // removes the given keys from the want list
+ cancelWants (cids) {
+ if (!Array.isArray(cids)) {
+ cids = [cids]
+ }
+ this.wm.cancelWants(cids)
+ }
+
+ /**
+ * Put the given block to the underlying blockstore and
+ * send it to nodes that have it in their wantlist.
+ *
+ * @param {Block} block
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ put (block, callback) {
+ this._log('putting block')
+
+ waterfall([
+ (cb) => this.blockstore.has(block.cid, cb),
+ (has, cb) => {
+ if (has) {
+ return nextTick(cb)
+ }
+
+ this._putBlock(block, cb)
+ }
+ ], callback)
+ }
+
+ /**
+ * Put the given blocks to the underlying blockstore and
+ * send it to nodes that have it them their wantlist.
+ *
+ * @param {Array} blocks
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ putMany (blocks, callback) {
+ waterfall([
+ (cb) => reject(blocks, (b, cb) => {
+ this.blockstore.has(b.cid, cb)
+ }, cb),
+ (newBlocks, cb) => this.blockstore.putMany(newBlocks, (err) => {
+ if (err) {
+ return cb(err)
+ }
+
+ newBlocks.forEach((block) => {
+ this.notifications.hasBlock(block)
+ this.engine.receivedBlocks([block.cid])
+ this.network.provide(block.cid, (err) => {
+ if (err) {
+ this._log.error('Failed to provide: %s', err.message)
+ }
+ })
+ })
+ cb()
+ })
+ ], callback)
+ }
+
+ /**
+ * Get the current list of wants.
+ *
+ * @returns {Iterator}
+ */
+ getWantlist () {
+ return this.wm.wantlist.entries()
+ }
+
+ /**
+ * Get the current list of partners.
+ *
+ * @returns {Array}
+ */
+ peers () {
+ return this.engine.peers()
+ }
+
+ /**
+ * Get stats about the bitswap node.
+ *
+ * @returns {Object}
+ */
+ stat () {
+ return this._stats
+ }
+
+ /**
+ * Start the bitswap node.
+ *
+ * @param {function(Error)} callback
+ *
+ * @returns {void}
+ */
+ start (callback) {
+ series([
+ (cb) => this.wm.start(cb),
+ (cb) => this.network.start(cb),
+ (cb) => this.engine.start(cb)
+ ], callback)
+ }
+
+ /**
+ * Stop the bitswap node.
+ *
+ * @param {function(Error)} callback
+ *
+ * @returns {void}
+ */
+ stop (callback) {
+ this._stats.stop()
+ series([
+ (cb) => this.wm.stop(cb),
+ (cb) => this.network.stop(cb),
+ (cb) => this.engine.stop(cb)
+ ], callback)
+ }
+}
+
+module.exports = Bitswap
+
+},{"./decision-engine":337,"./network":340,"./notifications":341,"./stats":342,"./utils":349,"./want-manager":350,"async/each":56,"async/map":87,"async/nextTick":90,"async/reject":93,"async/series":95,"async/waterfall":102}],340:[function(require,module,exports){
+'use strict'
+
+const lp = require('pull-length-prefixed')
+const pull = require('pull-stream')
+const waterfall = require('async/waterfall')
+const each = require('async/each')
+const nextTick = require('async/nextTick')
+
+const Message = require('./types/message')
+const CONSTANTS = require('./constants')
+const logger = require('./utils').logger
+
+const BITSWAP100 = '/ipfs/bitswap/1.0.0'
+const BITSWAP110 = '/ipfs/bitswap/1.1.0'
+
+class Network {
+ constructor (libp2p, bitswap, options, stats) {
+ this._log = logger(libp2p.peerInfo.id, 'network')
+ options = options || {}
+ this.libp2p = libp2p
+ this.bitswap = bitswap
+ this.b100Only = options.b100Only || false
+
+ this._stats = stats
+ this._running = false
+ }
+
+ start (callback) {
+ this._running = true
+ // bind event listeners
+ this._onPeerConnect = this._onPeerConnect.bind(this)
+ this._onPeerDisconnect = this._onPeerDisconnect.bind(this)
+
+ this._onConnection = this._onConnection.bind(this)
+ this.libp2p.handle(BITSWAP100, this._onConnection)
+ if (!this.b100Only) { this.libp2p.handle(BITSWAP110, this._onConnection) }
+
+ this.libp2p.on('peer:connect', this._onPeerConnect)
+ this.libp2p.on('peer:disconnect', this._onPeerDisconnect)
+
+ // All existing connections are like new ones for us
+ this.libp2p.peerBook
+ .getAllArray()
+ .filter((peer) => peer.isConnected())
+ .forEach((peer) => this._onPeerConnect((peer)))
+
+ nextTick(() => callback())
+ }
+
+ stop (callback) {
+ this._running = false
+
+ this.libp2p.unhandle(BITSWAP100)
+ if (!this.b100Only) { this.libp2p.unhandle(BITSWAP110) }
+
+ this.libp2p.removeListener('peer:connect', this._onPeerConnect)
+ this.libp2p.removeListener('peer:disconnect', this._onPeerDisconnect)
+
+ nextTick(() => callback())
+ }
+
+ // Handles both types of bitswap messgages
+ _onConnection (protocol, conn) {
+ if (!this._running) { return }
+ this._log('incomming new bitswap connection: %s', protocol)
+
+ pull(
+ conn,
+ lp.decode(),
+ pull.asyncMap((data, cb) => Message.deserialize(data, cb)),
+ pull.asyncMap((msg, cb) => {
+ conn.getPeerInfo((err, peerInfo) => {
+ if (err) { return cb(err) }
+
+ // this._log('data from', peerInfo.id.toB58String())
+ this.bitswap._receiveMessage(peerInfo.id, msg, cb)
+ })
+ }),
+ pull.onEnd((err) => {
+ this._log('ending connection')
+ if (err) {
+ this.bitswap._receiveError(err)
+ }
+ })
+ )
+ }
+
+ _onPeerConnect (peerInfo) {
+ if (!this._running) { return }
+
+ this.bitswap._onPeerConnected(peerInfo.id)
+ }
+
+ _onPeerDisconnect (peerInfo) {
+ if (!this._running) { return }
+
+ this.bitswap._onPeerDisconnected(peerInfo.id)
+ }
+
+ findProviders (cid, maxProviders, callback) {
+ this.libp2p.contentRouting.findProviders(cid, {
+ maxTimeout: CONSTANTS.providerRequestTimeout,
+ maxNumProviders: maxProviders
+ }, callback)
+ }
+
+ findAndConnect (cid, callback) {
+ waterfall([
+ (cb) => this.findProviders(cid, CONSTANTS.maxProvidersPerRequest, cb),
+ (provs, cb) => {
+ this._log('connecting to providers', provs.map((p) => p.id.toB58String()))
+ each(provs, (p, cb) => this.connectTo(p, cb))
+ }
+ ], callback)
+ }
+
+ provide (cid, callback) {
+ this.libp2p.contentRouting.provide(cid, callback)
+ }
+
+ // Connect to the given peer
+ // Send the given msg (instance of Message) to the given peer
+ sendMessage (peer, msg, callback) {
+ if (!this._running) { return callback(new Error(`network isn't running`)) }
+
+ const stringId = peer.toB58String() ? peer.toB58String() : peer.id.toB58String()
+ this._log('sendMessage to %s', stringId, msg)
+
+ this._dialPeer(peer, (err, conn, protocol) => {
+ if (err) {
+ return callback(err)
+ }
+
+ let serialized
+ switch (protocol) {
+ case BITSWAP100:
+ serialized = msg.serializeToBitswap100()
+ break
+ case BITSWAP110:
+ serialized = msg.serializeToBitswap110()
+ break
+ default:
+ return callback(new Error('Unkown protocol: ' + protocol))
+ }
+ // TODO: why doesn't the error get propageted back??
+ writeMessage(conn, serialized, (err) => {
+ if (err) {
+ this._log.error(err)
+ }
+ })
+ callback()
+ this._updateSentStats(peer, msg.blocks)
+ })
+ }
+
+ connectTo (peer, callback) {
+ if (!this._running) { return callback(new Error(`network isn't running`)) }
+
+ this.libp2p.dial(peer, callback)
+ }
+
+ // Dial to the peer and try to use the most recent Bitswap
+ _dialPeer (peer, callback) {
+ // Attempt Bitswap 1.1.0
+ this.libp2p.dialProtocol(peer, BITSWAP110, (err, conn) => {
+ if (err) {
+ // Attempt Bitswap 1.0.0
+ this.libp2p.dialProtocol(peer, BITSWAP100, (err, conn) => {
+ if (err) { return callback(err) }
+
+ callback(null, conn, BITSWAP100)
+ })
+
+ return
+ }
+
+ callback(null, conn, BITSWAP110)
+ })
+ }
+
+ _updateSentStats (peer, blocks) {
+ const peerId = peer.toB58String()
+ if (this._stats) {
+ blocks.forEach((block) => this._stats.push(peerId, 'dataSent', block.data.length))
+ this._stats.push(peerId, 'blocksSent', blocks.size)
+ }
+ }
+}
+
+function writeMessage (conn, msg, callback) {
+ pull(
+ pull.values([msg]),
+ lp.encode(),
+ conn,
+ pull.onEnd(callback)
+ )
+}
+
+module.exports = Network
+
+},{"./constants":336,"./types/message":345,"./utils":349,"async/each":56,"async/nextTick":90,"async/waterfall":102,"pull-length-prefixed":1292,"pull-stream":1311}],341:[function(require,module,exports){
+'use strict'
+
+const EventEmitter = require('events').EventEmitter
+
+const CONSTANTS = require('./constants')
+const logger = require('./utils').logger
+
+const unwantEvent = (c) => `unwant:${c}`
+const blockEvent = (c) => `block:${c}`
+
+/**
+ * Internal module used to track events about incoming blocks,
+ * wants and unwants.
+ *
+ * @param {PeerId} peerId
+ * @private
+ */
+class Notifications extends EventEmitter {
+ constructor (peerId) {
+ super()
+
+ this.setMaxListeners(CONSTANTS.maxListeners)
+
+ this._log = logger(peerId, 'notif')
+
+ this._unwantListeners = {}
+ this._blockListeners = {}
+ }
+
+ /**
+ * Signal the system that we received `block`.
+ *
+ * @param {Block} block
+ * @return {void}
+ */
+ hasBlock (block) {
+ const cidStr = block.cid.toString('base58btc')
+ const str = `block:${cidStr}`
+ this._log(str)
+ this.emit(str, block)
+ }
+
+ /**
+ * Signal the system that we are waiting to receive the
+ * block associated with the given `cid`.
+ *
+ * @param {CID} cid
+ * @param {function(Block)} onBlock - called when the block is received
+ * @param {function()} onUnwant - called when the block is unwanted
+ * @returns {void}
+ */
+ wantBlock (cid, onBlock, onUnwant) {
+ const cidStr = cid.toString('base58btc')
+ this._log(`wantBlock:${cidStr}`)
+
+ this._unwantListeners[cidStr] = () => {
+ this._log(`manual unwant: ${cidStr}`)
+ this._cleanup(cidStr)
+ onUnwant()
+ }
+
+ this._blockListeners[cidStr] = (block) => {
+ this._cleanup(cidStr)
+ onBlock(block)
+ }
+
+ this.once(
+ unwantEvent(cidStr),
+ this._unwantListeners[cidStr]
+ )
+ this.once(
+ blockEvent(cidStr),
+ this._blockListeners[cidStr]
+ )
+ }
+
+ /**
+ * Signal that the block is not wanted anymore.
+ *
+ * @param {CID} cid - the CID of the block that is not wanted anymore.
+ * @returns {void}
+ */
+ unwantBlock (cid) {
+ const str = `unwant:${cid.toString('base58btc')}`
+ this._log(str)
+ this.emit(str)
+ }
+
+ /**
+ * Internal method to clean up once a block was received or unwanted.
+ *
+ * @private
+ * @param {string} cidStr
+ * @returns {void}
+ */
+ _cleanup (cidStr) {
+ if (this._unwantListeners[cidStr]) {
+ this.removeListener(
+ unwantEvent(cidStr),
+ this._unwantListeners[cidStr]
+ )
+ delete this._unwantListeners[cidStr]
+ }
+
+ if (this._blockListeners[cidStr]) {
+ this.removeListener(
+ blockEvent(cidStr),
+ this._blockListeners[cidStr]
+ )
+ delete this._blockListeners[cidStr]
+ }
+ }
+}
+
+module.exports = Notifications
+
+},{"./constants":336,"./utils":349,"events":272}],342:[function(require,module,exports){
+'use strict'
+
+const EventEmitter = require('events')
+const Stat = require('./stat')
+
+const defaultOptions = {
+ movingAverageIntervals: [
+ 60 * 1000, // 1 minute
+ 5 * 60 * 1000, // 5 minutes
+ 15 * 60 * 1000 // 15 minutes
+ ]
+}
+
+class Stats extends EventEmitter {
+ constructor (initialCounters, _options) {
+ super()
+
+ const options = Object.assign({}, defaultOptions, _options)
+
+ if (typeof options.computeThrottleTimeout !== 'number') {
+ throw new Error('need computeThrottleTimeout')
+ }
+
+ if (typeof options.computeThrottleMaxQueueSize !== 'number') {
+ throw new Error('need computeThrottleMaxQueueSize')
+ }
+
+ this._initialCounters = initialCounters
+ this._options = options
+ this._enabled = this._options.enabled
+
+ this._global = new Stat(initialCounters, options)
+ this._global.on('update', (stats) => this.emit('update', stats))
+
+ this._peers = new Map()
+ }
+
+ enable () {
+ this._enabled = true
+ this._options.enabled = true
+ this._global.enable()
+ }
+
+ disable () {
+ this._enabled = false
+ this._options.enabled = false
+ this._global.disable()
+ }
+
+ stop () {
+ this._enabled = false
+ this._global.stop()
+ for (let peerStat of this._peers) {
+ peerStat[1].stop()
+ }
+ }
+
+ get snapshot () {
+ return this._global.snapshot
+ }
+
+ get movingAverages () {
+ return this._global.movingAverages
+ }
+
+ forPeer (peerId) {
+ if (peerId.toB58String) {
+ peerId = peerId.toB58String()
+ }
+ return this._peers.get(peerId)
+ }
+
+ push (peer, counter, inc) {
+ if (this._enabled) {
+ this._global.push(counter, inc)
+
+ if (peer) {
+ let peerStats = this._peers.get(peer)
+ if (!peerStats) {
+ peerStats = new Stat(this._initialCounters, this._options)
+ this._peers.set(peer, peerStats)
+ }
+
+ peerStats.push(counter, inc)
+ }
+ }
+ }
+
+ disconnected (peer) {
+ const peerId = peer.toB58String()
+ const peerStats = this._peers.get(peerId)
+ if (peerStats) {
+ peerStats.stop()
+ this._peers.delete(peerId)
+ }
+ }
+}
+
+module.exports = Stats
+
+},{"./stat":343,"events":272}],343:[function(require,module,exports){
+'use strict'
+
+const EventEmitter = require('events')
+const Big = require('bignumber.js')
+const MovingAverage = require('moving-average')
+
+class Stats extends EventEmitter {
+ constructor (initialCounters, options) {
+ super()
+
+ this._options = options
+ this._queue = []
+ this._stats = {}
+
+ this._frequencyLastTime = Date.now()
+ this._frequencyAccumulators = {}
+ this._movingAverages = {}
+
+ this._update = this._update.bind(this)
+
+ initialCounters.forEach((key) => {
+ this._stats[key] = Big(0)
+ this._movingAverages[key] = {}
+ this._options.movingAverageIntervals.forEach((interval) => {
+ const ma = this._movingAverages[key][interval] = MovingAverage(interval)
+ ma.push(this._frequencyLastTime, 0)
+ })
+ })
+
+ this._enabled = this._options.enabled
+ }
+
+ enable () {
+ this._enabled = true
+ }
+
+ disable () {
+ this._disabled = true
+ }
+
+ stop () {
+ if (this._timeout) {
+ clearTimeout(this._timeout)
+ }
+ }
+
+ get snapshot () {
+ return Object.assign({}, this._stats)
+ }
+
+ get movingAverages () {
+ return Object.assign({}, this._movingAverages)
+ }
+
+ push (counter, inc) {
+ if (this._enabled) {
+ this._queue.push([counter, inc, Date.now()])
+ this._resetComputeTimeout()
+ }
+ }
+
+ _resetComputeTimeout () {
+ if (this._timeout) {
+ clearTimeout(this._timeout)
+ }
+ this._timeout = setTimeout(this._update, this._nextTimeout())
+ }
+
+ _nextTimeout () {
+ // calculate the need for an update, depending on the queue length
+ const urgency = this._queue.length / this._options.computeThrottleMaxQueueSize
+ return Math.max(this._options.computeThrottleTimeout * (1 - urgency), 0)
+ }
+
+ _update () {
+ this._timeout = null
+ if (this._queue.length) {
+ let last
+ while (this._queue.length) {
+ const op = last = this._queue.shift()
+ this._applyOp(op)
+ }
+
+ this._updateFrequency(last[2]) // contains timestamp of last op
+
+ this.emit('update', this._stats)
+ }
+ }
+
+ _updateFrequency (latestTime) {
+ const timeDiff = latestTime - this._frequencyLastTime
+
+ Object.keys(this._stats).forEach((key) => {
+ this._updateFrequencyFor(key, timeDiff, latestTime)
+ })
+
+ this._frequencyLastTime = latestTime
+ }
+
+ _updateFrequencyFor (key, timeDiffMS, latestTime) {
+ const count = this._frequencyAccumulators[key] || 0
+ this._frequencyAccumulators[key] = 0
+ const hz = (count / timeDiffMS) * 1000
+
+ let movingAverages = this._movingAverages[key]
+ if (!movingAverages) {
+ movingAverages = this._movingAverages[key] = {}
+ }
+ this._options.movingAverageIntervals.forEach((movingAverageInterval) => {
+ let movingAverage = movingAverages[movingAverageInterval]
+ if (!movingAverage) {
+ movingAverage = movingAverages[movingAverageInterval] = MovingAverage(movingAverageInterval)
+ }
+ movingAverage.push(latestTime, hz)
+ })
+ }
+
+ _applyOp (op) {
+ const key = op[0]
+ const inc = op[1]
+
+ if (typeof inc !== 'number') {
+ throw new Error('invalid increment number:', inc)
+ }
+
+ let n
+
+ if (!this._stats.hasOwnProperty(key)) {
+ n = this._stats[key] = Big(0)
+ } else {
+ n = this._stats[key]
+ }
+ this._stats[key] = n.plus(inc)
+
+ if (!this._frequencyAccumulators[key]) {
+ this._frequencyAccumulators[key] = 0
+ }
+ this._frequencyAccumulators[key] += inc
+ }
+}
+
+module.exports = Stats
+
+},{"bignumber.js":328,"events":272,"moving-average":1135}],344:[function(require,module,exports){
+'use strict'
+
+const WantlistEntry = require('../wantlist').Entry
+const CID = require('cids')
+const assert = require('assert')
+
+module.exports = class BitswapMessageEntry {
+ constructor (cid, priority, cancel) {
+ assert(CID.isCID(cid), 'needs valid cid')
+ this.entry = new WantlistEntry(cid, priority)
+ this.cancel = Boolean(cancel)
+ }
+
+ get cid () {
+ return this.entry.cid
+ }
+
+ set cid (cid) {
+ this.entry.cid = cid
+ }
+
+ get priority () {
+ return this.entry.priority
+ }
+
+ set priority (val) {
+ this.entry.priority = val
+ }
+
+ get [Symbol.toStringTag] () {
+ const cidStr = this.cid.toString('base58btc')
+ return `BitswapMessageEntry ${cidStr} `
+ }
+
+ equals (other) {
+ return (this.cancel === other.cancel) &&
+ this.entry.equals(other.entry)
+ }
+}
+
+},{"../wantlist":348,"assert":26,"cids":185}],345:[function(require,module,exports){
+'use strict'
+
+const protons = require('protons')
+const Block = require('ipfs-block')
+const isEqualWith = require('lodash.isequalwith')
+const assert = require('assert')
+const each = require('async/each')
+const nextTick = require('async/nextTick')
+const CID = require('cids')
+const codecName = require('multicodec/src/name-table')
+const vd = require('varint-decoder')
+const multihashing = require('multihashing-async')
+
+const pbm = protons(require('./message.proto'))
+const Entry = require('./entry')
+
+class BitswapMessage {
+ constructor (full) {
+ this.full = full
+ this.wantlist = new Map()
+ this.blocks = new Map()
+ }
+
+ get empty () {
+ return this.blocks.size === 0 &&
+ this.wantlist.size === 0
+ }
+
+ addEntry (cid, priority, cancel) {
+ assert(cid && CID.isCID(cid), 'must be a valid cid')
+ const cidStr = cid.toString('base58btc')
+
+ const entry = this.wantlist.get(cidStr)
+
+ if (entry) {
+ entry.priority = priority
+ entry.cancel = Boolean(cancel)
+ } else {
+ this.wantlist.set(cidStr, new Entry(cid, priority, cancel))
+ }
+ }
+
+ addBlock (block) {
+ assert(Block.isBlock(block), 'must be a valid cid')
+ const cidStr = block.cid.toString('base58btc')
+ this.blocks.set(cidStr, block)
+ }
+
+ cancel (cid) {
+ assert(CID.isCID(cid), 'must be a valid cid')
+ const cidStr = cid.toString('base58btc')
+ this.wantlist.delete(cidStr)
+ this.addEntry(cid, 0, true)
+ }
+
+ /*
+ * Serializes to Bitswap Message protobuf of
+ * version 1.0.0
+ */
+ serializeToBitswap100 () {
+ const msg = {
+ wantlist: {
+ entries: Array.from(this.wantlist.values()).map((entry) => {
+ return {
+ block: entry.cid.buffer, // cid
+ priority: Number(entry.priority),
+ cancel: Boolean(entry.cancel)
+ }
+ })
+ },
+ blocks: Array.from(this.blocks.values())
+ .map((block) => block.data)
+ }
+
+ if (this.full) {
+ msg.wantlist.full = true
+ }
+
+ return pbm.Message.encode(msg)
+ }
+
+ /*
+ * Serializes to Bitswap Message protobuf of
+ * version 1.1.0
+ */
+ serializeToBitswap110 () {
+ const msg = {
+ wantlist: {
+ entries: Array.from(this.wantlist.values()).map((entry) => {
+ return {
+ block: entry.cid.buffer, // cid
+ priority: Number(entry.priority),
+ cancel: Boolean(entry.cancel)
+ }
+ })
+ },
+ payload: []
+ }
+
+ if (this.full) {
+ msg.wantlist.full = true
+ }
+
+ this.blocks.forEach((block) => {
+ msg.payload.push({
+ prefix: block.cid.prefix,
+ data: block.data
+ })
+ })
+
+ return pbm.Message.encode(msg)
+ }
+
+ equals (other) {
+ const cmp = (a, b) => {
+ if (a.equals && typeof a.equals === 'function') {
+ return a.equals(b)
+ }
+ }
+
+ if (this.full !== other.full ||
+ !isEqualWith(this.wantlist, other.wantlist, cmp) ||
+ !isEqualWith(this.blocks, other.blocks, cmp)
+ ) {
+ return false
+ }
+
+ return true
+ }
+
+ get [Symbol.toStringTag] () {
+ const list = Array.from(this.wantlist.keys())
+ const blocks = Array.from(this.blocks.keys())
+ return `BitswapMessage `
+ }
+}
+
+BitswapMessage.deserialize = (raw, callback) => {
+ let decoded
+ try {
+ decoded = pbm.Message.decode(raw)
+ } catch (err) {
+ return nextTick(() => callback(err))
+ }
+
+ const isFull = (decoded.wantlist && decoded.wantlist.full) || false
+ const msg = new BitswapMessage(isFull)
+
+ if (decoded.wantlist) {
+ decoded.wantlist.entries.forEach((entry) => {
+ // note: entry.block is the CID here
+ let cid
+ try {
+ cid = new CID(entry.block)
+ } catch (err) {
+ return callback(err)
+ }
+ msg.addEntry(cid, entry.priority, entry.cancel)
+ })
+ }
+
+ // Bitswap 1.0.0
+ // decoded.blocks are just the byte arrays
+ if (decoded.blocks.length > 0) {
+ return each(decoded.blocks, (b, cb) => {
+ multihashing(b, 'sha2-256', (err, hash) => {
+ if (err) {
+ return cb(err)
+ }
+ let cid
+ try {
+ cid = new CID(hash)
+ } catch (err) {
+ return callback(err)
+ }
+ msg.addBlock(new Block(b, cid))
+ cb()
+ })
+ }, (err) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, msg)
+ })
+ }
+
+ // Bitswap 1.1.0
+ if (decoded.payload.length > 0) {
+ return each(decoded.payload, (p, cb) => {
+ if (!p.prefix || !p.data) {
+ return nextTick(cb)
+ }
+ const values = vd(p.prefix)
+ const cidVersion = values[0]
+ const multicodec = values[1]
+ const hashAlg = values[2]
+ // const hashLen = values[3] // We haven't need to use this so far
+ multihashing(p.data, hashAlg, (err, hash) => {
+ if (err) {
+ return cb(err)
+ }
+
+ let cid
+ try {
+ cid = new CID(cidVersion, codecName[multicodec.toString('16')], hash)
+ } catch (err) {
+ return cb(err)
+ }
+
+ msg.addBlock(new Block(p.data, cid))
+ cb()
+ })
+ }, (err) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, msg)
+ })
+ }
+
+ callback(null, msg)
+}
+
+BitswapMessage.Entry = Entry
+module.exports = BitswapMessage
+
+},{"./entry":344,"./message.proto":346,"assert":26,"async/each":56,"async/nextTick":90,"cids":185,"ipfs-block":353,"lodash.isequalwith":1043,"multicodec/src/name-table":1152,"multihashing-async":334,"protons":1274,"varint-decoder":1518}],346:[function(require,module,exports){
+'use strict'
+
+// from: https://github.com/ipfs/go-ipfs/blob/master/exchange/bitswap/message/pb/message.proto
+
+module.exports = `
+ message Message {
+ message Wantlist {
+ message Entry {
+ // changed from string to bytes, it makes a difference in JavaScript
+ optional bytes block = 1; // the block cid (cidV0 in bitswap 1.0.0, cidV1 in bitswap 1.1.0)
+ optional int32 priority = 2; // the priority (normalized). default to 1
+ optional bool cancel = 3; // whether this revokes an entry
+ }
+
+ repeated Entry entries = 1; // a list of wantlist entries
+ optional bool full = 2; // whether this is the full wantlist. default to false
+ }
+
+ message Block {
+ optional bytes prefix = 1; // CID prefix (cid version, multicodec and multihash prefix (type + length)
+ optional bytes data = 2;
+ }
+
+ optional Wantlist wantlist = 1;
+ repeated bytes blocks = 2; // used to send Blocks in bitswap 1.0.0
+ repeated Block payload = 3; // used to send Blocks in bitswap 1.1.0
+ }
+`
+
+},{}],347:[function(require,module,exports){
+'use strict'
+
+const assert = require('assert')
+const CID = require('cids')
+
+class WantListEntry {
+ constructor (cid, priority) {
+ assert(CID.isCID(cid), 'must be valid CID')
+
+ // Keep track of how many requests we have for this key
+ this._refCounter = 1
+
+ this.cid = cid
+ this.priority = priority || 1
+ }
+
+ inc () {
+ this._refCounter += 1
+ }
+
+ dec () {
+ this._refCounter = Math.max(0, this._refCounter - 1)
+ }
+
+ hasRefs () {
+ return this._refCounter > 0
+ }
+
+ // So that console.log prints a nice description of this object
+ get [Symbol.toStringTag] () {
+ const cidStr = this.cid.toString('base58btc')
+ return `WantlistEntry `
+ }
+
+ equals (other) {
+ return (this._refCounter === other._refCounter) &&
+ this.cid.equals(other.cid) &&
+ this.priority === other.priority
+ }
+}
+
+module.exports = WantListEntry
+
+},{"assert":26,"cids":185}],348:[function(require,module,exports){
+'use strict'
+
+const { sortBy } = require('../../utils')
+const Entry = require('./entry')
+
+class Wantlist {
+ constructor (stats) {
+ this.set = new Map()
+ this._stats = stats
+ }
+
+ get length () {
+ return this.set.size
+ }
+
+ add (cid, priority) {
+ const cidStr = cid.toString('base58btc')
+ const entry = this.set.get(cidStr)
+
+ if (entry) {
+ entry.inc()
+ entry.priority = priority
+ } else {
+ this.set.set(cidStr, new Entry(cid, priority))
+ if (this._stats) {
+ this._stats.push(null, 'wantListSize', 1)
+ }
+ }
+ }
+
+ remove (cid) {
+ const cidStr = cid.toString('base58btc')
+ const entry = this.set.get(cidStr)
+
+ if (!entry) {
+ return
+ }
+
+ entry.dec()
+
+ // only delete when no refs are held
+ if (entry.hasRefs()) {
+ return
+ }
+
+ this.set.delete(cidStr)
+ if (this._stats) {
+ this._stats.push(null, 'wantListSize', -1)
+ }
+ }
+
+ removeForce (cidStr) {
+ if (this.set.has(cidStr)) {
+ this.set.delete(cidStr)
+ }
+ }
+
+ forEach (fn) {
+ return this.set.forEach(fn)
+ }
+
+ entries () {
+ return this.set.entries()
+ }
+
+ sortedEntries () {
+ return new Map(sortBy(o => o[1].key, Array.from(this.set.entries())))
+ }
+
+ contains (cid) {
+ const cidStr = cid.toString('base58btc')
+ return this.set.get(cidStr)
+ }
+}
+
+Wantlist.Entry = Entry
+module.exports = Wantlist
+
+},{"../../utils":349,"./entry":347}],349:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+
+/**
+ * Creates a logger for the given subsystem
+ *
+ * @param {PeerId} [id]
+ * @param {string} [subsystem]
+ * @returns {debug}
+ *
+ * @private
+ */
+const logger = (id, subsystem) => {
+ const name = ['bitswap']
+ if (subsystem) {
+ name.push(subsystem)
+ }
+ if (id) {
+ name.push(`${id.toB58String().slice(0, 8)}`)
+ }
+ const logger = debug(name.join(':'))
+ logger.error = debug(name.concat(['error']).join(':'))
+
+ return logger
+}
+
+const includesWith = (pred, x, list) => {
+ let idx = 0
+ const len = list.length
+ while (idx < len) {
+ if (pred(x, list[idx])) {
+ return true
+ }
+ idx += 1
+ }
+ return false
+}
+
+const uniqWith = (pred, list) => {
+ let idx = 0
+ const len = list.length
+ const result = []
+ let item
+
+ while (idx < len) {
+ item = list[idx]
+ if (!includesWith(pred, item, result)) {
+ result[result.length] = item
+ }
+ idx += 1
+ }
+ return result
+}
+
+const groupBy = (pred, list) => {
+ return list.reduce((acc, v) => {
+ const k = pred(v)
+
+ if (acc[k]) {
+ acc[k].push(v)
+ } else {
+ acc[k] = [v]
+ }
+ return acc
+ }, {})
+}
+
+const pullAllWith = (pred, list, values) => {
+ return list.filter(i => {
+ return !includesWith(pred, i, values)
+ })
+}
+
+const sortBy = (fn, list) => {
+ return Array.prototype.slice.call(list, 0).sort((a, b) => {
+ const aa = fn(a)
+ const bb = fn(b)
+ return aa < bb ? -1 : aa > bb ? 1 : 0
+ })
+}
+
+module.exports = {
+ logger,
+ includesWith,
+ uniqWith,
+ groupBy,
+ pullAllWith,
+ sortBy
+}
+
+},{"debug":329}],350:[function(require,module,exports){
+'use strict'
+
+const nextTick = require('async/nextTick')
+const Message = require('../types/message')
+const Wantlist = require('../types/wantlist')
+const CONSTANTS = require('../constants')
+const MsgQueue = require('./msg-queue')
+const logger = require('../utils').logger
+
+module.exports = class WantManager {
+ constructor (peerId, network, stats) {
+ this.peers = new Map()
+ this.wantlist = new Wantlist(stats)
+
+ this.network = network
+ this._stats = stats
+
+ this._peerId = peerId
+ this._log = logger(peerId, 'want')
+ }
+
+ _addEntries (cids, cancel, force) {
+ const entries = cids.map((cid, i) => {
+ return new Message.Entry(cid, CONSTANTS.kMaxPriority - i, cancel)
+ })
+
+ entries.forEach((e) => {
+ // add changes to our wantlist
+ if (e.cancel) {
+ if (force) {
+ this.wantlist.removeForce(e.cid)
+ } else {
+ this.wantlist.remove(e.cid)
+ }
+ } else {
+ this._log('adding to wl')
+ this.wantlist.add(e.cid, e.priority)
+ }
+ })
+
+ // broadcast changes
+ for (let p of this.peers.values()) {
+ p.addEntries(entries)
+ }
+ }
+
+ _startPeerHandler (peerId) {
+ let mq = this.peers.get(peerId.toB58String())
+
+ if (mq) {
+ mq.refcnt++
+ return
+ }
+
+ mq = new MsgQueue(this._peerId, peerId, this.network)
+
+ // new peer, give them the full wantlist
+ const fullwantlist = new Message(true)
+
+ for (let entry of this.wantlist.entries()) {
+ fullwantlist.addEntry(entry[1].cid, entry[1].priority)
+ }
+
+ mq.addMessage(fullwantlist)
+
+ this.peers.set(peerId.toB58String(), mq)
+ return mq
+ }
+
+ _stopPeerHandler (peerId) {
+ const mq = this.peers.get(peerId.toB58String())
+
+ if (!mq) {
+ return
+ }
+
+ mq.refcnt--
+ if (mq.refcnt > 0) {
+ return
+ }
+
+ this.peers.delete(peerId.toB58String())
+ }
+
+ // add all the cids to the wantlist
+ wantBlocks (cids) {
+ this._addEntries(cids, false)
+ }
+
+ // remove blocks of all the given keys without respecting refcounts
+ unwantBlocks (cids) {
+ this._log('unwant blocks: %s', cids.length)
+ this._addEntries(cids, true, true)
+ }
+
+ // cancel wanting all of the given keys
+ cancelWants (cids) {
+ this._log('cancel wants: %s', cids.length)
+ this._addEntries(cids, true)
+ }
+
+ // Returns a list of all currently connected peers
+ connectedPeers () {
+ return Array.from(this.peers.keys())
+ }
+
+ connected (peerId) {
+ this._startPeerHandler(peerId)
+ }
+
+ disconnected (peerId) {
+ this._stopPeerHandler(peerId)
+ }
+
+ start (callback) {
+ // resend entire wantlist every so often
+ this.timer = setInterval(() => {
+ this._log('resend full-wantlist')
+ const fullwantlist = new Message(true)
+ this.wantlist.forEach((entry) => {
+ fullwantlist.addEntry(entry.cid, entry.priority)
+ })
+
+ this.peers.forEach((p) => p.addMessage(fullwantlist))
+ }, 60 * 1000)
+
+ nextTick(() => callback())
+ }
+
+ stop (callback) {
+ this.peers.forEach((mq) => this.disconnected(mq.peerId))
+
+ clearInterval(this.timer)
+ nextTick(() => callback())
+ }
+}
+
+},{"../constants":336,"../types/message":345,"../types/wantlist":348,"../utils":349,"./msg-queue":351,"async/nextTick":90}],351:[function(require,module,exports){
+'use strict'
+
+const debounce = require('just-debounce-it')
+
+const Message = require('../types/message')
+const logger = require('../utils').logger
+
+module.exports = class MsgQueue {
+ constructor (selfPeerId, otherPeerId, network) {
+ this.peerId = otherPeerId
+ this.network = network
+ this.refcnt = 1
+
+ this._entries = []
+ this._log = logger(selfPeerId, 'msgqueue', otherPeerId.toB58String().slice(0, 8))
+ this.sendEntries = debounce(this._sendEntries.bind(this), 200)
+ }
+
+ addMessage (msg) {
+ if (msg.empty) {
+ return
+ }
+
+ this.send(msg)
+ }
+
+ addEntries (entries) {
+ this._entries = this._entries.concat(entries)
+ this.sendEntries()
+ }
+
+ _sendEntries () {
+ if (!this._entries.length) {
+ return
+ }
+
+ const msg = new Message(false)
+ this._entries.forEach((entry) => {
+ if (entry.cancel) {
+ msg.cancel(entry.cid)
+ } else {
+ msg.addEntry(entry.cid, entry.priority)
+ }
+ })
+ this._entries = []
+ this.addMessage(msg)
+ }
+
+ send (msg) {
+ this.network.connectTo(this.peerId, (err) => {
+ if (err) {
+ this._log.error('cant connect to peer %s: %s', this.peerId.toB58String(), err.message)
+ return
+ }
+
+ this._log('sending message')
+ this.network.sendMessage(this.peerId, msg, (err) => {
+ if (err) {
+ this._log.error('send error: %s', err.message)
+ }
+ })
+ })
+ }
+}
+
+},{"../types/message":345,"../utils":349,"just-debounce-it":668}],352:[function(require,module,exports){
+'use strict'
+
+const asyncMap = require('async/map')
+
+/**
+ * BlockService is a hybrid block datastore. It stores data in a local
+ * datastore and may retrieve data from a remote Exchange.
+ * It uses an internal `datastore.Datastore` instance to store values.
+ */
+class BlockService {
+ /**
+ * Create a new BlockService
+ *
+ * @param {IPFSRepo} ipfsRepo
+ */
+ constructor (ipfsRepo) {
+ this._repo = ipfsRepo
+ this._bitswap = null
+ }
+
+ /**
+ * Add a bitswap instance that communicates with the
+ * network to retreive blocks that are not in the local store.
+ *
+ * If the node is online all requests for blocks first
+ * check locally and afterwards ask the network for the blocks.
+ *
+ * @param {Bitswap} bitswap
+ * @returns {void}
+ */
+ setExchange (bitswap) {
+ this._bitswap = bitswap
+ }
+
+ /**
+ * Go offline, i.e. drop the reference to bitswap.
+ *
+ * @returns {void}
+ */
+ unsetExchange () {
+ this._bitswap = null
+ }
+
+ /**
+ * Is the blockservice online, i.e. is bitswap present.
+ *
+ * @returns {bool}
+ */
+ hasExchange () {
+ return this._bitswap != null
+ }
+
+ /**
+ * Put a block to the underlying datastore.
+ *
+ * @param {Block} block
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ put (block, callback) {
+ if (this.hasExchange()) {
+ this._bitswap.put(block, callback)
+ } else {
+ this._repo.blocks.put(block, callback)
+ }
+ }
+
+ /**
+ * Put a multiple blocks to the underlying datastore.
+ *
+ * @param {Array} blocks
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ putMany (blocks, callback) {
+ if (this.hasExchange()) {
+ this._bitswap.putMany(blocks, callback)
+ } else {
+ this._repo.blocks.putMany(blocks, callback)
+ }
+ }
+
+ /**
+ * Get a block by cid.
+ *
+ * @param {CID} cid
+ * @param {function(Error, Block)} callback
+ * @returns {void}
+ */
+ get (cid, callback) {
+ if (this.hasExchange()) {
+ this._bitswap.get(cid, callback)
+ } else {
+ this._repo.blocks.get(cid, callback)
+ }
+ }
+
+ /**
+ * Get multiple blocks back from an array of cids.
+ *
+ * @param {Array} cids
+ * @param {function(Error, Block)} callback
+ * @returns {void}
+ */
+ getMany (cids, callback) {
+ if (!Array.isArray(cids)) {
+ callback(new Error('first arg must be an array of cids'))
+ } else if (this.hasExchange()) {
+ this._bitswap.getMany(cids, callback)
+ } else {
+ asyncMap(cids, (cid, cb) => this._repo.blocks.get(cid, cb), callback)
+ }
+ }
+
+ /**
+ * Delete a block from the blockstore.
+ *
+ * @param {CID} cid
+ * @param {function(Error)} callback
+ * @return {void}
+ */
+ delete (cid, callback) {
+ this._repo.blocks.delete(cid, callback)
+ }
+}
+
+module.exports = BlockService
+
+},{"async/map":87}],353:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+const withIs = require('class-is')
+
+/**
+ * Represents an immutable block of data that is uniquely referenced with a cid.
+ *
+ * @constructor
+ * @param {Buffer} data - The data to be stored in the block as a buffer.
+ * @param {CID} cid - The cid of the data
+ *
+ * @example
+ * const block = new Block(new Buffer('a012d83b20f9371...'))
+ */
+class Block {
+ constructor (data, cid) {
+ if (!data || !Buffer.isBuffer(data)) {
+ throw new Error('first argument must be a buffer')
+ }
+
+ if (!cid || !CID.isCID(cid)) {
+ throw new Error('second argument must be a CID')
+ }
+
+ this._data = data
+ this._cid = cid
+ }
+
+ /**
+ * The data of this block.
+ *
+ * @type {Buffer}
+ */
+ get data () {
+ return this._data
+ }
+
+ set data (val) {
+ throw new Error('Tried to change an immutable block')
+ }
+
+ /**
+ * The cid of the data this block represents.
+ *
+ * @type {CID}
+ */
+ get cid () {
+ return this._cid
+ }
+
+ set cid (val) {
+ throw new Error('Tried to change an immutable block')
+ }
+}
+
+module.exports = withIs(Block, { className: 'Block', symbolName: '@ipfs/js-ipfs-block/block' })
+
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":608,"cids":185,"class-is":187}],354:[function(require,module,exports){
+'use strict'
+
+module.exports = require('./src/core')
+
+},{"./src/core":360}],355:[function(require,module,exports){
+arguments[4][208][0].apply(exports,arguments)
+},{"./common":356,"_process":1258,"dup":208}],356:[function(require,module,exports){
+arguments[4][209][0].apply(exports,arguments)
+},{"dup":209,"ms":1136}],357:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],358:[function(require,module,exports){
+'use strict'
+
+const mkdir = require('./mkdir')
+const stat = require('./stat')
+const log = require('debug')('ipfs:mfs:cp')
+const errCode = require('err-code')
+const updateTree = require('./utils/update-tree')
+const updateMfsRoot = require('./utils/update-mfs-root')
+const addLink = require('./utils/add-link')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const toMfsPath = require('./utils/to-mfs-path')
+const toSourcesAndDestination = require('./utils/to-sources-and-destination')
+const toTrail = require('./utils/to-trail')
+
+const defaultOptions = {
+ parents: false,
+ flush: true,
+ format: 'dag-pb',
+ hashAlg: 'sha2-256',
+ cidVersion: 0,
+ shardSplitThreshold: 1000
+}
+
+module.exports = (context) => {
+ return async function mfsCp (...args) {
+ const options = applyDefaultOptions(args, defaultOptions)
+ let {
+ sources, destination
+ } = await toSourcesAndDestination(context, args)
+
+ if (!sources.length) {
+ throw errCode(new Error('Please supply at least one source'), 'ERR_INVALID_PARAMS')
+ }
+
+ if (!destination) {
+ throw errCode(new Error('Please supply a destination'), 'ERR_INVALID_PARAMS')
+ }
+
+ options.parents = options.p || options.parents
+
+ // make sure all sources exist
+ const missing = sources.find(source => !source.exists)
+
+ if (missing) {
+ throw errCode(new Error(`${missing.path} does not exist`), 'ERR_INVALID_PARAMS')
+ }
+
+ const destinationIsDirectory = isDirectory(destination)
+
+ if (destination.exists) {
+ log('Destination exists')
+
+ if (sources.length === 1 && !destinationIsDirectory) {
+ throw errCode(new Error('directory already has entry by that name'), 'ERR_ALREADY_EXISTS')
+ }
+ } else {
+ log('Destination does not exist')
+
+ if (sources.length > 1) {
+ // copying multiple files to one location, destination will be a directory
+ if (!options.parents) {
+ throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')
+ }
+
+ await mkdir(context)(destination.path, options)
+ destination = await toMfsPath(context, destination.path)
+ } else if (destination.parts.length > 1) {
+ // copying to a folder, create it if necessary
+ const parentFolder = `/${destination.parts.slice(0, -1).join('/')}`
+
+ try {
+ await stat(context)(parentFolder, options)
+ } catch (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ throw err
+ }
+
+ if (!options.parents) {
+ throw errCode(new Error('destination did not exist, pass -p to create intermediate directories'), 'ERR_INVALID_PARAMS')
+ }
+
+ await mkdir(context)(parentFolder, options)
+ destination = await toMfsPath(context, destination.path)
+ }
+ }
+ }
+
+ const destinationPath = isDirectory(destination) ? destination.mfsPath : destination.mfsDirectory
+ const trail = await toTrail(context, destinationPath, options)
+
+ if (sources.length === 1) {
+ const source = sources.pop()
+ const destinationName = destinationIsDirectory ? source.name : destination.name
+
+ log(`Only one source, copying to destination ${destinationIsDirectory ? 'directory' : 'file'} ${destinationName}`)
+
+ return copyToFile(context, source, destinationName, trail, options)
+ }
+
+ log('Multiple sources, wrapping in a directory')
+ return copyToDirectory(context, sources, destination, trail, options)
+ }
+}
+
+const isDirectory = (destination) => {
+ return destination.unixfs &&
+ destination.unixfs.type &&
+ destination.unixfs.type.includes('directory')
+}
+
+const copyToFile = async (context, source, destination, destinationTrail, options) => {
+ let parent = destinationTrail.pop()
+
+ parent = await addSourceToParent(context, source, destination, parent, options)
+
+ // update the tree with the new containg directory
+ destinationTrail.push(parent)
+
+ const newRootCid = await updateTree(context, destinationTrail, options)
+
+ // Update the MFS record with the new CID for the root of the tree
+ await updateMfsRoot(context, newRootCid)
+}
+
+const copyToDirectory = async (context, sources, destination, destinationTrail, options) => {
+ // copy all the sources to the destination
+ for (let i = 0; i < sources.length; i++) {
+ const source = sources[i]
+
+ destination = await addSourceToParent(context, source, source.name, destination, options)
+ }
+
+ // update the tree with the new containg directory
+ destinationTrail[destinationTrail.length - 1] = destination
+
+ const newRootCid = await updateTree(context, destinationTrail, options)
+
+ // Update the MFS record with the new CID for the root of the tree
+ await updateMfsRoot(context, newRootCid)
+}
+
+const addSourceToParent = async (context, source, childName, parent, options) => {
+ const sourceBlock = await context.repo.blocks.get(source.cid)
+
+ const {
+ node,
+ cid
+ } = await addLink(context, {
+ parentCid: parent.cid,
+ size: sourceBlock.data.length,
+ cid: source.cid,
+ name: childName,
+ format: options.format,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion
+ })
+
+ parent.node = node
+ parent.cid = cid
+ parent.size = node.size
+
+ return parent
+}
+
+},{"./mkdir":362,"./stat":366,"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"./utils/to-sources-and-destination":377,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"debug":355,"err-code":357}],359:[function(require,module,exports){
+'use strict'
+
+const applyDefaultOptions = require('./utils/apply-default-options')
+const stat = require('./stat')
+const {
+ FILE_SEPARATOR
+} = require('./utils/constants')
+
+const defaultOptions = {}
+
+module.exports = (context) => {
+ return async function mfsFlush (path = FILE_SEPARATOR, options = defaultOptions) {
+ options = applyDefaultOptions(options, defaultOptions)
+
+ await stat(context)(path, options)
+ }
+}
+
+},{"./stat":366,"./utils/apply-default-options":368,"./utils/constants":369}],360:[function(require,module,exports){
+'use strict'
+
+const assert = require('assert')
+const promisify = require('promisify-es6')
+const createLock = require('./utils/create-lock')
+
+// These operations are read-locked at the function level and will execute simultaneously
+const readOperations = {
+ stat: require('./stat')
+}
+
+// These operations are locked at the function level and will execute in series
+const writeOperations = {
+ cp: require('./cp'),
+ flush: require('./flush'),
+ mkdir: require('./mkdir'),
+ mv: require('./mv'),
+ rm: require('./rm')
+}
+
+// These operations are asynchronous and manage their own locking
+const unwrappedOperations = {
+ write: require('./write'),
+ read: require('./read'),
+ ls: require('./ls')
+}
+
+const wrap = ({
+ options, mfs, operations, lock
+}) => {
+ Object.keys(operations).forEach(key => {
+ mfs[key] = lock(operations[key](options))
+ })
+}
+
+const defaultOptions = {
+ repoOwner: true,
+ ipld: null,
+ repo: null
+}
+
+module.exports = (options) => {
+ const {
+ repoOwner
+ } = Object.assign({}, defaultOptions || {}, options)
+
+ assert(options.ipld, 'MFS requires an IPLD instance')
+ assert(options.blocks, 'MFS requires an BlockStore instance')
+ assert(options.datastore, 'MFS requires a DataStore instance')
+
+ // should be able to remove this when async/await PRs are in for datastore, blockstore & repo
+ options.repo = {
+ blocks: {
+ get: promisify(options.blocks.get, {
+ context: options.blocks
+ })
+ },
+ datastore: {
+ open: promisify(options.datastore.open, {
+ context: options.datastore
+ }),
+ get: promisify(options.datastore.get, {
+ context: options.datastore
+ }),
+ put: promisify(options.datastore.put, {
+ context: options.datastore
+ })
+ }
+ }
+
+ const lock = createLock(repoOwner)
+
+ const readLock = (operation) => {
+ return lock.readLock(operation)
+ }
+
+ const writeLock = (operation) => {
+ return lock.writeLock(operation)
+ }
+
+ const mfs = {}
+
+ wrap({
+ options, mfs, operations: readOperations, lock: readLock
+ })
+ wrap({
+ options, mfs, operations: writeOperations, lock: writeLock
+ })
+
+ Object.keys(unwrappedOperations).forEach(key => {
+ mfs[key] = unwrappedOperations[key](options)
+ })
+
+ return mfs
+}
+
+},{"./cp":358,"./flush":359,"./ls":361,"./mkdir":362,"./mv":363,"./read":364,"./rm":365,"./stat":366,"./utils/create-lock":370,"./write":383,"assert":26,"promisify-es6":1263}],361:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const toMfsPath = require('./utils/to-mfs-path')
+const {
+ FILE_SEPARATOR,
+ FILE_TYPES
+} = require('./utils/constants')
+
+const defaultOptions = {
+
+}
+
+const toOutput = (fsEntry) => {
+ let type = 0
+ let size = fsEntry.node.size || fsEntry.node.length
+
+ if (fsEntry.unixfs) {
+ size = fsEntry.unixfs.fileSize()
+ type = FILE_TYPES[fsEntry.unixfs.type]
+ }
+
+ return {
+ cid: fsEntry.cid,
+ name: fsEntry.name,
+ type,
+ size
+ }
+}
+
+module.exports = (context) => {
+ return async function * mfsLs (path = FILE_SEPARATOR, options = {}) {
+ if (typeof path === 'object' && !(path instanceof String)) {
+ options = path
+ path = FILE_SEPARATOR
+ }
+
+ options = applyDefaultOptions(options, defaultOptions)
+
+ const mfsPath = await toMfsPath(context, path)
+ const fsDir = await exporter(mfsPath.mfsPath, context.ipld)
+
+ // single file/node
+ if (!fsDir.unixfs || !fsDir.unixfs.type.includes('directory')) {
+ yield toOutput(fsDir)
+
+ return
+ }
+
+ // directory, perhaps sharded
+ for await (const fsEntry of fsDir.content(options)) {
+ yield toOutput(fsEntry)
+ }
+ }
+}
+
+},{"./utils/apply-default-options":368,"./utils/constants":369,"./utils/to-mfs-path":375,"ipfs-unixfs-exporter":400}],362:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const log = require('debug')('ipfs:mfs:mkdir')
+const exporter = require('ipfs-unixfs-exporter')
+const createNode = require('./utils/create-node')
+const toPathComponents = require('./utils/to-path-components')
+const updateMfsRoot = require('./utils/update-mfs-root')
+const updateTree = require('./utils/update-tree')
+const addLink = require('./utils/add-link')
+const withMfsRoot = require('./utils/with-mfs-root')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const {
+ FILE_SEPARATOR
+} = require('./utils/constants')
+
+const defaultOptions = {
+ parents: false,
+ hashAlg: 'sha2-256',
+ cidVersion: 0,
+ shardSplitThreshold: 1000,
+ format: 'dag-pb',
+ flush: true
+}
+
+module.exports = (context) => {
+ return async function mfsMkdir (path, options) {
+ options = applyDefaultOptions(options, defaultOptions)
+
+ if (!path) {
+ throw new Error('no path given to Mkdir')
+ }
+
+ path = path.trim()
+
+ if (path === FILE_SEPARATOR) {
+ if (options.parents) {
+ return
+ }
+
+ throw errCode(new Error(`cannot create directory '${FILE_SEPARATOR}': Already exists`), 'ERR_INVALID_PATH')
+ }
+
+ if (path.substring(0, 1) !== FILE_SEPARATOR) {
+ throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH')
+ }
+
+ log(`Creating ${path}`)
+
+ const pathComponents = toPathComponents(path)
+
+ if (pathComponents[0] === 'ipfs') {
+ throw errCode(new Error("path cannot have the prefix 'ipfs'"), 'ERR_INVALID_PATH')
+ }
+
+ let root = await withMfsRoot(context)
+ let parent
+ let trail = []
+ const emptyDir = await createNode(context, 'directory', options)
+
+ // make sure the containing folder exists, creating it if necessary
+ for (let i = 0; i <= pathComponents.length; i++) {
+ const subPathComponents = pathComponents.slice(0, i)
+ const subPath = `/ipfs/${root}/${subPathComponents.join('/')}`
+
+ try {
+ parent = await exporter(subPath, context.ipld)
+ log(`${subPath} existed`)
+ log(`${subPath} had children ${parent.node.Links.map(link => link.Name)}`)
+
+ if (i === pathComponents.length) {
+ if (options.parents) {
+ return
+ }
+
+ throw errCode(new Error('file already exists'), 'ERR_ALREADY_EXISTS')
+ }
+
+ trail.push({
+ name: parent.name,
+ cid: parent.cid
+ })
+ } catch (err) {
+ if (err.code === 'ERR_NOT_FOUND') {
+ if (i < pathComponents.length && !options.parents) {
+ throw errCode(new Error(`Intermediate directory path ${subPath} does not exist, use the -p flag to create it`), 'ERR_NOT_FOUND')
+ }
+
+ // add the intermediate directory
+ await addEmptyDir(context, subPathComponents[subPathComponents.length - 1], emptyDir, trail[trail.length - 1], trail, options)
+ } else {
+ throw err
+ }
+ }
+ }
+
+ // add an empty dir to the last path component
+ // await addEmptyDir(context, pathComponents[pathComponents.length - 1], emptyDir, parent, trail)
+
+ // update the tree from the leaf to the root
+ const newRootCid = await updateTree(context, trail, options)
+
+ // Update the MFS record with the new CID for the root of the tree
+ await updateMfsRoot(context, newRootCid)
+ }
+}
+
+const addEmptyDir = async (context, childName, emptyDir, parent, trail, options) => {
+ log(`Adding empty dir called ${childName} to ${parent.cid}`)
+
+ const result = await addLink(context, {
+ parent: parent.node,
+ parentCid: parent.cid,
+ size: emptyDir.node.size,
+ cid: emptyDir.cid,
+ name: childName,
+ format: options.format,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion
+ })
+
+ trail[trail.length - 1].cid = result.cid
+
+ trail.push({
+ name: childName,
+ cid: emptyDir.cid
+ })
+}
+
+},{"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/constants":369,"./utils/create-node":371,"./utils/to-path-components":376,"./utils/update-mfs-root":380,"./utils/update-tree":381,"./utils/with-mfs-root":382,"debug":355,"err-code":357,"ipfs-unixfs-exporter":400}],363:[function(require,module,exports){
+'use strict'
+
+const applyDefaultOptions = require('./utils/apply-default-options')
+const toSources = require('./utils/to-sources')
+const cp = require('./cp')
+const rm = require('./rm')
+
+const defaultOptions = {
+ parents: false,
+ recursive: false,
+ flush: true,
+ format: 'dag-pb',
+ hashAlg: 'sha2-256',
+ shardSplitThreshold: 1000
+}
+
+module.exports = (context) => {
+ return async function mfsMv (...args) {
+ if (Array.isArray(args[0])) {
+ args = args[0].concat(args.slice(1))
+ }
+
+ const {
+ sources
+ } = await toSources(context, args)
+ const options = applyDefaultOptions(args, defaultOptions)
+
+ const cpArgs = sources
+ .map(source => source.path).concat(options)
+
+ // remove the last source as it'll be the destination
+ const rmArgs = sources
+ .slice(0, -1)
+ .map(source => source.path)
+ .concat(Object.assign(options, {
+ recursive: true
+ }))
+
+ await cp(context).apply(null, cpArgs)
+ await rm(context).apply(null, rmArgs)
+ }
+}
+
+},{"./cp":358,"./rm":365,"./utils/apply-default-options":368,"./utils/to-sources":378}],364:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const toMfsPath = require('./utils/to-mfs-path')
+const errCode = require('err-code')
+
+const defaultOptions = {
+ offset: 0,
+ length: Infinity
+}
+
+module.exports = (context) => {
+ return function mfsRead (path, options = {}) {
+ options = applyDefaultOptions(options, defaultOptions)
+
+ return {
+ [Symbol.asyncIterator]: async function * read () {
+ const mfsPath = await toMfsPath(context, path)
+ const result = await exporter(mfsPath.mfsPath, context.ipld)
+
+ if (result.unixfs.type !== 'file') {
+ throw errCode(new Error(`${path} was not a file`), 'ERR_NOT_FILE')
+ }
+
+ if (!result.content) {
+ throw errCode(new Error(`Could not load content stream from ${path}`), 'ERR_NO_CONTENT')
+ }
+
+ for await (const buf of result.content({
+ offset: options.offset,
+ length: options.length
+ })) {
+ yield buf
+ }
+ }
+ }
+ }
+}
+
+},{"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"err-code":357,"ipfs-unixfs-exporter":400}],365:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const updateTree = require('./utils/update-tree')
+const updateMfsRoot = require('./utils/update-mfs-root')
+const toSources = require('./utils/to-sources')
+const removeLink = require('./utils/remove-link')
+const toMfsPath = require('./utils/to-mfs-path')
+const toTrail = require('./utils/to-trail')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const {
+ FILE_SEPARATOR
+} = require('./utils/constants')
+
+const defaultOptions = {
+ recursive: false,
+ cidVersion: 0,
+ hashAlg: 'sha2-256',
+ format: 'dag-pb',
+ flush: true
+}
+
+module.exports = (context) => {
+ return async function mfsRm () {
+ const args = Array.from(arguments)
+
+ const {
+ sources
+ } = await toSources(context, args, defaultOptions)
+ const options = applyDefaultOptions(args, defaultOptions)
+
+ if (!sources.length) {
+ throw errCode(new Error('Please supply at least one path to remove'), 'ERR_INVALID_PARAMS')
+ }
+
+ sources.forEach(source => {
+ if (source.path === FILE_SEPARATOR) {
+ throw errCode(new Error('Cannot delete root'), 'ERR_INVALID_PARAMS')
+ }
+ })
+
+ for (const source of sources) {
+ await removePath(context, source.path, options)
+ }
+ }
+}
+
+const removePath = async (context, path, options) => {
+ const mfsPath = await toMfsPath(context, path)
+ const trail = await toTrail(context, mfsPath.mfsPath, options)
+ const child = trail.pop()
+ const parent = trail[trail.length - 1]
+
+ if (!parent) {
+ throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')
+ }
+
+ if (child.type === 'directory' && !options.recursive) {
+ throw errCode(new Error(`${path} is a directory, use -r to remove directories`), 'ERR_WAS_DIR')
+ }
+
+ const {
+ cid
+ } = await removeLink(context, {
+ parentCid: parent.cid,
+ name: child.name,
+ format: options.format,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion,
+ flush: options.flush
+ })
+
+ parent.cid = cid
+
+ // update the tree with the new child
+ const newRootCid = await updateTree(context, trail, options)
+
+ // Update the MFS record with the new CID for the root of the tree
+ await updateMfsRoot(context, newRootCid)
+}
+
+},{"./utils/apply-default-options":368,"./utils/constants":369,"./utils/remove-link":373,"./utils/to-mfs-path":375,"./utils/to-sources":378,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"err-code":357}],366:[function(require,module,exports){
+'use strict'
+
+const applyDefaultOptions = require('./utils/apply-default-options')
+const toMfsPath = require('./utils/to-mfs-path')
+const exporter = require('ipfs-unixfs-exporter')
+const log = require('debug')('ipfs:mfs:stat')
+const errCode = require('err-code')
+
+const defaultOptions = {
+ withLocal: false
+}
+
+module.exports = (context) => {
+ return async function mfsStat (path, options) {
+ options = applyDefaultOptions(options, defaultOptions)
+
+ log(`Fetching stats for ${path}`)
+
+ const {
+ type,
+ cid,
+ mfsPath
+ } = await toMfsPath(context, path)
+
+ let exportPath = type === 'ipfs' && cid ? cid : mfsPath
+ let file
+
+ try {
+ file = await exporter(exportPath, context.ipld)
+ } catch (err) {
+ if (err.code === 'ERR_NOT_FOUND') {
+ throw errCode(new Error(`${path} does not exist`), 'ERR_NOT_FOUND')
+ }
+
+ throw err
+ }
+
+ if (!statters[file.cid.codec]) {
+ throw new Error(`Cannot stat codec ${file.cid.codec}`)
+ }
+
+ return statters[file.cid.codec](file, options)
+ }
+}
+
+const statters = {
+ raw: (file) => {
+ return {
+ cid: file.cid,
+ size: file.node.length,
+ cumulativeSize: file.node.length,
+ blocks: 0,
+ type: 'file', // for go compatibility
+ local: undefined,
+ sizeLocal: undefined,
+ withLocality: false
+ }
+ },
+ 'dag-pb': (file) => {
+ let blocks = file.node.Links.length
+ let size = file.node.size
+ let cumulativeSize = file.node.size
+ let nodeType = null
+
+ if (file.unixfs) {
+ size = file.unixfs.fileSize()
+ nodeType = file.unixfs.type
+
+ if (nodeType.includes('directory')) {
+ size = 0
+ cumulativeSize = file.node.size
+ }
+
+ if (nodeType === 'file') {
+ blocks = file.unixfs.blockSizes.length
+ }
+ }
+
+ return {
+ cid: file.cid,
+ size: size,
+ cumulativeSize: cumulativeSize,
+ blocks: blocks,
+ type: nodeType,
+ local: undefined,
+ sizeLocal: undefined,
+ withLocality: false
+ }
+ },
+ 'dag-cbor': (file) => {
+ return {
+ cid: file.cid,
+ local: undefined,
+ sizeLocal: undefined,
+ withLocality: false
+ }
+ }
+}
+
+},{"./utils/apply-default-options":368,"./utils/to-mfs-path":375,"debug":355,"err-code":357,"ipfs-unixfs-exporter":400}],367:[function(require,module,exports){
+'use strict'
+
+const {
+ DAGNode,
+ DAGLink
+} = require('ipld-dag-pb')
+const CID = require('cids')
+const log = require('debug')('ipfs:mfs:core:utils:add-link')
+const UnixFS = require('ipfs-unixfs')
+const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded')
+const {
+ updateHamtDirectory,
+ recreateHamtLevel,
+ createShard,
+ toPrefix,
+ addLinksToHamtBucket
+} = require('./hamt-utils')
+const errCode = require('err-code')
+const mc = require('multicodec')
+const mh = require('multihashes')
+const last = require('async-iterator-last')
+
+const addLink = async (context, options) => {
+ if (!options.parentCid && !options.parent) {
+ throw errCode(new Error('No parent node or CID passed to addLink'), 'EINVALIDPARENT')
+ }
+
+ if (options.parentCid && !CID.isCID(options.parentCid)) {
+ throw errCode(new Error('Invalid CID passed to addLink'), 'EINVALIDPARENTCID')
+ }
+
+ if (!options.parent) {
+ log(`Loading parent node ${options.parentCid}`)
+
+ options.parent = await context.ipld.get(options.parentCid)
+ }
+
+ if (!options.cid) {
+ throw errCode(new Error('No child cid passed to addLink'), 'EINVALIDCHILDCID')
+ }
+
+ if (!options.name) {
+ throw errCode(new Error('No child name passed to addLink'), 'EINVALIDCHILDNAME')
+ }
+
+ if (!CID.isCID(options.cid)) {
+ options.cid = new CID(options.cid)
+ }
+
+ if (!options.size && options.size !== 0) {
+ throw errCode(new Error('No child size passed to addLink'), 'EINVALIDCHILDSIZE')
+ }
+
+ const meta = UnixFS.unmarshal(options.parent.Data)
+
+ if (meta.type === 'hamt-sharded-directory') {
+ log('Adding link to sharded directory')
+
+ return addToShardedDirectory(context, options)
+ }
+
+ if (options.parent.Links.length >= options.shardSplitThreshold) {
+ log('Converting directory to sharded directory')
+
+ return convertToShardedDirectory(context, options)
+ }
+
+ log(`Adding ${options.name} (${options.cid}) to regular directory`)
+
+ return addToDirectory(context, options)
+}
+
+const convertToShardedDirectory = async (context, options) => {
+ const result = await createShard(context, options.parent.Links.map(link => ({
+ name: link.Name,
+ size: link.Tsize,
+ cid: link.Hash
+ })).concat({
+ name: options.name,
+ size: options.size,
+ cid: options.cid
+ }), options)
+
+ log(`Converted directory to sharded directory ${result.cid}`)
+
+ return result
+}
+
+const addToDirectory = async (context, options) => {
+ let parent = await DAGNode.rmLink(options.parent, options.name)
+ parent = await DAGNode.addLink(parent, new DAGLink(options.name, options.size, options.cid))
+
+ const format = mc[options.format.toUpperCase().replace(/-/g, '_')]
+ const hashAlg = mh.names[options.hashAlg]
+
+ // Persist the new parent DAGNode
+ const cid = await context.ipld.put(parent, format, {
+ cidVersion: options.cidVersion,
+ hashAlg,
+ hashOnly: !options.flush
+ })
+
+ return {
+ node: parent,
+ cid
+ }
+}
+
+const addToShardedDirectory = async (context, options) => {
+ const {
+ shard, path
+ } = await addFileToShardedDirectory(context, options)
+
+ const result = await last(shard.flush('', context.ipld))
+
+ // we have written out the shard, but only one sub-shard will have been written so replace it in the original shard
+ const oldLink = options.parent.Links
+ .find(link => link.Name.substring(0, 2) === path[0].prefix)
+
+ const newLink = result.node.Links
+ .find(link => link.Name.substring(0, 2) === path[0].prefix)
+
+ let parent = options.parent
+
+ if (oldLink) {
+ parent = await DAGNode.rmLink(options.parent, oldLink.Name)
+ }
+
+ parent = await DAGNode.addLink(parent, newLink)
+
+ return updateHamtDirectory(context, parent.Links, path[0].bucket, options)
+}
+
+const addFileToShardedDirectory = async (context, options) => {
+ const file = {
+ name: options.name,
+ cid: options.cid,
+ size: options.size
+ }
+
+ // start at the root bucket and descend, loading nodes as we go
+ const rootBucket = await recreateHamtLevel(options.parent.Links)
+
+ const shard = new DirSharded({
+ root: true,
+ dir: true,
+ parent: null,
+ parentKey: null,
+ path: '',
+ dirty: true,
+ flat: false
+ }, options)
+ shard._bucket = rootBucket
+
+ // load subshards until the bucket & position no longer changes
+ const position = await rootBucket._findNewBucketAndPos(file.name)
+ const path = toBucketPath(position)
+ path[0].node = options.parent
+ let index = 0
+
+ while (index < path.length) {
+ let segment = path[index]
+ index++
+ let node = segment.node
+
+ let link = node.Links
+ .find(link => link.Name.substring(0, 2) === segment.prefix)
+
+ if (!link) {
+ // prefix is new, file will be added to the current bucket
+ log(`Link ${segment.prefix}${file.name} will be added`)
+ index = path.length
+
+ break
+ }
+
+ if (link.Name === `${segment.prefix}${file.name}`) {
+ // file already existed, file will be added to the current bucket
+ log(`Link ${segment.prefix}${file.name} will be replaced`)
+ index = path.length
+
+ break
+ }
+
+ if (link.Name.length > 2) {
+ // another file had the same prefix, will be replaced with a subshard
+ log(`Link ${link.Name} will be replaced with a subshard`)
+ index = path.length
+
+ break
+ }
+
+ // load sub-shard
+ log(`Found subshard ${segment.prefix}`)
+ const subShard = await context.ipld.get(link.Hash)
+
+ // subshard hasn't been loaded, descend to the next level of the HAMT
+ if (!path[index]) {
+ log(`Loaded new subshard ${segment.prefix}`)
+ await recreateHamtLevel(subShard.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))
+
+ const position = await rootBucket._findNewBucketAndPos(file.name)
+
+ path.push({
+ bucket: position.bucket,
+ prefix: toPrefix(position.pos),
+ node: subShard
+ })
+
+ break
+ }
+
+ const nextSegment = path[index]
+
+ // add next level's worth of links to bucket
+ await addLinksToHamtBucket(subShard.Links, nextSegment.bucket, rootBucket)
+
+ nextSegment.node = subShard
+ }
+
+ // finally add the new file into the shard
+ await shard._bucket.put(file.name, {
+ size: file.size,
+ cid: file.cid
+ })
+
+ return {
+ shard, path
+ }
+}
+
+const toBucketPath = (position) => {
+ let bucket = position.bucket
+ let positionInBucket = position.pos
+ let path = [{
+ bucket,
+ prefix: toPrefix(positionInBucket)
+ }]
+
+ bucket = position.bucket._parent
+ positionInBucket = position.bucket._posAtParent
+
+ while (bucket) {
+ path.push({
+ bucket,
+ prefix: toPrefix(positionInBucket)
+ })
+
+ positionInBucket = bucket._posAtParent
+ bucket = bucket._parent
+ }
+
+ path.reverse()
+
+ return path
+}
+
+module.exports = addLink
+
+},{"./hamt-utils":372,"async-iterator-last":33,"cids":185,"debug":355,"err-code":357,"ipfs-unixfs":435,"ipfs-unixfs-importer/src/dir-sharded":428,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],368:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+
+module.exports = (options = {}, defaults) => {
+ if (Array.isArray(options)) {
+ options = options.filter(arg => typeof arg === 'object').pop() || {}
+ }
+
+ const output = {}
+
+ for (let key in defaults) {
+ if (options[key] !== null && options[key] !== undefined) {
+ output[key] = options[key]
+ } else {
+ output[key] = defaults[key]
+ }
+ }
+
+ const format = output.format || output.codec
+
+ if (format && isNaN(format)) {
+ output.format = format
+ delete output.codec
+ }
+
+ // support legacy go arguments
+ if (options.count !== undefined) {
+ output.length = options.count
+ }
+
+ if (options.p !== undefined) {
+ output.parents = options.p
+ }
+
+ if (options.l !== undefined) {
+ output.long = options.l
+ }
+
+ if (!output.length && output.length !== 0) {
+ output.length = Infinity
+ }
+
+ if (output.offset < 0) {
+ throw errCode(new Error('cannot have negative write offset'), 'ERR_INVALID_PARAMS')
+ }
+
+ if (output.length < 0) {
+ throw errCode(new Error('cannot have negative byte count'), 'ERR_INVALID_PARAMS')
+ }
+
+ return output
+}
+
+},{"err-code":357}],369:[function(require,module,exports){
+'use strict'
+
+const Key = require('interface-datastore').Key
+
+const FILE_TYPES = {
+ file: 0,
+ directory: 1,
+ 'hamt-sharded-directory': 1
+}
+
+module.exports = {
+ FILE_SEPARATOR: '/',
+ MFS_ROOT_KEY: new Key('/local/filesroot'),
+ MAX_CHUNK_SIZE: 262144,
+ MAX_LINKS: 174,
+ FILE_TYPES
+}
+
+},{"interface-datastore":322}],370:[function(require,module,exports){
+'use strict'
+
+const mortice = require('mortice')
+
+let lock
+
+module.exports = (repoOwner) => {
+ if (lock) {
+ return lock
+ }
+
+ const mutex = mortice({
+ // ordinarily the main thread would store the read/write lock but
+ // if we are the thread that owns the repo, we can store the lock
+ // on this process even if we are a worker thread
+ singleProcess: repoOwner
+ })
+
+ lock = {
+ readLock: (func) => {
+ return async (...args) => {
+ const releaseLock = await mutex.readLock()
+
+ try {
+ return await func.apply(null, args)
+ } finally {
+ releaseLock()
+ }
+ }
+ },
+
+ writeLock: (func) => {
+ return async (...args) => {
+ const releaseLock = await mutex.writeLock()
+
+ try {
+ return await func.apply(null, args)
+ } finally {
+ releaseLock()
+ }
+ }
+ }
+ }
+
+ return lock
+}
+
+},{"mortice":1133}],371:[function(require,module,exports){
+'use strict'
+
+const UnixFS = require('ipfs-unixfs')
+const {
+ DAGNode
+} = require('ipld-dag-pb')
+const mc = require('multicodec')
+const mh = require('multihashes')
+
+const createNode = async (context, type, options) => {
+ const format = mc[options.format.toUpperCase().replace(/-/g, '_')]
+ const hashAlg = mh.names[options.hashAlg]
+
+ const node = DAGNode.create(new UnixFS(type).marshal())
+ const cid = await context.ipld.put(node, format, {
+ cidVersion: options.cidVersion,
+ hashAlg
+ })
+
+ return {
+ cid,
+ node
+ }
+}
+
+module.exports = createNode
+
+},{"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],372:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const {
+ DAGNode
+} = require('ipld-dag-pb')
+const Bucket = require('hamt-sharding/src/bucket')
+const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded')
+const log = require('debug')('ipfs:mfs:core:utils:hamt-utils')
+const UnixFS = require('ipfs-unixfs')
+const mc = require('multicodec')
+const mh = require('multihashes')
+const last = require('async-iterator-last')
+
+const updateHamtDirectory = async (context, links, bucket, options) => {
+ // update parent with new bit field
+ const data = Buffer.from(bucket._children.bitField().reverse())
+ const dir = new UnixFS('hamt-sharded-directory', data)
+ dir.fanout = bucket.tableSize()
+ dir.hashType = DirSharded.hashFn.code
+
+ const format = mc[options.format.toUpperCase().replace(/-/g, '_')]
+ const hashAlg = mh.names[options.hashAlg]
+
+ const parent = DAGNode.create(dir.marshal(), links)
+ const cid = await context.ipld.put(parent, format, {
+ cidVersion: options.cidVersion,
+ hashAlg,
+ hashOnly: !options.flush
+ })
+
+ return {
+ node: parent,
+ cid
+ }
+}
+
+const recreateHamtLevel = async (links, rootBucket, parentBucket, positionAtParent) => {
+ // recreate this level of the HAMT
+ const bucket = new Bucket({
+ hashFn: DirSharded.hashFn,
+ hash: parentBucket ? parentBucket._options.hash : undefined
+ }, parentBucket, positionAtParent)
+
+ if (parentBucket) {
+ parentBucket._putObjectAt(positionAtParent, bucket)
+ }
+
+ await addLinksToHamtBucket(links, bucket, rootBucket)
+
+ return bucket
+}
+
+const addLinksToHamtBucket = async (links, bucket, rootBucket) => {
+ await Promise.all(
+ links.map(link => {
+ if (link.Name.length === 2) {
+ const pos = parseInt(link.Name, 16)
+
+ bucket._putObjectAt(pos, new Bucket({
+ hashFn: DirSharded.hashFn
+ }, bucket, pos))
+
+ return Promise.resolve()
+ }
+
+ return (rootBucket || bucket).put(link.Name.substring(2), {
+ size: link.TSize,
+ cid: link.Hash
+ })
+ })
+ )
+}
+
+const toPrefix = (position) => {
+ return position
+ .toString('16')
+ .toUpperCase()
+ .padStart(2, '0')
+ .substring(0, 2)
+}
+
+const generatePath = async (context, fileName, rootNode) => {
+ // start at the root bucket and descend, loading nodes as we go
+ const rootBucket = await recreateHamtLevel(rootNode.Links, null, null, null)
+ const position = await rootBucket._findNewBucketAndPos(fileName)
+
+ // the path to the root bucket
+ let path = [{
+ bucket: position.bucket,
+ prefix: toPrefix(position.pos)
+ }]
+ let currentBucket = position.bucket
+
+ while (currentBucket !== rootBucket) {
+ path.push({
+ bucket: currentBucket,
+ prefix: toPrefix(currentBucket._posAtParent)
+ })
+
+ currentBucket = currentBucket._parent
+ }
+
+ path.reverse()
+ path[0].node = rootNode
+
+ // load DAGNode for each path segment
+ for (let i = 0; i < path.length; i++) {
+ const segment = path[i]
+
+ // find prefix in links
+ const link = segment.node.Links
+ .filter(link => link.Name.substring(0, 2) === segment.prefix)
+ .pop()
+
+ // entry was not in shard
+ if (!link) {
+ // reached bottom of tree, file will be added to the current bucket
+ log(`Link ${segment.prefix}${fileName} will be added`)
+ // return path
+ continue
+ }
+
+ // found entry
+ if (link.Name === `${segment.prefix}${fileName}`) {
+ log(`Link ${segment.prefix}${fileName} will be replaced`)
+ // file already existed, file will be added to the current bucket
+ // return path
+ continue
+ }
+
+ // found subshard
+ log(`Found subshard ${segment.prefix}`)
+ const node = await context.ipld.get(link.Hash)
+
+ // subshard hasn't been loaded, descend to the next level of the HAMT
+ if (!path[i + 1]) {
+ log(`Loaded new subshard ${segment.prefix}`)
+
+ await recreateHamtLevel(node.Links, rootBucket, segment.bucket, parseInt(segment.prefix, 16))
+ const position = await rootBucket._findNewBucketAndPos(fileName)
+
+ // i--
+ path.push({
+ bucket: position.bucket,
+ prefix: toPrefix(position.pos),
+ node: node
+ })
+
+ continue
+ }
+
+ const nextSegment = path[i + 1]
+
+ // add intermediate links to bucket
+ await addLinksToHamtBucket(node.Links, nextSegment.bucket, rootBucket)
+
+ nextSegment.node = node
+ }
+
+ await rootBucket.put(fileName, true)
+
+ path.reverse()
+
+ return {
+ rootBucket,
+ path
+ }
+}
+
+const createShard = async (context, contents, options) => {
+ const shard = new DirSharded({
+ root: true,
+ dir: true,
+ parent: null,
+ parentKey: null,
+ path: '',
+ dirty: true,
+ flat: false
+ }, options)
+
+ for (let i = 0; i < contents.length; i++) {
+ await shard._bucket.put(contents[i].name, {
+ size: contents[i].size,
+ cid: contents[i].cid
+ })
+ }
+
+ return last(shard.flush('', context.ipld, null))
+}
+
+module.exports = {
+ generatePath,
+ updateHamtDirectory,
+ recreateHamtLevel,
+ addLinksToHamtBucket,
+ toPrefix,
+ createShard
+}
+
+}).call(this,require("buffer").Buffer)
+},{"async-iterator-last":33,"buffer":181,"debug":355,"hamt-sharding/src/bucket":286,"ipfs-unixfs":435,"ipfs-unixfs-importer/src/dir-sharded":428,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],373:[function(require,module,exports){
+'use strict'
+
+const {
+ DAGNode,
+ DAGLink
+} = require('ipld-dag-pb')
+const CID = require('cids')
+const log = require('debug')('ipfs:mfs:core:utils:remove-link')
+const UnixFS = require('ipfs-unixfs')
+const {
+ generatePath,
+ updateHamtDirectory
+} = require('./hamt-utils')
+const errCode = require('err-code')
+const mc = require('multicodec')
+const mh = require('multihashes')
+
+const removeLink = async (context, options) => {
+ if (!options.parentCid && !options.parent) {
+ throw errCode(new Error('No parent node or CID passed to removeLink'), 'EINVALIDPARENT')
+ }
+
+ if (options.parentCid && !CID.isCID(options.parentCid)) {
+ throw errCode(new Error('Invalid CID passed to removeLink'), 'EINVALIDPARENTCID')
+ }
+
+ if (!options.parent) {
+ log(`Loading parent node ${options.parentCid}`)
+
+ options.parent = await context.ipld.get(options.parentCid)
+ }
+
+ if (!options.name) {
+ throw errCode(new Error('No child name passed to removeLink'), 'EINVALIDCHILDNAME')
+ }
+
+ const meta = UnixFS.unmarshal(options.parent.Data)
+
+ if (meta.type === 'hamt-sharded-directory') {
+ log(`Removing ${options.name} from sharded directory`)
+
+ return removeFromShardedDirectory(context, options)
+ }
+
+ log(`Removing link ${options.name} regular directory`)
+
+ return removeFromDirectory(context, options)
+}
+
+const removeFromDirectory = async (context, options) => {
+ const format = mc[options.format.toUpperCase().replace(/-/g, '_')]
+ const hashAlg = mh.names[options.hashAlg]
+
+ const newParentNode = await DAGNode.rmLink(options.parent, options.name)
+ const cid = await context.ipld.put(newParentNode, format, {
+ cidVersion: options.cidVersion,
+ hashAlg
+ })
+
+ log(`Updated regular directory ${cid}`)
+
+ return {
+ node: newParentNode,
+ cid
+ }
+}
+
+const removeFromShardedDirectory = async (context, options) => {
+ const {
+ rootBucket, path
+ } = await generatePath(context, options.name, options.parent)
+
+ await rootBucket.del(options.name)
+
+ const {
+ node
+ } = await updateShard(context, path, {
+ name: options.name,
+ cid: options.cid,
+ size: options.size,
+ hashAlg: options.hashAlg,
+ format: options.format,
+ cidVersion: options.cidVersion,
+ flush: options.flush
+ }, options)
+
+ return updateHamtDirectory(context, node.Links, rootBucket, options)
+}
+
+const updateShard = async (context, positions, child, options) => {
+ const {
+ bucket,
+ prefix,
+ node
+ } = positions.pop()
+
+ const link = node.Links
+ .find(link => link.Name.substring(0, 2) === prefix)
+
+ if (!link) {
+ throw errCode(new Error(`No link found with prefix ${prefix} for file ${child.name}`), 'ERR_NOT_FOUND')
+ }
+
+ if (link.Name === `${prefix}${child.name}`) {
+ log(`Removing existing link ${link.Name}`)
+
+ const newNode = await DAGNode.rmLink(node, link.Name)
+
+ await bucket.del(child.name)
+
+ return updateHamtDirectory(context, newNode.Links, bucket, options)
+ }
+
+ log(`Descending into sub-shard ${link.Name} for ${prefix}${child.name}`)
+
+ const result = await updateShard(context, positions, child, options)
+
+ let newName = prefix
+
+ if (result.node.Links.length === 1) {
+ log(`Removing subshard for ${prefix}`)
+
+ // convert shard back to normal dir
+ result.cid = result.node.Links[0].Hash
+ result.node = result.node.Links[0]
+
+ newName = `${prefix}${result.node.Name.substring(2)}`
+ }
+
+ log(`Updating shard ${prefix} with name ${newName}`)
+
+ const size = DAGNode.isDAGNode(result.node) ? result.node.size : result.node.Tsize
+
+ return updateShardParent(context, bucket, node, prefix, newName, size, result.cid, options)
+}
+
+const updateShardParent = async (context, bucket, parent, oldName, newName, size, cid, options) => {
+ parent = await DAGNode.rmLink(parent, oldName)
+ parent = await DAGNode.addLink(parent, new DAGLink(newName, size, cid))
+
+ return updateHamtDirectory(context, parent.Links, bucket, options)
+}
+
+module.exports = removeLink
+
+},{"./hamt-utils":372,"cids":185,"debug":355,"err-code":357,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],374:[function(require,module,exports){
+(function (global,Buffer){
+'use strict'
+
+const errCode = require('err-code')
+const fs = require('fs')
+const log = require('debug')('ipfs:mfs:utils:to-async-iterator')
+const {
+ MAX_CHUNK_SIZE
+} = require('./constants')
+
+const toAsyncIterator = async (content) => {
+ if (!content) {
+ throw errCode(new Error('paths must start with a leading /'), 'ERR_INVALID_PATH')
+ }
+
+ if (typeof content === 'string' || content instanceof String) {
+ // Paths, node only
+ log('Content was a path')
+
+ return fs.createReadStream(content)
+ }
+
+ if (content.length) {
+ log('Content was array-like')
+
+ return {
+ [Symbol.asyncIterator]: async function * bufferContent () {
+ yield content
+ }
+ }
+ }
+
+ if (content[Symbol.asyncIterator]) {
+ log('Content was an async iterator')
+ return content
+ }
+
+ if (content[Symbol.iterator]) {
+ log('Content was an iterator')
+ return content
+ }
+
+ if (global.Blob && content instanceof global.Blob) {
+ // HTML5 Blob objects (including Files)
+ log('Content was an HTML5 Blob')
+
+ let index = 0
+
+ const iterator = {
+ next: async () => {
+ if (index > content.size) {
+ return {
+ done: true
+ }
+ }
+
+ return new Promise((resolve, reject) => {
+ const chunk = content.slice(index, MAX_CHUNK_SIZE)
+ index += MAX_CHUNK_SIZE
+
+ const reader = new global.FileReader()
+
+ const handleLoad = (ev) => {
+ reader.removeEventListener('loadend', handleLoad, false)
+
+ if (ev.error) {
+ return reject(ev.error)
+ }
+
+ resolve({
+ done: false,
+ value: Buffer.from(reader.result)
+ })
+ }
+
+ reader.addEventListener('loadend', handleLoad)
+ reader.readAsArrayBuffer(chunk)
+ })
+ }
+ }
+
+ return {
+ [Symbol.asyncIterator]: () => {
+ return iterator
+ }
+ }
+ }
+
+ throw errCode(new Error(`Don't know how to convert ${content} into an async iterator`), 'ERR_INVALID_PARAMS')
+}
+
+module.exports = toAsyncIterator
+
+}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
+},{"./constants":369,"buffer":181,"debug":355,"err-code":357,"fs":146}],375:[function(require,module,exports){
+'use strict'
+
+const {
+ FILE_SEPARATOR
+} = require('./constants')
+const loadMfsRoot = require('./with-mfs-root')
+const toPathComponents = require('./to-path-components')
+const exporter = require('ipfs-unixfs-exporter')
+const errCode = require('err-code')
+
+const IPFS_PREFIX = 'ipfs'
+
+const toMfsPath = async (context, path) => {
+ let outputArray = Array.isArray(path)
+ let paths = Array.isArray(path) ? path : [path]
+ const root = await loadMfsRoot(context)
+
+ paths = paths.map(path => {
+ path = (path || '').trim()
+ path = path.replace(/(\/\/+)/g, '/')
+
+ if (path.endsWith('/') && path.length > 1) {
+ path = path.substring(0, path.length - 1)
+ }
+
+ if (!path) {
+ throw errCode(new Error('paths must not be empty'), 'ERR_NO_PATH')
+ }
+
+ if (path.substring(0, 1) !== FILE_SEPARATOR) {
+ throw errCode(new Error(`paths must start with a leading ${FILE_SEPARATOR}`), 'ERR_INVALID_PATH')
+ }
+
+ if (path.substring(path.length - FILE_SEPARATOR.length) === FILE_SEPARATOR) {
+ path = path.substring(0, path.length - FILE_SEPARATOR.length)
+ }
+
+ const pathComponents = toPathComponents(path)
+
+ if (pathComponents[0] === IPFS_PREFIX) {
+ // e.g. /ipfs/QMfoo or /ipfs/Qmfoo/sub/path
+ let mfsDirectory
+
+ if (pathComponents.length === 2) {
+ mfsDirectory = `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`
+ } else {
+ mfsDirectory = `${FILE_SEPARATOR}${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}`
+ }
+
+ return {
+ type: 'ipfs',
+ depth: pathComponents.length - 2,
+
+ mfsPath: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`,
+ mfsDirectory,
+ parts: pathComponents,
+ path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`,
+ name: pathComponents[pathComponents.length - 1]
+ }
+ }
+
+ const mfsPath = `/${IPFS_PREFIX}/${root}${pathComponents.length ? '/' + pathComponents.join(FILE_SEPARATOR) : ''}`
+ const mfsDirectory = `/${IPFS_PREFIX}/${root}/${pathComponents.slice(0, pathComponents.length - 1).join(FILE_SEPARATOR)}`
+
+ return {
+ type: 'mfs',
+ depth: pathComponents.length,
+
+ mfsDirectory,
+ mfsPath,
+ parts: pathComponents,
+ path: `${FILE_SEPARATOR}${pathComponents.join(FILE_SEPARATOR)}`,
+ name: pathComponents[pathComponents.length - 1]
+ }
+ })
+
+ await Promise.all(
+ paths.map(async (path) => {
+ const cidPath = path.type === 'mfs' ? path.mfsPath : path.path
+
+ try {
+ const res = await exporter(cidPath, context.ipld)
+
+ path.cid = res.cid
+ path.mfsPath = `/ipfs/${res.path}`
+ path.unixfs = res.unixfs
+ path.content = res.content
+ } catch (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ throw err
+ }
+ }
+
+ path.exists = Boolean(path.cid)
+ })
+ )
+
+ if (outputArray) {
+ return paths
+ }
+
+ return paths[0]
+}
+
+module.exports = toMfsPath
+
+},{"./constants":369,"./to-path-components":376,"./with-mfs-root":382,"err-code":357,"ipfs-unixfs-exporter":400}],376:[function(require,module,exports){
+'use strict'
+
+const toPathComponents = (path = '') => {
+ // split on / unless escaped with \
+ return (path
+ .trim()
+ .match(/([^\\^/]|\\\/)+/g) || [])
+ .filter(Boolean)
+}
+
+module.exports = toPathComponents
+
+},{}],377:[function(require,module,exports){
+'use strict'
+
+const toSources = require('./to-sources')
+
+async function toSourcesAndDestination (context, args) {
+ const {
+ sources,
+ options
+ } = await toSources(context, args)
+
+ const destination = sources.pop()
+
+ return {
+ destination,
+ sources,
+ options
+ }
+}
+
+module.exports = toSourcesAndDestination
+
+},{"./to-sources":378}],378:[function(require,module,exports){
+'use strict'
+
+const toMfsPath = require('./to-mfs-path')
+
+async function toSources (context, args) {
+ // Support weird mfs.mv([source, dest], options, callback) signature
+ if (Array.isArray(args[0])) {
+ args = args[0]
+ }
+
+ const sources = args
+ .filter(arg => typeof arg === 'string')
+ .map(source => source.trim())
+
+ return {
+ sources: await toMfsPath(context, sources)
+ }
+}
+
+module.exports = toSources
+
+},{"./to-mfs-path":375}],379:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const log = require('debug')('ipfs:mfs:utils:to-trail')
+
+const toTrail = async (context, path) => {
+ log(`Creating trail for path ${path}`)
+
+ const output = []
+
+ for await (const fsEntry of exporter.path(path, context.ipld)) {
+ output.push({
+ name: fsEntry.name,
+ cid: fsEntry.cid,
+ size: fsEntry.node.size,
+ type: fsEntry.unixfs ? fsEntry.unixfs.type : undefined
+ })
+ }
+
+ return output
+}
+
+module.exports = toTrail
+
+},{"debug":355,"ipfs-unixfs-exporter":400}],380:[function(require,module,exports){
+'use strict'
+
+const log = require('debug')('ipfs:mfs:utils:update-mfs-root')
+const {
+ MFS_ROOT_KEY
+} = require('./constants')
+
+const updateMfsRoot = async (context, cid) => {
+ log(`New MFS root will be ${cid}`)
+
+ await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer)
+
+ return cid
+}
+
+module.exports = updateMfsRoot
+
+},{"./constants":369,"debug":355}],381:[function(require,module,exports){
+'use strict'
+
+const log = require('debug')('ipfs:mfs:utils:update-tree')
+const addLink = require('./add-link')
+
+const defaultOptions = {
+ shardSplitThreshold: 1000
+}
+
+// loop backwards through the trail, replacing links of all components to update CIDs
+const updateTree = async (context, trail, options) => {
+ options = Object.assign({}, defaultOptions, options)
+
+ log('Trail', trail)
+ trail = trail.slice().reverse()
+
+ let index = 0
+ let child
+
+ for await (const node of context.ipld.getMany(trail.map(node => node.cid))) {
+ const cid = trail[index].cid
+ const name = trail[index].name
+ index++
+
+ if (!child) {
+ child = {
+ cid,
+ name,
+ size: node.size
+ }
+
+ continue
+ }
+
+ const result = await addLink(context, {
+ parent: node,
+ name: child.name,
+ cid: child.cid,
+ size: child.size,
+ flush: options.flush,
+ shardSplitThreshold: options.shardSplitThreshold,
+ format: options.format,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion
+ })
+
+ // new child for next loop
+ child = {
+ cid: result.cid,
+ name,
+ size: result.node.size
+ }
+ }
+
+ log(`Final CID ${child.cid}`)
+
+ return child.cid
+}
+
+module.exports = updateTree
+
+},{"./add-link":367,"debug":355}],382:[function(require,module,exports){
+'use strict'
+
+const CID = require('cids')
+const UnixFs = require('ipfs-unixfs')
+const {
+ DAGNode
+} = require('ipld-dag-pb')
+const log = require('debug')('ipfs:mfs:utils:with-mfs-root')
+const mc = require('multicodec')
+const mh = require('multihashes')
+
+const {
+ MFS_ROOT_KEY
+} = require('./constants')
+
+const loadMfsRoot = async (context) => {
+ // Open the repo if it's been closed
+ await context.repo.datastore.open()
+
+ // Load the MFS root CID
+ let cid
+
+ try {
+ const buf = await context.repo.datastore.get(MFS_ROOT_KEY)
+
+ cid = new CID(buf)
+ } catch (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ throw err
+ }
+
+ log('Creating new MFS root')
+ const node = DAGNode.create(new UnixFs('directory').marshal())
+ cid = await context.ipld.put(node, mc.DAG_PB, {
+ cidVersion: 0,
+ hashAlg: mh.names['sha2-256'] // why can't ipld look this up?
+ })
+
+ await context.repo.datastore.put(MFS_ROOT_KEY, cid.buffer)
+ }
+
+ log(`Loaded MFS root /ipfs/${cid}`)
+
+ return cid
+}
+
+module.exports = loadMfsRoot
+
+},{"./constants":369,"cids":185,"debug":355,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157}],383:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const log = require('debug')('ipfs:mfs:write')
+const importer = require('ipfs-unixfs-importer')
+const stat = require('./stat')
+const mkdir = require('./mkdir')
+const addLink = require('./utils/add-link')
+const applyDefaultOptions = require('./utils/apply-default-options')
+const createLock = require('./utils/create-lock')
+const toAsyncIterator = require('./utils/to-async-iterator')
+const toMfsPath = require('./utils/to-mfs-path')
+const toPathComponents = require('./utils/to-path-components')
+const toTrail = require('./utils/to-trail')
+const updateTree = require('./utils/update-tree')
+const updateMfsRoot = require('./utils/update-mfs-root')
+const errCode = require('err-code')
+const {
+ MAX_CHUNK_SIZE
+} = require('./utils/constants')
+const last = require('async-iterator-last')
+
+const defaultOptions = {
+ offset: 0, // the offset in the file to begin writing
+ length: undefined, // how many bytes from the incoming buffer to write
+ create: false, // whether to create the file if it does not exist
+ truncate: false, // whether to truncate the file first
+ rawLeaves: false,
+ reduceSingleLeafToSelf: false,
+ cidVersion: 0,
+ hashAlg: 'sha2-256',
+ format: 'dag-pb',
+ parents: false, // whether to create intermediate directories if they do not exist
+ progress: () => {},
+ strategy: 'trickle',
+ flush: true,
+ leafType: 'raw',
+ shardSplitThreshold: 1000
+}
+
+module.exports = (context) => {
+ return async function mfsWrite (path, content, options) {
+ log('Hello world, writing', path, content, options)
+ options = applyDefaultOptions(options, defaultOptions)
+
+ let source, destination, parent
+ log('Reading source, destination and parent')
+ await createLock().readLock(async () => {
+ source = await toAsyncIterator(content, options)
+ destination = await toMfsPath(context, path)
+ parent = await toMfsPath(context, destination.mfsDirectory)
+ })()
+ log('Read source, destination and parent')
+ if (!options.parents && !parent.exists) {
+ throw errCode(new Error('directory does not exist'), 'ERR_NO_EXIST')
+ }
+
+ if (!options.create && !destination.exists) {
+ throw errCode(new Error('file does not exist'), 'ERR_NO_EXIST')
+ }
+
+ return updateOrImport(context, path, source, destination, options)
+ }
+}
+
+const updateOrImport = async (context, path, source, destination, options) => {
+ const child = await write(context, source, destination, options)
+
+ // The slow bit is done, now add or replace the DAGLink in the containing directory
+ // re-reading the path to the containing folder in case it has changed in the interim
+ await createLock().writeLock(async () => {
+ const pathComponents = toPathComponents(path)
+ const fileName = pathComponents.pop()
+ let parentExists = false
+
+ try {
+ await stat(context)(`/${pathComponents.join('/')}`, options)
+ parentExists = true
+ } catch (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ throw err
+ }
+ }
+
+ if (!parentExists) {
+ await mkdir(context)(`/${pathComponents.join('/')}`, options)
+ }
+
+ // get an updated mfs path in case the root changed while we were writing
+ const updatedPath = await toMfsPath(context, path)
+ const trail = await toTrail(context, updatedPath.mfsDirectory, options)
+ const parent = trail[trail.length - 1]
+
+ if (!parent.type.includes('directory')) {
+ throw errCode(new Error(`cannot write to ${parent.name}: Not a directory`), 'ERR_NOT_A_DIRECTORY')
+ }
+
+ const parentNode = await context.ipld.get(parent.cid)
+
+ const result = await addLink(context, {
+ parent: parentNode,
+ name: fileName,
+ cid: child.cid,
+ size: child.size,
+ flush: options.flush,
+ shardSplitThreshold: options.shardSplitThreshold,
+ format: options.format,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion
+ })
+
+ parent.cid = result.cid
+
+ // update the tree with the new child
+ const newRootCid = await updateTree(context, trail, options)
+
+ // Update the MFS record with the new CID for the root of the tree
+ await updateMfsRoot(context, newRootCid)
+ })()
+}
+
+const write = async (context, source, destination, options) => {
+ if (destination.exists) {
+ log(`Overwriting file ${destination.cid} offset ${options.offset} length ${options.length}`)
+ } else {
+ log(`Writing file offset ${options.offset} length ${options.length}`)
+ }
+
+ const sources = []
+
+ // pad start of file if necessary
+ if (options.offset > 0) {
+ if (destination.unixfs && destination.unixfs.fileSize() > options.offset) {
+ log(`Writing first ${options.offset} bytes of original file`)
+
+ sources.push(
+ () => {
+ return destination.content({
+ offset: 0,
+ length: options.offset
+ })
+ }
+ )
+ } else {
+ log(`Writing zeros for first ${options.offset} bytes`)
+ sources.push(
+ asyncZeroes(options.offset)
+ )
+ }
+ }
+
+ sources.push(
+ limitAsyncStreamBytes(source, options.length)
+ )
+
+ const content = countBytesStreamed(catAsyncInterators(sources), (bytesWritten) => {
+ if (destination.unixfs && !options.truncate) {
+ // if we've done reading from the new source and we are not going
+ // to truncate the file, add the end of the existing file to the output
+ const fileSize = destination.unixfs.fileSize()
+
+ if (fileSize > bytesWritten) {
+ log(`Writing last ${fileSize - bytesWritten} of ${fileSize} bytes from original file starting at offset ${bytesWritten}`)
+
+ return destination.content({
+ offset: bytesWritten
+ })
+ } else {
+ log(`Not writing last bytes from original file`)
+ }
+ }
+
+ return {
+ [Symbol.asyncIterator]: async function * () {}
+ }
+ })
+
+ let result = await last(importer([{
+ content: content
+ }], context.ipld, {
+ progress: options.progress,
+ hashAlg: options.hashAlg,
+ cidVersion: options.cidVersion,
+ strategy: options.strategy,
+ rawLeaves: options.rawLeaves,
+ reduceSingleLeafToSelf: options.reduceSingleLeafToSelf,
+ leafType: options.leafType
+ }))
+
+ log(`Wrote ${result.cid}`)
+
+ return {
+ cid: result.cid,
+ size: result.size
+ }
+}
+
+const limitAsyncStreamBytes = (stream, limit) => {
+ return async function * _limitAsyncStreamBytes () {
+ let emitted = 0
+
+ for await (const buf of stream) {
+ emitted += buf.length
+
+ if (emitted > limit) {
+ yield buf.slice(0, limit - emitted)
+
+ return
+ }
+
+ yield buf
+ }
+ }
+}
+
+const asyncZeroes = (count, chunkSize = MAX_CHUNK_SIZE) => {
+ const buf = Buffer.alloc(chunkSize, 0)
+
+ const stream = {
+ [Symbol.asyncIterator]: async function * _asyncZeroes () {
+ while (true) {
+ yield buf.slice()
+ }
+ }
+ }
+
+ return limitAsyncStreamBytes(stream, count)
+}
+
+const catAsyncInterators = async function * (sources) {
+ for (let i = 0; i < sources.length; i++) {
+ for await (const buf of sources[i]()) {
+ yield buf
+ }
+ }
+}
+
+const countBytesStreamed = async function * (source, notify) {
+ let wrote = 0
+
+ for await (const buf of source) {
+ wrote += buf.length
+
+ yield buf
+ }
+
+ for await (const buf of notify(wrote)) {
+ wrote += buf.length
+
+ yield buf
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./mkdir":362,"./stat":366,"./utils/add-link":367,"./utils/apply-default-options":368,"./utils/constants":369,"./utils/create-lock":370,"./utils/to-async-iterator":374,"./utils/to-mfs-path":375,"./utils/to-path-components":376,"./utils/to-trail":379,"./utils/update-mfs-root":380,"./utils/update-tree":381,"async-iterator-last":33,"buffer":181,"debug":355,"err-code":357,"ipfs-unixfs-importer":431}],384:[function(require,module,exports){
+arguments[4][328][0].apply(exports,arguments)
+},{"dup":328}],385:[function(require,module,exports){
+arguments[4][208][0].apply(exports,arguments)
+},{"./common":386,"_process":1258,"dup":208}],386:[function(require,module,exports){
+arguments[4][209][0].apply(exports,arguments)
+},{"dup":209,"ms":1136}],387:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const Key = require('interface-datastore').Key
+
+const apiFile = new Key('api')
+
+module.exports = (store) => {
+ return {
+ /**
+ * Get the current configuration from the repo.
+ *
+ * @param {function(Error, Object)} callback
+ * @returns {void}
+ */
+ get (callback) {
+ store.get(apiFile, (err, value) => callback(err, value && value.toString()))
+ },
+ /**
+ * Set the current configuration for this repo.
+ *
+ * @param {Object} value - the api address to be written
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ set (value, callback) {
+ store.put(apiFile, Buffer.from(value.toString()), callback)
+ },
+ /**
+ * Deletes api file
+ *
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ delete (callback) {
+ store.delete(apiFile, callback)
+ }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"interface-datastore":322}],388:[function(require,module,exports){
+'use strict'
+
+exports.create = function createBackend (name, path, options) {
+ const Ctor = options.storageBackends[name]
+ const backendOptions = Object.assign({}, options.storageBackendOptions[name] || {})
+ return new Ctor(path, backendOptions)
+}
+
+},{}],389:[function(require,module,exports){
+'use strict'
+
+const core = require('datastore-core')
+const ShardingStore = core.ShardingDatastore
+const Key = require('interface-datastore').Key
+const base32 = require('base32.js')
+const Block = require('ipfs-block')
+const setImmediate = require('async/setImmediate')
+const reject = require('async/reject')
+const CID = require('cids')
+const pull = require('pull-stream/pull')
+const collect = require('pull-stream/sinks/collect')
+
+/**
+ * Transform a raw buffer to a base32 encoded key.
+ *
+ * @param {Buffer} rawKey
+ * @returns {Key}
+ */
+const keyFromBuffer = (rawKey) => {
+ const enc = new base32.Encoder()
+ return new Key('/' + enc.write(rawKey).finalize(), false)
+}
+
+/**
+ * Transform a cid to the appropriate datastore key.
+ *
+ * @param {CID} cid
+ * @returns {Key}
+ */
+const cidToDsKey = (cid) => {
+ return keyFromBuffer(cid.buffer)
+}
+
+module.exports = (filestore, options, callback) => {
+ maybeWithSharding(filestore, options, (err, store) => {
+ if (err) { return callback(err) }
+
+ callback(null, createBaseStore(store))
+ })
+}
+
+function maybeWithSharding (filestore, options, callback) {
+ if (options.sharding) {
+ const shard = new core.shard.NextToLast(2)
+ ShardingStore.createOrOpen(filestore, shard, callback)
+ } else {
+ setImmediate(() => callback(null, filestore))
+ }
+}
+
+function createBaseStore (store) {
+ return {
+ /**
+ * Query the store.
+ *
+ * @param {object} query
+ * @param {function(Error, Array)} callback
+ * @return {void}
+ */
+ query (query, callback) {
+ pull(
+ store.query(query),
+ collect(callback)
+ )
+ },
+ /**
+ * Get a single block by CID.
+ *
+ * @param {CID} cid
+ * @param {function(Error, Block)} callback
+ * @returns {void}
+ */
+ get (cid, callback) {
+ if (!CID.isCID(cid)) {
+ return setImmediate(() => {
+ callback(new Error('Not a valid cid'))
+ })
+ }
+
+ const key = cidToDsKey(cid)
+ store.get(key, (err, blockData) => {
+ if (err) {
+ // If not found, we try with the other CID version.
+ // If exists, then store that block under the CID that was requested.
+ // Some duplication occurs.
+ if (err.code === 'ERR_NOT_FOUND') {
+ const otherCid = cidToOtherVersion(cid)
+ if (!otherCid) return callback(err)
+
+ const otherKey = cidToDsKey(otherCid)
+ return store.get(otherKey, (err, blockData) => {
+ if (err) return callback(err)
+
+ store.put(key, blockData, (err) => {
+ if (err) return callback(err)
+ callback(null, new Block(blockData, cid))
+ })
+ })
+ }
+
+ return callback(err)
+ }
+
+ callback(null, new Block(blockData, cid))
+ })
+ },
+ put (block, callback) {
+ if (!Block.isBlock(block)) {
+ return setImmediate(() => {
+ callback(new Error('invalid block'))
+ })
+ }
+
+ const k = cidToDsKey(block.cid)
+
+ store.has(k, (err, exists) => {
+ if (err) { return callback(err) }
+ if (exists) { return callback() }
+
+ store.put(k, block.data, callback)
+ })
+ },
+ /**
+ * Like put, but for more.
+ *
+ * @param {Array} blocks
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ putMany (blocks, callback) {
+ const keys = blocks.map((b) => ({
+ key: cidToDsKey(b.cid),
+ block: b
+ }))
+
+ const batch = store.batch()
+ reject(keys, (k, cb) => store.has(k.key, cb), (err, newKeys) => {
+ if (err) {
+ return callback(err)
+ }
+
+ newKeys.forEach((k) => {
+ batch.put(k.key, k.block.data)
+ })
+
+ batch.commit(callback)
+ })
+ },
+ /**
+ * Does the store contain block with this cid?
+ *
+ * @param {CID} cid
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ has (cid, callback) {
+ if (!CID.isCID(cid)) {
+ return setImmediate(() => {
+ callback(new Error('Not a valid cid'))
+ })
+ }
+
+ store.has(cidToDsKey(cid), (err, exists) => {
+ if (err) return callback(err)
+ if (exists) return callback(null, true)
+
+ // If not found, we try with the other CID version.
+ const otherCid = cidToOtherVersion(cid)
+ if (!otherCid) return callback(null, false)
+
+ store.has(cidToDsKey(otherCid), callback)
+ })
+ },
+ /**
+ * Delete a block from the store
+ *
+ * @param {CID} cid
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ delete (cid, callback) {
+ if (!CID.isCID(cid)) {
+ return setImmediate(() => {
+ callback(new Error('Not a valid cid'))
+ })
+ }
+
+ store.delete(cidToDsKey(cid), callback)
+ },
+
+ close (callback) {
+ store.close(callback)
+ }
+ }
+}
+
+function cidToOtherVersion (cid) {
+ try {
+ return cid.version === 0 ? cid.toV1() : cid.toV0()
+ } catch (err) {
+ return null
+ }
+}
+
+},{"async/reject":93,"async/setImmediate":96,"base32.js":107,"cids":185,"datastore-core":199,"interface-datastore":322,"ipfs-block":353,"pull-stream/pull":1312,"pull-stream/sinks/collect":1313}],390:[function(require,module,exports){
+'use strict'
+
+const Key = require('interface-datastore').Key
+const queue = require('async/queue')
+const waterfall = require('async/waterfall')
+const _get = require('dlv')
+const _set = require('just-safe-set')
+const Buffer = require('buffer').Buffer
+
+const configKey = new Key('config')
+
+module.exports = (store) => {
+ const setQueue = queue(_doSet, 1)
+
+ const configStore = {
+ /**
+ * Get the current configuration from the repo.
+ *
+ * @param {String} key - the config key to get
+ * @param {function(Error, Object)} callback
+ * @returns {void}
+ */
+ get (key, callback) {
+ if (typeof key === 'function') {
+ callback = key
+ key = undefined
+ }
+ if (!key) {
+ key = undefined
+ }
+ store.get(configKey, (err, encodedValue) => {
+ if (err) { return callback(err) }
+
+ let config
+ try {
+ config = JSON.parse(encodedValue.toString())
+ } catch (err) {
+ return callback(err)
+ }
+
+ if (typeof key === 'undefined') {
+ return callback(null, config)
+ }
+
+ if (typeof key !== 'string') {
+ return callback(new Error('Key ' + key + ' must be a string.'))
+ }
+
+ const value = _get(config, key, null)
+
+ if (value === null) {
+ return callback(new Error('Key ' + key + ' does not exist in config.'))
+ }
+
+ callback(null, value)
+ })
+ },
+ /**
+ * Set the current configuration for this repo.
+ *
+ * @param {String} key - the config key to be written
+ * @param {Object} value - the config value to be written
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ set (key, value, callback) {
+ if (typeof value === 'function') {
+ callback = value
+ value = key
+ key = undefined
+ } else if (!key || typeof key !== 'string') {
+ return callback(new Error('Invalid key type'))
+ }
+
+ if (value === undefined || Buffer.isBuffer(value)) {
+ return callback(new Error('Invalid value type'))
+ }
+
+ setQueue.push({
+ key: key,
+ value: value
+ }, callback)
+ },
+
+ /**
+ * Check if a config file exists.
+ *
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ exists (callback) {
+ store.has(configKey, callback)
+ }
+ }
+
+ return configStore
+
+ function _doSet (m, callback) {
+ const key = m.key
+ const value = m.value
+ if (key) {
+ waterfall(
+ [
+ (cb) => configStore.get(cb),
+ (config, cb) => {
+ _set(config, key, value)
+ cb(null, config)
+ },
+ _saveAll
+ ],
+ callback)
+ } else {
+ _saveAll(value, callback)
+ }
+ }
+
+ function _saveAll (config, callback) {
+ const buf = Buffer.from(JSON.stringify(config, null, 2))
+ store.put(configKey, buf, callback)
+ }
+}
+
+},{"async/queue":92,"async/waterfall":102,"buffer":181,"dlv":233,"interface-datastore":322,"just-safe-set":669}],391:[function(require,module,exports){
+'use strict'
+
+module.exports = {
+ repoVersion: 7
+}
+
+},{}],392:[function(require,module,exports){
+'use strict'
+
+// Default configuration for the datastore spec in node.js
+module.exports = {
+ Spec: {
+ type: 'mount',
+ mounts: [
+ {
+ mountpoint: '/blocks',
+ type: 'measure',
+ prefix: 'flatfs.datastore',
+ child: {
+ type: 'flatfs',
+ path: 'blocks',
+ sync: true,
+ shardFunc: '/repo/flatfs/shard/v1/next-to-last/2'
+ }
+ },
+ {
+ mountpoint: '/',
+ type: 'measure',
+ prefix: 'leveldb.datastore',
+ child: {
+ type: 'levelds',
+ path: 'datastore',
+ compression: 'none'
+ }
+ }
+ ]
+ }
+}
+
+},{}],393:[function(require,module,exports){
+'use strict'
+
+// Default configuration for a repo in the browser
+module.exports = {
+ lock: 'memory',
+ storageBackends: {
+ root: require('datastore-level'),
+ blocks: require('datastore-level'),
+ keys: require('datastore-level'),
+ datastore: require('datastore-level')
+ },
+ storageBackendOptions: {
+ root: {
+ extension: ''
+ },
+ blocks: {
+ sharding: false
+ },
+ keys: {
+ sharding: false
+ }
+ }
+}
+
+},{"datastore-level":207}],394:[function(require,module,exports){
+'use strict'
+
+exports.ERR_REPO_NOT_INITIALIZED = 'ERR_REPO_NOT_INITIALIZED'
+
+},{}],395:[function(require,module,exports){
+(function (setImmediate){
+'use strict'
+
+const waterfall = require('async/waterfall')
+const series = require('async/series')
+const parallel = require('async/parallel')
+const each = require('async/each')
+const _get = require('dlv')
+const assert = require('assert')
+const path = require('path')
+const debug = require('debug')
+const Big = require('bignumber.js')
+const pull = require('pull-stream/pull')
+const reduce = require('pull-stream/sinks/reduce')
+
+const backends = require('./backends')
+const version = require('./version')
+const config = require('./config')
+const spec = require('./spec')
+const apiAddr = require('./api-addr')
+const blockstore = require('./blockstore')
+const defaultOptions = require('./default-options')
+const defaultDatastore = require('./default-datastore')
+const ERRORS = require('./errors')
+
+const log = debug('repo')
+
+const noLimit = Number.MAX_SAFE_INTEGER
+
+const lockers = {
+ memory: require('./lock-memory'),
+ fs: require('./lock')
+}
+
+const repoVersion = require('./constants').repoVersion
+
+/**
+ * IpfsRepo implements all required functionality to read and write to an ipfs repo.
+ *
+ */
+class IpfsRepo {
+ /**
+ * @param {string} repoPath - path where the repo is stored
+ * @param {object} options - Configuration
+ */
+ constructor (repoPath, options) {
+ assert.strictEqual(typeof repoPath, 'string', 'missing repoPath')
+
+ this.options = buildOptions(options)
+ this.closed = true
+ this.path = repoPath
+
+ this._locker = this._getLocker()
+
+ this.root = backends.create('root', this.path, this.options)
+ this.version = version(this.root)
+ this.config = config(this.root)
+ this.spec = spec(this.root)
+ this.apiAddr = apiAddr(this.root)
+ }
+
+ /**
+ * Initialize a new repo.
+ *
+ * @param {Object} config - config to write into `config`.
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ init (config, callback) {
+ log('initializing at: %s', this.path)
+
+ series([
+ (cb) => this.root.open(ignoringAlreadyOpened(cb)),
+ (cb) => this.config.set(buildConfig(config), cb),
+ (cb) => this.spec.set(buildDatastoreSpec(config), cb),
+ (cb) => this.version.set(repoVersion, cb)
+ ], callback)
+ }
+
+ /**
+ * Open the repo. If the repo is already open no action will be taken.
+ * If the repo is not initialized it will return an error.
+ *
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ open (callback) {
+ if (!this.closed) {
+ setImmediate(() => callback(new Error('repo is already open')))
+ return // early
+ }
+ log('opening at: %s', this.path)
+
+ // check if the repo is already initialized
+ waterfall([
+ (cb) => this.root.open(ignoringAlreadyOpened(cb)),
+ (cb) => this._isInitialized(cb),
+ (cb) => this._openLock(this.path, cb),
+ (lck, cb) => {
+ log('aquired repo.lock')
+ this.lockfile = lck
+ cb()
+ },
+ (cb) => {
+ log('creating datastore')
+ this.datastore = backends.create('datastore', path.join(this.path, 'datastore'), this.options)
+ log('creating blocks')
+ const blocksBaseStore = backends.create('blocks', path.join(this.path, 'blocks'), this.options)
+ blockstore(
+ blocksBaseStore,
+ this.options.storageBackendOptions.blocks,
+ cb)
+ },
+ (blocks, cb) => {
+ this.blocks = blocks
+ cb()
+ },
+ (cb) => {
+ log('creating keystore')
+ this.keys = backends.create('keys', path.join(this.path, 'keys'), this.options)
+ cb()
+ },
+
+ (cb) => {
+ this.closed = false
+ log('all opened')
+ cb()
+ }
+ ], (err) => {
+ if (err && this.lockfile) {
+ this._closeLock((err2) => {
+ if (!err2) {
+ this.lockfile = null
+ } else {
+ log('error removing lock', err2)
+ }
+ callback(err)
+ })
+ } else {
+ callback(err)
+ }
+ })
+ }
+
+ /**
+ * Returns the repo locker to be used. Null will be returned if no locker is requested
+ *
+ * @private
+ * @returns {Locker}
+ */
+ _getLocker () {
+ if (typeof this.options.lock === 'string') {
+ assert(lockers[this.options.lock], 'Unknown lock type: ' + this.options.lock)
+ return lockers[this.options.lock]
+ }
+
+ assert(this.options.lock, 'No lock provided')
+ return this.options.lock
+ }
+
+ /**
+ * Creates a lock on the repo if a locker is specified. The lockfile object will
+ * be returned in the callback if one has been created.
+ *
+ * @param {string} path
+ * @param {function(Error, lockfile)} callback
+ * @returns {void}
+ */
+ _openLock (path, callback) {
+ this._locker.lock(path, (err, lockfile) => {
+ if (err) {
+ return callback(err, null)
+ }
+
+ assert.strictEqual(typeof lockfile.close, 'function', 'Locks must have a close method')
+ callback(null, lockfile)
+ })
+ }
+
+ /**
+ * Closes the lock on the repo
+ *
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ _closeLock (callback) {
+ if (this.lockfile) {
+ return this.lockfile.close(callback)
+ }
+ callback()
+ }
+
+ /**
+ * Check if the repo is already initialized.
+ *
+ * @private
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ _isInitialized (callback) {
+ log('init check')
+ parallel(
+ {
+ config: (cb) => this.config.exists(cb),
+ spec: (cb) => this.spec.exists(cb),
+ version: (cb) => this.version.check(repoVersion, cb)
+ },
+ (err, res) => {
+ log('init', err, res)
+ if (err && !res.config) {
+ return callback(Object.assign(new Error('repo is not initialized yet'),
+ {
+ code: ERRORS.ERR_REPO_NOT_INITIALIZED,
+ path: this.path
+ }))
+ }
+ callback(err)
+ }
+ )
+ }
+
+ /**
+ * Close the repo and cleanup.
+ *
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ close (callback) {
+ if (this.closed) {
+ return callback(new Error('repo is already closed'))
+ }
+
+ log('closing at: %s', this.path)
+ series([
+ (cb) => this.apiAddr.delete(ignoringNotFound(cb)),
+ (cb) => {
+ each(
+ [this.blocks, this.keys, this.datastore],
+ (store, callback) => store.close(callback),
+ cb)
+ },
+ (cb) => {
+ log('unlocking')
+ this.closed = true
+ this._closeLock(cb)
+ },
+ (cb) => {
+ this.lockfile = null
+ cb()
+ }
+ ], (err) => callback(err))
+ }
+
+ /**
+ * Check if a repo exists.
+ *
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ exists (callback) {
+ this.version.exists(callback)
+ }
+
+ /**
+ * Get repo status.
+ *
+ * @param {Object} options
+ * @param {Boolean} options.human
+ * @param {function(Error, Object)} callback
+ * @return {void}
+ */
+ stat (options, callback) {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = Object.assign({}, { human: false }, options)
+
+ parallel({
+ storageMax: (cb) => this.config.get('Datastore.StorageMax', (err, max) => {
+ if (err) {
+ cb(null, new Big(noLimit))
+ } else {
+ cb(null, new Big(max))
+ }
+ }),
+ version: (cb) => this.version.get(cb),
+ blocks: (cb) => this.blocks.query({}, (err, list) => {
+ list = list || []
+
+ const count = new Big(list.length)
+ let size = new Big(0)
+
+ list.forEach(block => {
+ size = size
+ .plus(block.value.byteLength)
+ .plus(block.key._buf.byteLength)
+ })
+
+ cb(err, {
+ count: count,
+ size: size
+ })
+ }),
+ datastore: (cb) => getSize(this.datastore, cb),
+ keys: (cb) => getSize(this.keys, cb)
+ }, (err, results) => {
+ if (err) return callback(err)
+
+ let size = results.blocks.size
+ .plus(results.datastore)
+ .plus(results.keys)
+
+ if (options.human) {
+ size = size.div(1048576)
+ }
+
+ callback(null, {
+ repoPath: this.path,
+ storageMax: results.storageMax,
+ version: results.version,
+ numObjects: results.blocks.count,
+ repoSize: size
+ })
+ })
+ }
+}
+
+function getSize (queryFn, callback) {
+ pull(
+ queryFn.query({}),
+ reduce((sum, block) => {
+ return sum
+ .plus(block.value.byteLength)
+ .plus(block.key._buf.byteLength)
+ }, new Big(0), callback))
+}
+
+module.exports = IpfsRepo
+module.exports.repoVersion = repoVersion
+module.exports.errors = ERRORS
+
+function ignoringIf (cond, cb) {
+ return (err) => {
+ cb(err && !cond(err) ? err : null)
+ }
+}
+function ignoringAlreadyOpened (cb) {
+ return ignoringIf((err) => err.message === 'Already open', cb)
+}
+
+function ignoringNotFound (cb) {
+ return ignoringIf((err) => {
+ return err && (err.code === ERRORS.ERR_REPO_NOT_INITIALIZED || err.message.startsWith('ENOENT'))
+ }, cb)
+}
+
+function buildOptions (_options) {
+ const options = Object.assign({}, defaultOptions, _options)
+
+ options.storageBackends = Object.assign(
+ {},
+ defaultOptions.storageBackends,
+ options.storageBackends)
+
+ options.storageBackendOptions = Object.assign(
+ {},
+ defaultOptions.storageBackendOptions,
+ options.storageBackendOptions)
+
+ return options
+}
+
+// TODO this should come from js-ipfs instead
+function buildConfig (_config) {
+ _config.datastore = Object.assign({}, defaultDatastore, _get(_config, 'datastore', {}))
+
+ return _config
+}
+
+function buildDatastoreSpec (_config) {
+ const spec = Object.assign({}, defaultDatastore.Spec, _get(_config, 'datastore.Spec', {}))
+
+ return {
+ type: spec.type,
+ mounts: spec.mounts.map((mounting) => ({
+ mountpoint: mounting.mountpoint,
+ type: mounting.child.type,
+ path: mounting.child.path,
+ shardFunc: mounting.child.shardFunc
+ }))
+ }
+}
+
+}).call(this,require("timers").setImmediate)
+},{"./api-addr":387,"./backends":388,"./blockstore":389,"./config":390,"./constants":391,"./default-datastore":392,"./default-options":393,"./errors":394,"./lock":396,"./lock-memory":396,"./spec":397,"./version":398,"assert":26,"async/each":56,"async/parallel":91,"async/series":95,"async/waterfall":102,"bignumber.js":384,"debug":385,"dlv":233,"path":1246,"pull-stream/pull":1312,"pull-stream/sinks/reduce":1320,"timers":1500}],396:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const setImmediate = require('async/setImmediate')
+
+const log = debug('repo:lock')
+
+const lockFile = 'repo.lock'
+
+const LOCKS = {}
+
+/**
+ * Lock the repo in the given dir.
+ *
+ * @param {string} dir
+ * @param {function(Error, lock)} callback
+ * @returns {void}
+ */
+exports.lock = (dir, callback) => {
+ const file = dir + '/' + lockFile
+ log('locking %s', file)
+ LOCKS[file] = true
+ const closer = {
+ close (cb) {
+ if (LOCKS[file]) {
+ delete LOCKS[file]
+ }
+ setImmediate(cb)
+ }
+ }
+ setImmediate(() => {
+ callback(null, closer)
+ })
+}
+
+/**
+ * Check if the repo in the given directory is locked.
+ *
+ * @param {string} dir
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+exports.locked = (dir, callback) => {
+ const file = dir + '/' + lockFile
+ log('checking lock: %s')
+
+ const locked = LOCKS[file]
+ setImmediate(() => {
+ callback(null, locked)
+ })
+}
+
+},{"async/setImmediate":96,"debug":385}],397:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const Key = require('interface-datastore').Key
+const sortKeys = require('sort-keys')
+
+const specKey = new Key('datastore_spec')
+
+module.exports = (store) => {
+ return {
+ /**
+ * Check if a datastore spec file exists.
+ *
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ exists (callback) {
+ store.has(specKey, callback)
+ },
+ /**
+ * Get the current datastore spec.
+ *
+ * @param {function(Error, number)} callback
+ * @returns {void}
+ */
+ get (callback) {
+ store.get(specKey, (err, buf) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, JSON.parse(buf.toString()))
+ })
+ },
+ /**
+ * Set the datastore spec of the repo, writing it to the underlying store.
+ *
+ * @param {number} spec
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ set (spec, callback) {
+ store.put(specKey, Buffer.from(JSON.stringify(sortKeys(spec, { deep: true }))), callback)
+ }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"interface-datastore":322,"sort-keys":1438}],398:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const Key = require('interface-datastore').Key
+const debug = require('debug')
+const log = debug('repo:version')
+
+const versionKey = new Key('version')
+
+module.exports = (store) => {
+ return {
+ /**
+ * Check if a version file exists.
+ *
+ * @param {function(Error, bool)} callback
+ * @returns {void}
+ */
+ exists (callback) {
+ store.has(versionKey, callback)
+ },
+ /**
+ * Get the current version.
+ *
+ * @param {function(Error, number)} callback
+ * @returns {void}
+ */
+ get (callback) {
+ store.get(versionKey, (err, buf) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, parseInt(buf.toString().trim(), 10))
+ })
+ },
+ /**
+ * Set the version of the repo, writing it to the underlying store.
+ *
+ * @param {number} version
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ set (version, callback) {
+ store.put(versionKey, Buffer.from(String(version)), callback)
+ },
+ /**
+ * Check the current version, and return an error on missmatch
+ * @param {number} expected
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ check (expected, callback) {
+ this.get((err, version) => {
+ if (err) {
+ return callback(err)
+ }
+ log('comparing version: %s and %s', version, expected)
+
+ // Version 6 and 7 are the same
+ // TODO: Clean up the compatibility logic. Repo feature detection would be ideal, or a better version schema
+ const compatibleVersion = (version === 6 && expected === 7) || (expected === 6 && version === 7)
+
+ if (version !== expected && !compatibleVersion) {
+ return callback(new Error(`ipfs repo needs migration: expected version v${expected}, found version v${version}`))
+ }
+ callback()
+ })
+ }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"debug":385,"interface-datastore":322}],399:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],400:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const errCode = require('err-code')
+const CID = require('cids')
+const resolve = require('./resolvers')
+const last = require('async-iterator-last')
+
+const toPathComponents = (path = '') => {
+ // split on / unless escaped with \
+ return (path
+ .trim()
+ .match(/([^\\^/]|\\\/)+/g) || [])
+ .filter(Boolean)
+}
+
+const cidAndRest = (path) => {
+ if (Buffer.isBuffer(path)) {
+ return {
+ cid: new CID(path),
+ toResolve: []
+ }
+ }
+
+ if (CID.isCID(path)) {
+ return {
+ cid: path,
+ toResolve: []
+ }
+ }
+
+ if (typeof path === 'string') {
+ if (path.indexOf('/ipfs/') === 0) {
+ path = path.substring(6)
+ }
+
+ const output = toPathComponents(path)
+
+ return {
+ cid: new CID(output[0]),
+ toResolve: output.slice(1)
+ }
+ }
+
+ throw errCode(new Error(`Unknown path type ${path}`), 'ERR_BAD_PATH')
+}
+
+const walkPath = async function * (path, ipld) {
+ let {
+ cid,
+ toResolve
+ } = cidAndRest(path)
+ let name = cid.toBaseEncodedString()
+ let entryPath = name
+ const startingDepth = toResolve.length
+
+ while (true) {
+ const result = await resolve(cid, name, entryPath, toResolve, startingDepth, ipld)
+
+ if (!result.entry && !result.next) {
+ throw errCode(new Error(`Could not resolve ${path}`), 'ERR_NOT_FOUND')
+ }
+
+ if (result.entry) {
+ yield result.entry
+ }
+
+ if (!result.next) {
+ return
+ }
+
+ // resolve further parts
+ toResolve = result.next.toResolve
+ cid = result.next.cid
+ name = result.next.name
+ entryPath = result.next.path
+ }
+}
+
+const exporter = (path, ipld) => {
+ return last(walkPath(path, ipld))
+}
+
+const recursive = async function * (path, ipld) {
+ const node = await exporter(path, ipld)
+
+ yield node
+
+ if (node.unixfs && node.unixfs.type.includes('dir')) {
+ for await (const child of recurse(node)) {
+ yield child
+ }
+ }
+
+ async function * recurse (node) {
+ for await (const file of node.content()) {
+ yield file
+
+ if (file.unixfs.type.includes('dir')) {
+ for await (const subFile of recurse(file)) {
+ yield subFile
+ }
+ }
+ }
+ }
+}
+
+module.exports = exporter
+module.exports.path = walkPath
+module.exports.recursive = recursive
+
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":608,"./resolvers":402,"async-iterator-last":33,"cids":185,"err-code":399}],401:[function(require,module,exports){
+'use strict'
+
+const CID = require('cids')
+const errCode = require('err-code')
+
+const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => {
+ let node = await ipld.get(cid)
+ let subObject = node
+ let subPath = path
+
+ while (toResolve.length) {
+ const prop = toResolve[0]
+
+ if (prop in subObject) {
+ // remove the bit of the path we have resolved
+ toResolve.shift()
+ subPath = `${subPath}/${prop}`
+
+ if (CID.isCID(subObject[prop])) {
+ return {
+ entry: {
+ name,
+ path,
+ cid,
+ node,
+ depth
+ },
+ next: {
+ cid: subObject[prop],
+ name: prop,
+ path: subPath,
+ toResolve
+ }
+ }
+ }
+
+ subObject = subObject[prop]
+ } else {
+ // cannot resolve further
+ throw errCode(new Error(`No property named ${prop} found in cbor node ${cid.toBaseEncodedString()}`), 'ERR_NO_PROP')
+ }
+ }
+
+ return {
+ entry: {
+ name,
+ path,
+ cid,
+ node,
+ depth
+ }
+ }
+}
+
+module.exports = resolve
+
+},{"cids":185,"err-code":399}],402:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+
+const resolvers = {
+ 'dag-pb': require('./unixfs-v1'),
+ raw: require('./raw'),
+ 'dag-cbor': require('./dag-cbor')
+}
+
+const resolve = (cid, name, path, toResolve, depth, ipld) => {
+ const resolver = resolvers[cid.codec]
+
+ if (!resolver) {
+ throw errCode(new Error(`No resolver for codec ${cid.codec}`), 'ERR_NO_RESOLVER')
+ }
+
+ return resolver(cid, name, path, toResolve, resolve, depth, ipld)
+}
+
+module.exports = resolve
+
+},{"./dag-cbor":401,"./raw":403,"./unixfs-v1":407,"err-code":399}],403:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const extractDataFromBlock = require('../utils/extract-data-from-block')
+const validateOffsetAndLength = require('../utils/validate-offset-and-length')
+
+const rawContent = (node) => {
+ return function * (options = {}) {
+ const {
+ offset,
+ length
+ } = validateOffsetAndLength(node.length, options.offset, options.length)
+
+ yield extractDataFromBlock(node, 0, offset, offset + length)
+ }
+}
+
+const resolve = async (cid, name, path, toResolve, resolve, depth, ipld) => {
+ if (toResolve.length) {
+ throw errCode(new Error(`No link named ${path} found in raw node ${cid.toBaseEncodedString()}`), 'ERR_NOT_FOUND')
+ }
+
+ const buf = await ipld.get(cid)
+
+ return {
+ entry: {
+ name,
+ path,
+ cid,
+ node: buf,
+ content: rawContent(buf),
+ depth
+ }
+ }
+}
+
+module.exports = resolve
+
+},{"../utils/extract-data-from-block":408,"../utils/validate-offset-and-length":410,"err-code":399}],404:[function(require,module,exports){
+'use strict'
+
+const directoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => {
+ return async function * (options = {}) {
+ const offset = options.offset || 0
+ const length = options.length || node.Links.length
+ const links = node.Links.slice(offset, length)
+
+ for (const link of links) {
+ const result = await resolve(link.Hash, link.Name, `${path}/${link.Name}`, [], depth + 1, ipld)
+
+ yield result.entry
+ }
+ }
+}
+
+module.exports = directoryContent
+
+},{}],405:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const extractDataFromBlock = require('../../../utils/extract-data-from-block')
+const validateOffsetAndLength = require('../../../utils/validate-offset-and-length')
+const UnixFS = require('ipfs-unixfs')
+const errCode = require('err-code')
+
+async function * emitBytes (ipld, node, start, end, streamPosition = 0) {
+ // a `raw` node
+ if (Buffer.isBuffer(node)) {
+ const buf = extractDataFromBlock(node, streamPosition, start, end)
+
+ if (buf.length) {
+ yield buf
+ }
+
+ streamPosition += buf.length
+
+ return streamPosition
+ }
+
+ let file
+
+ try {
+ file = UnixFS.unmarshal(node.Data)
+ } catch (err) {
+ throw errCode(err, 'ERR_NOT_UNIXFS')
+ }
+
+ // might be a unixfs `raw` node or have data on intermediate nodes
+ const nodeHasData = Boolean(file.data && file.data.length)
+
+ if (nodeHasData) {
+ const buf = extractDataFromBlock(file.data, streamPosition, start, end)
+
+ if (buf.length) {
+ yield buf
+ }
+
+ streamPosition += file.data.length
+ }
+
+ let childStart = streamPosition
+
+ // work out which child nodes contain the requested data
+ for (let i = 0; i < node.Links.length; i++) {
+ const childLink = node.Links[i]
+ const childEnd = streamPosition + file.blockSizes[i]
+
+ if ((start >= childStart && start < childEnd) || // child has offset byte
+ (end > childStart && end <= childEnd) || // child has end byte
+ (start < childStart && end > childEnd)) { // child is between offset and end bytes
+ const child = await ipld.get(childLink.Hash)
+
+ for await (const buf of emitBytes(ipld, child, start, end, streamPosition)) {
+ streamPosition += buf.length
+
+ yield buf
+ }
+ }
+
+ streamPosition = childEnd
+ childStart = childEnd + 1
+ }
+}
+
+const fileContent = (cid, node, unixfs, path, resolve, depth, ipld) => {
+ return (options = {}) => {
+ const fileSize = unixfs.fileSize()
+
+ const {
+ offset,
+ length
+ } = validateOffsetAndLength(fileSize, options.offset, options.length)
+
+ const start = offset
+ const end = offset + length
+
+ return emitBytes(ipld, node, start, end)
+ }
+}
+
+module.exports = fileContent
+
+}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
+},{"../../../../../is-buffer/index.js":608,"../../../utils/extract-data-from-block":408,"../../../utils/validate-offset-and-length":410,"err-code":399,"ipfs-unixfs":435}],406:[function(require,module,exports){
+'use strict'
+
+const hamtShardedDirectoryContent = (cid, node, unixfs, path, resolve, depth, ipld) => {
+ return (options = {}) => {
+ return listDirectory(node, path, resolve, depth, ipld, options)
+ }
+}
+
+async function * listDirectory (node, path, resolve, depth, ipld, options) {
+ const links = node.Links
+
+ for (const link of links) {
+ const name = link.Name.substring(2)
+
+ if (name) {
+ const result = await resolve(link.Hash, name, `${path}/${name}`, [], depth + 1, ipld)
+
+ yield result.entry
+ } else {
+ // descend into subshard
+ node = await ipld.get(link.Hash)
+
+ for await (const file of listDirectory(node, path, resolve, depth, ipld, options)) {
+ yield file
+ }
+ }
+ }
+}
+
+module.exports = hamtShardedDirectoryContent
+
+},{}],407:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const UnixFS = require('ipfs-unixfs')
+const findShardCid = require('../../utils/find-cid-in-shard')
+
+const findLinkCid = (node, name) => {
+ const link = node.Links.find(link => link.Name === name)
+
+ return link && link.Hash
+}
+
+const contentExporters = {
+ raw: require('./content/file'),
+ file: require('./content/file'),
+ directory: require('./content/directory'),
+ 'hamt-sharded-directory': require('./content/hamt-sharded-directory'),
+ metadata: (cid, node, unixfs, path, resolve, depth, ipld) => {},
+ symlink: (cid, node, unixfs, path, resolve, depth, ipld) => {}
+}
+
+const unixFsResolver = async (cid, name, path, toResolve, resolve, depth, ipld) => {
+ const node = await ipld.get(cid)
+ let unixfs
+ let next
+
+ if (!name) {
+ name = cid.toBaseEncodedString()
+ }
+
+ try {
+ unixfs = UnixFS.unmarshal(node.Data)
+ } catch (err) {
+ // non-UnixFS dag-pb node? It could happen.
+ throw errCode(err, 'ERR_NOT_UNIXFS')
+ }
+
+ if (!path) {
+ path = name
+ }
+
+ if (toResolve.length) {
+ let linkCid
+
+ if (unixfs && unixfs.type === 'hamt-sharded-directory') {
+ // special case - unixfs v1 hamt shards
+ linkCid = await findShardCid(node, toResolve[0], ipld)
+ } else {
+ linkCid = findLinkCid(node, toResolve[0])
+ }
+
+ if (!linkCid) {
+ throw errCode(new Error(`file does not exist`), 'ERR_NOT_FOUND')
+ }
+
+ // remove the path component we have resolved
+ const nextName = toResolve.shift()
+ const nextPath = `${path}/${nextName}`
+
+ next = {
+ cid: linkCid,
+ toResolve,
+ name: nextName,
+ path: nextPath
+ }
+ }
+
+ return {
+ entry: {
+ name,
+ path,
+ cid,
+ node,
+ content: contentExporters[unixfs.type](cid, node, unixfs, path, resolve, depth, ipld),
+ unixfs,
+ depth
+ },
+ next
+ }
+}
+
+module.exports = unixFsResolver
+
+},{"../../utils/find-cid-in-shard":409,"./content/directory":404,"./content/file":405,"./content/hamt-sharded-directory":406,"err-code":399,"ipfs-unixfs":435}],408:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+module.exports = function extractDataFromBlock (block, blockStart, requestedStart, requestedEnd) {
+ const blockLength = block.length
+ const blockEnd = blockStart + blockLength
+
+ if (requestedStart >= blockEnd || requestedEnd < blockStart) {
+ // If we are looking for a byte range that is starts after the start of the block,
+ // return an empty block. This can happen when internal nodes contain data
+ return Buffer.alloc(0)
+ }
+
+ if (requestedEnd >= blockStart && requestedEnd < blockEnd) {
+ // If the end byte is in the current block, truncate the block to the end byte
+ block = block.slice(0, requestedEnd - blockStart)
+ }
+
+ if (requestedStart >= blockStart && requestedStart < blockEnd) {
+ // If the start byte is in the current block, skip to the start byte
+ block = block.slice(requestedStart - blockStart)
+ }
+
+ return block
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181}],409:[function(require,module,exports){
+'use strict'
+
+const Bucket = require('hamt-sharding/src/bucket')
+const DirSharded = require('ipfs-unixfs-importer/src/dir-sharded')
+
+const addLinksToHamtBucket = (links, bucket, rootBucket) => {
+ return Promise.all(
+ links.map(link => {
+ if (link.Name.length === 2) {
+ const pos = parseInt(link.Name, 16)
+
+ return bucket._putObjectAt(pos, new Bucket({
+ hashFn: DirSharded.hashFn
+ }, bucket, pos))
+ }
+
+ return rootBucket.put(link.Name.substring(2), true)
+ })
+ )
+}
+
+const toPrefix = (position) => {
+ return position
+ .toString('16')
+ .toUpperCase()
+ .padStart(2, '0')
+ .substring(0, 2)
+}
+
+const toBucketPath = (position) => {
+ let bucket = position.bucket
+ const path = []
+
+ while (bucket._parent) {
+ path.push(bucket)
+
+ bucket = bucket._parent
+ }
+
+ path.push(bucket)
+
+ return path.reverse()
+}
+
+const findShardCid = async (node, name, ipld, context) => {
+ if (!context) {
+ context = {
+ rootBucket: new Bucket({
+ hashFn: DirSharded.hashFn
+ }),
+ hamtDepth: 1
+ }
+
+ context.lastBucket = context.rootBucket
+ }
+
+ await addLinksToHamtBucket(node.Links, context.lastBucket, context.rootBucket)
+
+ const position = await context.rootBucket._findNewBucketAndPos(name)
+ let prefix = toPrefix(position.pos)
+ const bucketPath = toBucketPath(position)
+
+ if (bucketPath.length > (context.hamtDepth)) {
+ context.lastBucket = bucketPath[context.hamtDepth]
+
+ prefix = toPrefix(context.lastBucket._posAtParent)
+ }
+
+ const link = node.Links.find(link => {
+ const entryPrefix = link.Name.substring(0, 2)
+ const entryName = link.Name.substring(2)
+
+ if (entryPrefix !== prefix) {
+ // not the entry or subshard we're looking for
+ return
+ }
+
+ if (entryName && entryName !== name) {
+ // not the entry we're looking for
+ return
+ }
+
+ return true
+ })
+
+ if (!link) {
+ return null
+ }
+
+ if (link.Name.substring(2) === name) {
+ return link.Hash
+ }
+
+ context.hamtDepth++
+
+ node = await ipld.get(link.Hash)
+
+ return findShardCid(node, name, ipld, context)
+}
+
+module.exports = findShardCid
+
+},{"hamt-sharding/src/bucket":286,"ipfs-unixfs-importer/src/dir-sharded":428}],410:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+
+const validateOffsetAndLength = (size, offset, length) => {
+ if (!offset) {
+ offset = 0
+ }
+
+ if (offset < 0) {
+ throw errCode(new Error('Offset must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')
+ }
+
+ if (offset > size) {
+ throw errCode(new Error('Offset must be less than the file size'), 'ERR_INVALID_PARAMS')
+ }
+
+ if (!length && length !== 0) {
+ length = size - offset
+ }
+
+ if (length < 0) {
+ throw errCode(new Error('Length must be greater than or equal to 0'), 'ERR_INVALID_PARAMS')
+ }
+
+ if (offset + length > size) {
+ length = size - offset
+ }
+
+ return {
+ offset,
+ length
+ }
+}
+
+module.exports = validateOffsetAndLength
+
+},{"err-code":399}],411:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],412:[function(require,module,exports){
+'use strict'
+
+const { Buffer } = require('buffer')
+const blake = require('blakejs')
+
+const minB = 0xb201
+const minS = 0xb241
+
+const blake2b = {
+ init: blake.blake2bInit,
+ update: blake.blake2bUpdate,
+ digest: blake.blake2bFinal
+}
+
+const blake2s = {
+ init: blake.blake2sInit,
+ update: blake.blake2sUpdate,
+ digest: blake.blake2sFinal
+}
+
+// Note that although this function doesn't do any asynchronous work, we mark
+// the function as async because it must return a Promise to match the API
+// for other functions that do perform asynchronous work (see sha.browser.js)
+const makeB2Hash = (size, hf) => async (data) => {
+ const ctx = hf.init(size, null)
+ hf.update(ctx, data)
+ return Buffer.from(hf.digest(ctx))
+}
+
+module.exports = (table) => {
+ for (let i = 0; i < 64; i++) {
+ table[minB + i] = makeB2Hash(i + 1, blake2b)
+ }
+ for (let i = 0; i < 32; i++) {
+ table[minS + i] = makeB2Hash(i + 1, blake2s)
+ }
+}
+
+},{"blakejs":132,"buffer":181}],413:[function(require,module,exports){
+'use strict'
+
+const { Buffer } = require('buffer')
+const sha3 = require('js-sha3')
+const mur = require('murmurhash3js-revisited')
+const sha = require('./sha')
+const { fromNumberTo32BitBuf } = require('./utils')
+
+// Note that although this function doesn't do any asynchronous work, we mark
+// the function as async because it must return a Promise to match the API
+// for other functions that do perform asynchronous work (see sha.browser.js)
+const hash = (algorithm) => async (data) => {
+ switch (algorithm) {
+ case 'sha3-224':
+ return Buffer.from(sha3.sha3_224.arrayBuffer(data))
+ case 'sha3-256':
+ return Buffer.from(sha3.sha3_256.arrayBuffer(data))
+ case 'sha3-384':
+ return Buffer.from(sha3.sha3_384.arrayBuffer(data))
+ case 'sha3-512':
+ return Buffer.from(sha3.sha3_512.arrayBuffer(data))
+ case 'shake-128':
+ return Buffer.from(sha3.shake128.create(128).update(data).arrayBuffer())
+ case 'shake-256':
+ return Buffer.from(sha3.shake256.create(256).update(data).arrayBuffer())
+ case 'keccak-224':
+ return Buffer.from(sha3.keccak224.arrayBuffer(data))
+ case 'keccak-256':
+ return Buffer.from(sha3.keccak256.arrayBuffer(data))
+ case 'keccak-384':
+ return Buffer.from(sha3.keccak384.arrayBuffer(data))
+ case 'keccak-512':
+ return Buffer.from(sha3.keccak512.arrayBuffer(data))
+ case 'murmur3-128':
+ return Buffer.from(mur.x64.hash128(data), 'hex')
+ case 'murmur3-32':
+ return fromNumberTo32BitBuf(mur.x86.hash32(data))
+
+ default:
+ throw new TypeError(`${algorithm} is not a supported algorithm`)
+ }
+}
+
+module.exports = {
+ sha1: sha('sha1'),
+ sha2256: sha('sha2-256'),
+ sha2512: sha('sha2-512'),
+ dblSha2256: sha('dbl-sha2-256'),
+ sha3224: hash('sha3-224'),
+ sha3256: hash('sha3-256'),
+ sha3384: hash('sha3-384'),
+ sha3512: hash('sha3-512'),
+ shake128: hash('shake-128'),
+ shake256: hash('shake-256'),
+ keccak224: hash('keccak-224'),
+ keccak256: hash('keccak-256'),
+ keccak384: hash('keccak-384'),
+ keccak512: hash('keccak-512'),
+ murmur3128: hash('murmur3-128'),
+ murmur332: hash('murmur3-32'),
+ addBlake: require('./blake')
+}
+
+},{"./blake":412,"./sha":415,"./utils":416,"buffer":181,"js-sha3":666,"murmurhash3js-revisited":1177}],414:[function(require,module,exports){
+'use strict'
+
+const { Buffer } = require('buffer')
+const errcode = require('err-code')
+const multihash = require('multihashes')
+const crypto = require('./crypto')
+
+/**
+ * Hash the given `buf` using the algorithm specified by `alg`.
+ * @param {Buffer} buf - The value to hash.
+ * @param {number|string} alg - The algorithm to use eg 'sha1'
+ * @param {number} [length] - Optionally trim the result to this length.
+ * @returns {Promise}
+ */
+async function Multihashing (buf, alg, length) {
+ const digest = await Multihashing.digest(buf, alg, length)
+ return multihash.encode(digest, alg, length)
+}
+
+/**
+ * The `buffer` module for easy use in the browser.
+ *
+ * @type {Buffer}
+ */
+Multihashing.Buffer = Buffer // for browser things
+
+/**
+ * Expose multihash itself, to avoid silly double requires.
+ */
+Multihashing.multihash = multihash
+
+/**
+ * @param {Buffer} buf - The value to hash.
+ * @param {number|string} alg - The algorithm to use eg 'sha1'
+ * @param {number} [length] - Optionally trim the result to this length.
+ * @returns {Promise}
+ */
+Multihashing.digest = async (buf, alg, length) => {
+ const hash = Multihashing.createHash(alg)
+ const digest = await hash(buf)
+ return length ? digest.slice(0, length) : digest
+}
+
+/**
+ * Creates a function that hashes with the given algorithm
+ *
+ * @param {string|number} alg - The algorithm to use eg 'sha1'
+ *
+ * @returns {function} - The hash function corresponding to `alg`
+ */
+Multihashing.createHash = function (alg) {
+ if (!alg) {
+ throw errcode('hash algorithm must be specified', 'ERR_HASH_ALGORITHM_NOT_SPECIFIED')
+ }
+
+ alg = multihash.coerceCode(alg)
+ if (!Multihashing.functions[alg]) {
+ throw errcode(`multihash function '${alg}' not yet supported`, 'ERR_HASH_ALGORITHM_NOT_SUPPORTED')
+ }
+
+ return Multihashing.functions[alg]
+}
+
+/**
+ * Mapping of multihash codes to their hashing functions.
+ * @type {Object}
+ */
+Multihashing.functions = {
+ // sha1
+ 0x11: crypto.sha1,
+ // sha2-256
+ 0x12: crypto.sha2256,
+ // sha2-512
+ 0x13: crypto.sha2512,
+ // sha3-512
+ 0x14: crypto.sha3512,
+ // sha3-384
+ 0x15: crypto.sha3384,
+ // sha3-256
+ 0x16: crypto.sha3256,
+ // sha3-224
+ 0x17: crypto.sha3224,
+ // shake-128
+ 0x18: crypto.shake128,
+ // shake-256
+ 0x19: crypto.shake256,
+ // keccak-224
+ 0x1A: crypto.keccak224,
+ // keccak-256
+ 0x1B: crypto.keccak256,
+ // keccak-384
+ 0x1C: crypto.keccak384,
+ // keccak-512
+ 0x1D: crypto.keccak512,
+ // murmur3-128
+ 0x22: crypto.murmur3128,
+ // murmur3-32
+ 0x23: crypto.murmur332,
+ // dbl-sha2-256
+ 0x56: crypto.dblSha2256
+}
+
+// add blake functions
+crypto.addBlake(Multihashing.functions)
+
+Multihashing.validate = async (buf, hash) => {
+ const newHash = await Multihashing(buf, multihash.decode(hash).name)
+
+ return Buffer.compare(hash, newHash) === 0
+}
+
+module.exports = Multihashing
+
+},{"./crypto":413,"buffer":181,"err-code":411,"multihashes":1157}],415:[function(require,module,exports){
+'use strict'
+
+const { Buffer } = require('buffer')
+
+const crypto = self.crypto || self.msCrypto
+
+module.exports = (algorithm) => {
+ if (typeof self === 'undefined' || (!self.crypto && !self.msCrypto)) {
+ throw new Error(
+ 'Please use a browser with webcrypto support and ensure the code has been delivered securely via HTTPS/TLS and run within a Secure Context'
+ )
+ }
+
+ return async (data) => {
+ switch (algorithm) {
+ case 'sha1':
+ return Buffer.from(await crypto.subtle.digest({ name: 'SHA-1' }, data))
+ case 'sha2-256':
+ return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, data))
+ case 'sha2-512':
+ return Buffer.from(await crypto.subtle.digest({ name: 'SHA-512' }, data))
+ case 'dbl-sha2-256': {
+ const d = await crypto.subtle.digest({ name: 'SHA-256' }, data)
+ return Buffer.from(await crypto.subtle.digest({ name: 'SHA-256' }, d))
+ }
+ default:
+ throw new Error(`${algorithm} is not a supported algorithm`)
+ }
+ }
+}
+
+},{"buffer":181}],416:[function(require,module,exports){
+'use strict'
+
+const { Buffer } = require('buffer')
+
+const fromNumberTo32BitBuf = (number) => {
+ const bytes = new Array(4)
+
+ for (let i = 0; i < 4; i++) {
+ bytes[i] = number & 0xff
+ number = number >> 8
+ }
+
+ return Buffer.from(bytes)
+}
+
+module.exports = {
+ fromNumberTo32BitBuf
+}
+
+},{"buffer":181}],417:[function(require,module,exports){
+'use strict'
+
+const BufferList = require('bl')
+
+module.exports = async function * fixedSizeChunker (source, options) {
+ let bl = new BufferList()
+ let currentLength = 0
+ let emitted = false
+ const maxChunkSize = options.maxChunkSize
+
+ for await (const buffer of source) {
+ bl.append(buffer)
+
+ currentLength += buffer.length
+
+ while (currentLength >= maxChunkSize) {
+ yield bl.slice(0, maxChunkSize)
+ emitted = true
+
+ // throw away consumed bytes
+ if (maxChunkSize === bl.length) {
+ bl = new BufferList()
+ currentLength = 0
+ } else {
+ const newBl = new BufferList()
+ newBl.append(bl.shallowSlice(maxChunkSize))
+ bl = newBl
+
+ // update our offset
+ currentLength -= maxChunkSize
+ }
+ }
+ }
+
+ if (!emitted || currentLength) {
+ // return any remaining bytes or an empty buffer
+ yield bl.slice(0, currentLength)
+ }
+}
+
+},{"bl":112}],418:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+
+const chunkers = {
+ fixed: require('../chunker/fixed-size'),
+ rabin: require('../chunker/rabin')
+}
+
+module.exports = (type, source, options) => {
+ const chunker = chunkers[type]
+
+ if (!chunker) {
+ throw errCode(new Error(`Unknkown chunker named ${type}`), 'ERR_UNKNOWN_CHUNKER')
+ }
+
+ return chunker(source, options)
+}
+
+},{"../chunker/fixed-size":417,"../chunker/rabin":419,"err-code":411}],419:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const BufferList = require('bl')
+const { create } = require('rabin-wasm')
+const errcode = require('err-code')
+
+module.exports = async function * rabinChunker (source, options) {
+ const rabin = jsRabin()
+
+ let min, max, avg
+
+ if (options.minChunkSize && options.maxChunkSize && options.avgChunkSize) {
+ avg = options.avgChunkSize
+ min = options.minChunkSize
+ max = options.maxChunkSize
+ } else if (!options.avgChunkSize) {
+ throw errcode(new Error('please specify an average chunk size'), 'ERR_INVALID_AVG_CHUNK_SIZE')
+ } else {
+ avg = options.avgChunkSize
+ min = avg / 3
+ max = avg + (avg / 2)
+ }
+
+ // validate min/max/avg in the same way as go
+ if (min < 16) {
+ throw errcode(new Error('rabin min must be greater than 16'), 'ERR_INVALID_MIN_CHUNK_SIZE')
+ }
+
+ if (max < min) {
+ max = min
+ }
+
+ if (avg < min) {
+ avg = min
+ }
+
+ const sizepow = Math.floor(Math.log2(avg))
+
+ for await (const chunk of rabin(source, {
+ min: min,
+ max: max,
+ bits: sizepow,
+ window: options.window,
+ polynomial: options.polynomial
+ })) {
+ yield chunk
+ }
+}
+
+const jsRabin = () => {
+ return async function * (source, options) {
+ const r = await create(options.bits, options.min, options.max, options.window)
+ const buffers = new BufferList()
+ let pending = []
+
+ for await (const chunk of source) {
+ buffers.append(chunk)
+ pending.push(chunk)
+
+ const sizes = r.fingerprint(Buffer.concat(pending))
+ pending = []
+
+ for (let i = 0; i < sizes.length; i++) {
+ var size = sizes[i]
+ var buf = buffers.slice(0, size)
+ buffers.consume(size)
+
+ yield buf
+ }
+ }
+
+ if (buffers.length) {
+ yield buffers.slice(0)
+ }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"bl":112,"buffer":181,"err-code":411,"rabin-wasm":1364}],420:[function(require,module,exports){
+'use strict'
+
+const UnixFS = require('ipfs-unixfs')
+const persist = require('../utils/persist')
+const {
+ DAGNode
+} = require('ipld-dag-pb')
+
+const dirBuilder = async (item, ipld, options) => {
+ const unixfs = new UnixFS('directory')
+ const node = DAGNode.create(unixfs.marshal(), [])
+ const cid = await persist(node, ipld, options)
+ let path = item.path
+
+ return {
+ cid,
+ path,
+ unixfs,
+ node
+ }
+}
+
+module.exports = dirBuilder
+
+},{"../utils/persist":433,"ipfs-unixfs":435,"ipld-dag-pb":589}],421:[function(require,module,exports){
+'use strict'
+
+const batch = require('async-iterator-batch')
+
+async function * balanced (source, reduce, options) {
+ yield await reduceToParents(source, reduce, options)
+}
+
+async function reduceToParents (source, reduce, options) {
+ const roots = []
+
+ for await (const chunked of batch(source, options.maxChildrenPerNode)) {
+ roots.push(await reduce(chunked))
+ }
+
+ if (roots.length > 1) {
+ return reduceToParents(roots, reduce, options)
+ }
+
+ return roots[0]
+}
+
+module.exports = balanced
+
+},{"async-iterator-batch":31}],422:[function(require,module,exports){
+'use strict'
+
+const batch = require('async-iterator-batch')
+
+module.exports = async function * (source, reduce) {
+ const roots = []
+
+ for await (const chunk of batch(source, Infinity)) {
+ roots.push(await reduce(chunk))
+ }
+
+ yield roots[0]
+}
+
+},{"async-iterator-batch":31}],423:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const UnixFS = require('ipfs-unixfs')
+const persist = require('../../utils/persist')
+const {
+ DAGNode,
+ DAGLink
+} = require('ipld-dag-pb')
+const all = require('async-iterator-all')
+
+const dagBuilders = {
+ flat: require('./flat'),
+ balanced: require('./balanced'),
+ trickle: require('./trickle')
+}
+
+async function * buildFile (source, ipld, options) {
+ let count = -1
+ let previous
+
+ for await (const buffer of source) {
+ count++
+ options.progress(buffer.length)
+ let node
+ let unixfs
+
+ let opts = {
+ ...options
+ }
+
+ if (options.rawLeaves) {
+ node = buffer
+
+ opts.codec = 'raw'
+ opts.cidVersion = 1
+ } else {
+ unixfs = new UnixFS(options.leafType, buffer)
+ node = DAGNode.create(unixfs.marshal(), [])
+ }
+
+ const cid = await persist(node, ipld, opts)
+
+ const entry = {
+ cid: cid,
+ unixfs,
+ node
+ }
+
+ if (count === 0) {
+ previous = entry
+ continue
+ } else if (count === 1) {
+ yield previous
+ previous = null
+ }
+
+ yield entry
+ }
+
+ if (previous) {
+ previous.single = true
+ yield previous
+ }
+}
+
+const reduce = (file, ipld, options) => {
+ return async function (leaves) {
+ if (leaves.length === 1 && leaves[0].single && options.reduceSingleLeafToSelf) {
+ const leaf = leaves[0]
+
+ return {
+ cid: leaf.cid,
+ path: file.path,
+ name: (file.path || '').split('/').pop(),
+ unixfs: leaf.unixfs,
+ node: leaf.node
+ }
+ }
+
+ // create a parent node and add all the leaves
+ const f = new UnixFS('file')
+
+ const links = leaves
+ .filter(leaf => {
+ if (leaf.cid.codec === 'raw' && leaf.node.length) {
+ return true
+ }
+
+ if (!leaf.unixfs.data && leaf.unixfs.fileSize()) {
+ return true
+ }
+
+ return Boolean(leaf.unixfs.data.length)
+ })
+ .map((leaf) => {
+ if (leaf.cid.codec === 'raw') {
+ // node is a leaf buffer
+ f.addBlockSize(leaf.node.length)
+
+ return new DAGLink(leaf.name, leaf.node.length, leaf.cid)
+ }
+
+ if (!leaf.unixfs.data) {
+ // node is an intermediate node
+ f.addBlockSize(leaf.unixfs.fileSize())
+ } else {
+ // node is a unixfs 'file' leaf node
+ f.addBlockSize(leaf.unixfs.data.length)
+ }
+
+ return new DAGLink(leaf.name, leaf.node.size, leaf.cid)
+ })
+
+ const node = DAGNode.create(f.marshal(), links)
+ const cid = await persist(node, ipld, options)
+
+ return {
+ cid,
+ path: file.path,
+ unixfs: f,
+ node,
+ size: node.size
+ }
+ }
+}
+
+const fileBuilder = async (file, source, ipld, options) => {
+ const dagBuilder = dagBuilders[options.strategy]
+
+ if (!dagBuilder) {
+ throw errCode(new Error(`Unknown importer build strategy name: ${options.strategy}`), 'ERR_BAD_STRATEGY')
+ }
+
+ const roots = await all(dagBuilder(buildFile(source, ipld, options), reduce(file, ipld, options), options.builderOptions))
+
+ if (roots.length > 1) {
+ throw errCode(new Error('expected a maximum of 1 roots and got ' + roots.length), 'ETOOMANYROOTS')
+ }
+
+ return roots[0]
+}
+
+module.exports = fileBuilder
+
+},{"../../utils/persist":433,"./balanced":421,"./flat":422,"./trickle":424,"async-iterator-all":30,"err-code":411,"ipfs-unixfs":435,"ipld-dag-pb":589}],424:[function(require,module,exports){
+'use strict'
+
+const batch = require('async-iterator-batch')
+
+module.exports = function * trickleReduceToRoot (source, reduce, options) {
+ yield trickleStream(source, reduce, options)
+}
+
+async function trickleStream (source, reduce, options) {
+ let root
+ let iteration = 0
+ let maxDepth = 1
+ let subTree = root = new Root(options.layerRepeat)
+
+ for await (const layer of batch(source, options.maxChildrenPerNode)) {
+ if (subTree.isFull()) {
+ if (subTree !== root) {
+ root.addChild(await subTree.reduce(reduce))
+ }
+
+ if (iteration && iteration % options.layerRepeat === 0) {
+ maxDepth++
+ }
+
+ subTree = new SubTree(maxDepth, options.layerRepeat, iteration)
+
+ iteration++
+ }
+
+ subTree.append(layer)
+ }
+
+ if (subTree && subTree !== root) {
+ root.addChild(await subTree.reduce(reduce))
+ }
+
+ return root.reduce(reduce)
+}
+
+class SubTree {
+ constructor (maxDepth, layerRepeat, iteration) {
+ this.maxDepth = maxDepth
+ this.layerRepeat = layerRepeat
+ this.currentDepth = 1
+ this.iteration = iteration
+
+ this.root = this.node = this.parent = {
+ children: [],
+ depth: this.currentDepth,
+ maxDepth,
+ maxChildren: (this.maxDepth - this.currentDepth) * this.layerRepeat
+ }
+ }
+
+ isFull () {
+ if (!this.root.data) {
+ return false
+ }
+
+ if (this.currentDepth < this.maxDepth && this.node.maxChildren) {
+ // can descend
+ this._addNextNodeToParent(this.node)
+
+ return false
+ }
+
+ // try to find new node from node.parent
+ const distantRelative = this._findParent(this.node, this.currentDepth)
+
+ if (distantRelative) {
+ this._addNextNodeToParent(distantRelative)
+
+ return false
+ }
+
+ return true
+ }
+
+ _addNextNodeToParent (parent) {
+ this.parent = parent
+
+ // find site for new node
+ const nextNode = {
+ children: [],
+ depth: parent.depth + 1,
+ parent,
+ maxDepth: this.maxDepth,
+ maxChildren: Math.floor(parent.children.length / this.layerRepeat) * this.layerRepeat
+ }
+
+ parent.children.push(nextNode)
+
+ this.currentDepth = nextNode.depth
+ this.node = nextNode
+ }
+
+ append (layer) {
+ this.node.data = layer
+ }
+
+ reduce (reduce) {
+ return this._reduce(this.root, reduce)
+ }
+
+ async _reduce (node, reduce) {
+ let children = []
+
+ if (node.children.length) {
+ children = await Promise.all(
+ node.children
+ .filter(child => child.data)
+ .map(child => this._reduce(child, reduce))
+ )
+ }
+
+ return reduce(node.data.concat(children))
+ }
+
+ _findParent (node, depth) {
+ const parent = node.parent
+
+ if (!parent || parent.depth === 0) {
+ return
+ }
+
+ if (parent.children.length === parent.maxChildren || !parent.maxChildren) {
+ // this layer is full, may be able to traverse to a different branch
+ return this._findParent(parent, depth)
+ }
+
+ return parent
+ }
+}
+
+class Root extends SubTree {
+ constructor (layerRepeat) {
+ super(0, layerRepeat)
+
+ this.root.depth = 0
+ this.currentDepth = 1
+ }
+
+ addChild (child) {
+ this.root.children.push(child)
+ }
+
+ reduce (reduce) {
+ return reduce(this.root.data.concat(this.root.children))
+ }
+}
+
+},{"async-iterator-batch":31}],425:[function(require,module,exports){
+'use strict'
+
+const dirBuilder = require('./dir')
+const fileBuilder = require('./file')
+const createChunker = require('../chunker')
+const validateChunks = require('./validate-chunks')
+
+async function * dagBuilder (source, ipld, options) {
+ for await (const entry of source) {
+ if (entry.path) {
+ if (entry.path.substring(0, 2) === './') {
+ options.wrapWithDirectory = true
+ }
+
+ entry.path = entry.path
+ .split('/')
+ .filter(path => path && path !== '.')
+ .join('/')
+ }
+
+ if (entry.content) {
+ let source = entry.content
+
+ // wrap in iterator if it is array-like or not an iterator
+ if ((!source[Symbol.asyncIterator] && !source[Symbol.iterator]) || source.length !== undefined) {
+ source = {
+ [Symbol.iterator]: function * () {
+ yield entry.content
+ }
+ }
+ }
+
+ const chunker = createChunker(options.chunker, validateChunks(source), options.chunkerOptions)
+
+ // item is a file
+ yield fileBuilder(entry, chunker, ipld, options)
+ } else {
+ // item is a directory
+ yield dirBuilder(entry, ipld, options)
+ }
+ }
+}
+
+module.exports = dagBuilder
+
+},{"../chunker":418,"./dir":420,"./file":423,"./validate-chunks":426}],426:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const errCode = require('err-code')
+
+// make sure the content only emits buffer-a-likes
+async function * validateChunks (source) {
+ for await (const content of source) {
+ if (content.length === undefined) {
+ throw errCode(new Error('Content was invalid'), 'ERR_INVALID_CONTENT')
+ }
+
+ if (typeof content === 'string' || content instanceof String) {
+ yield Buffer.from(content, 'utf8')
+ } else if (Array.isArray(content)) {
+ yield Buffer.from(content)
+ } else {
+ yield content
+ }
+ }
+}
+
+module.exports = validateChunks
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"err-code":411}],427:[function(require,module,exports){
+'use strict'
+
+const {
+ DAGLink,
+ DAGNode
+} = require('ipld-dag-pb')
+const UnixFS = require('ipfs-unixfs')
+const Dir = require('./dir')
+const persist = require('./utils/persist')
+
+class DirFlat extends Dir {
+ constructor (props, options) {
+ super(props, options)
+ this._children = {}
+ }
+
+ put (name, value) {
+ this.cid = undefined
+ this.size = undefined
+ this._children[name] = value
+ }
+
+ get (name) {
+ return this._children[name]
+ }
+
+ childCount () {
+ return Object.keys(this._children).length
+ }
+
+ directChildrenCount () {
+ return this.childCount()
+ }
+
+ onlyChild () {
+ return this._children[Object.keys(this._children)[0]]
+ }
+
+ * eachChildSeries () {
+ const keys = Object.keys(this._children)
+
+ for (let i = 0; i < keys.length; i++) {
+ const key = keys[i]
+
+ yield {
+ key: key,
+ child: this._children[key]
+ }
+ }
+ }
+
+ async * flush (path, ipld) {
+ const children = Object.keys(this._children)
+ const links = []
+
+ for (let i = 0; i < children.length; i++) {
+ let child = this._children[children[i]]
+
+ if (typeof child.flush === 'function') {
+ for await (const entry of child.flush(child.path, ipld)) {
+ child = entry
+
+ yield child
+ }
+ }
+
+ links.push(new DAGLink(children[i], child.node.length || child.node.size, child.cid))
+ }
+
+ const unixfs = new UnixFS('directory')
+ let node = DAGNode.create(unixfs.marshal(), links)
+ const cid = await persist(node, ipld, this.options)
+
+ this.cid = cid
+ this.size = node.size
+
+ yield {
+ cid,
+ unixfs,
+ path,
+ node
+ }
+ }
+}
+
+module.exports = DirFlat
+
+},{"./dir":429,"./utils/persist":433,"ipfs-unixfs":435,"ipld-dag-pb":589}],428:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const {
+ DAGLink,
+ DAGNode
+} = require('ipld-dag-pb')
+const UnixFS = require('ipfs-unixfs')
+const multihashing = require('multihashing-async')
+const Dir = require('./dir')
+const persist = require('./utils/persist')
+const Bucket = require('hamt-sharding')
+const extend = require('deep-extend')
+
+const hashFn = async function (value) {
+ const hash = await multihashing(Buffer.from(value, 'utf8'), 'murmur3-128')
+
+ // Multihashing inserts preamble of 2 bytes. Remove it.
+ // Also, murmur3 outputs 128 bit but, accidently, IPFS Go's
+ // implementation only uses the first 64, so we must do the same
+ // for parity..
+ const justHash = hash.slice(2, 10)
+ const length = justHash.length
+ const result = Buffer.alloc(length)
+ // TODO: invert buffer because that's how Go impl does it
+ for (let i = 0; i < length; i++) {
+ result[length - i - 1] = justHash[i]
+ }
+
+ return result
+}
+hashFn.code = 0x22 // TODO: get this from multihashing-async?
+
+const defaultOptions = {
+ hashFn: hashFn
+}
+
+class DirSharded extends Dir {
+ constructor (props, options) {
+ options = extend({}, defaultOptions, options)
+
+ super(props, options)
+
+ this._bucket = Bucket(options)
+ }
+
+ async put (name, value) {
+ await this._bucket.put(name, value)
+ }
+
+ get (name) {
+ return this._bucket.get(name)
+ }
+
+ childCount () {
+ return this._bucket.leafCount()
+ }
+
+ directChildrenCount () {
+ return this._bucket.childrenCount()
+ }
+
+ onlyChild () {
+ return this._bucket.onlyChild()
+ }
+
+ async * eachChildSeries () {
+ for await (const { key, value } of this._bucket.eachLeafSeries()) {
+ yield {
+ key,
+ child: value
+ }
+ }
+ }
+
+ async * flush (path, ipld) {
+ for await (const entry of flush(path, this._bucket, ipld, this.options)) {
+ yield entry
+ }
+ }
+}
+
+module.exports = DirSharded
+
+module.exports.hashFn = hashFn
+
+async function * flush (path, bucket, ipld, options) {
+ const children = bucket._children
+ const links = []
+
+ for (let i = 0; i < children.length; i++) {
+ const child = children.get(i)
+
+ if (!child) {
+ continue
+ }
+
+ const labelPrefix = i.toString(16).toUpperCase().padStart(2, '0')
+
+ if (Bucket.isBucket(child)) {
+ let shard
+
+ for await (const subShard of await flush('', child, ipld, options)) {
+ shard = subShard
+ }
+
+ links.push(await new DAGLink(labelPrefix, shard.node.size, shard.cid))
+ } else if (typeof child.value.flush === 'function') {
+ const dir = child.value
+ let flushedDir
+
+ for await (const entry of dir.flush(dir.path, ipld)) {
+ flushedDir = entry
+
+ yield flushedDir
+ }
+
+ const label = labelPrefix + child.key
+ links.push(new DAGLink(label, flushedDir.node.size, flushedDir.cid))
+ } else {
+ const value = child.value
+
+ if (!value.node) {
+ if (value.cid) {
+ value.node = await ipld.get(value.cid)
+ } else {
+ continue
+ }
+ }
+
+ const label = labelPrefix + child.key
+ const size = value.node.length || value.node.size || value.node.Size
+
+ links.push(await new DAGLink(label, size, value.cid))
+ }
+ }
+
+ // go-ipfs uses little endian, that's why we have to
+ // reverse the bit field before storing it
+ const data = Buffer.from(children.bitField().reverse())
+ const dir = new UnixFS('hamt-sharded-directory', data)
+ dir.fanout = bucket.tableSize()
+ dir.hashType = options.hashFn.code
+
+ const node = DAGNode.create(dir.marshal(), links)
+ const cid = await persist(node, ipld, options)
+
+ yield {
+ cid,
+ node,
+ unixfs: dir,
+ path
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./dir":429,"./utils/persist":433,"buffer":181,"deep-extend":215,"hamt-sharding":289,"ipfs-unixfs":435,"ipld-dag-pb":589,"multihashing-async":414}],429:[function(require,module,exports){
+'use strict'
+
+module.exports = class Dir {
+ constructor (props, options) {
+ this.options = options || {}
+ Object.assign(this, props)
+ }
+}
+
+},{}],430:[function(require,module,exports){
+'use strict'
+
+const DirSharded = require('./dir-sharded')
+
+module.exports = async function flatToShard (child, dir, threshold, options) {
+ let newDir = dir
+
+ if (dir.flat && dir.directChildrenCount() >= threshold) {
+ newDir = await convertToShard(dir, options)
+ }
+
+ const parent = newDir.parent
+
+ if (parent) {
+ if (newDir !== dir) {
+ if (child) {
+ child.parent = newDir
+ }
+
+ await parent.put(newDir.parentKey, newDir)
+ }
+
+ if (parent) {
+ return flatToShard(newDir, parent, threshold, options)
+ }
+ }
+
+ return newDir
+}
+
+async function convertToShard (oldDir, options) {
+ const newDir = new DirSharded({
+ root: oldDir.root,
+ dir: true,
+ parent: oldDir.parent,
+ parentKey: oldDir.parentKey,
+ path: oldDir.path,
+ dirty: oldDir.dirty,
+ flat: false
+ }, options)
+
+ for await (const { key, child } of oldDir.eachChildSeries()) {
+ await newDir.put(key, child)
+ }
+
+ return newDir
+}
+
+},{"./dir-sharded":428}],431:[function(require,module,exports){
+'use strict'
+
+const { superstruct } = require('superstruct')
+const dagBuilder = require('./dag-builder')
+const treeBuilder = require('./tree-builder')
+const mh = require('multihashes')
+
+const struct = superstruct({
+ types: {
+ codec: v => ['dag-pb', 'dag-cbor', 'raw'].includes(v),
+ hashAlg: v => Object.keys(mh.names).includes(v),
+ leafType: v => ['file', 'raw'].includes(v)
+ }
+})
+
+const ChunkerOptions = struct({
+ minChunkSize: 'number?',
+ maxChunkSize: 'number?',
+ avgChunkSize: 'number?',
+ window: 'number?',
+ polynomial: 'number?'
+}, {
+ maxChunkSize: 262144,
+ avgChunkSize: 262144,
+ window: 16,
+ polynomial: 17437180132763653 // https://github.com/ipfs/go-ipfs-chunker/blob/d0125832512163708c0804a3cda060e21acddae4/rabin.go#L11
+})
+
+const BuilderOptions = struct({
+ maxChildrenPerNode: 'number?',
+ layerRepeat: 'number?'
+}, {
+ maxChildrenPerNode: 174,
+ layerRepeat: 4
+})
+
+const Options = struct({
+ chunker: struct.enum(['fixed', 'rabin']),
+ rawLeaves: 'boolean?',
+ hashOnly: 'boolean?',
+ strategy: struct.enum(['balanced', 'flat', 'trickle']),
+ reduceSingleLeafToSelf: 'boolean?',
+ codec: 'codec?',
+ format: 'codec?',
+ hashAlg: 'hashAlg?',
+ leafType: 'leafType?',
+ cidVersion: 'number?',
+ progress: 'function?',
+ wrapWithDirectory: 'boolean?',
+ shardSplitThreshold: 'number?',
+ onlyHash: 'boolean?',
+ chunkerOptions: ChunkerOptions,
+ builderOptions: BuilderOptions,
+
+ wrap: 'boolean?',
+ pin: 'boolean?',
+ recursive: 'boolean?',
+ ignore: 'array?',
+ hidden: 'boolean?',
+ preload: 'boolean?'
+}, {
+ chunker: 'fixed',
+ strategy: 'balanced',
+ rawLeaves: false,
+ reduceSingleLeafToSelf: true,
+ codec: 'dag-pb',
+ hashAlg: 'sha2-256',
+ leafType: 'file',
+ cidVersion: 0,
+ progress: () => () => {},
+ shardSplitThreshold: 1000
+})
+
+module.exports = async function * (source, ipld, options = {}) {
+ const opts = Options(options)
+
+ if (options.cidVersion > 0 && options.rawLeaves === undefined) {
+ // if the cid version is 1 or above, use raw leaves as this is
+ // what go does.
+ opts.rawLeaves = true
+ }
+
+ if (options.hashAlg !== undefined && options.rawLeaves === undefined) {
+ // if a non-default hash alg has been specified, use raw leaves as this is
+ // what go does.
+ opts.rawLeaves = true
+ }
+
+ // go-ifps trickle dag defaults to unixfs raw leaves, balanced dag defaults to file leaves
+ if (options.strategy === 'trickle') {
+ opts.leafType = 'raw'
+ opts.reduceSingleLeafToSelf = false
+ }
+
+ if (options.format) {
+ options.codec = options.format
+ }
+
+ for await (const entry of treeBuilder(dagBuilder(source, ipld, opts), ipld, opts)) {
+ yield {
+ cid: entry.cid,
+ path: entry.path,
+ unixfs: entry.unixfs,
+ size: entry.size
+ }
+ }
+}
+
+},{"./dag-builder":425,"./tree-builder":432,"multihashes":1157,"superstruct":1498}],432:[function(require,module,exports){
+'use strict'
+
+const DirFlat = require('./dir-flat')
+const flatToShard = require('./flat-to-shard')
+const Dir = require('./dir')
+const toPathComponents = require('./utils/to-path-components')
+const errCode = require('err-code')
+const first = require('async-iterator-first')
+
+async function addToTree (elem, tree, options) {
+ const pathElems = toPathComponents(elem.path || '')
+ const lastIndex = pathElems.length - 1
+ let parent = tree
+ let currentPath = ''
+
+ for (let i = 0; i < pathElems.length; i++) {
+ const pathElem = pathElems[i]
+
+ currentPath += `${currentPath ? '/' : ''}${pathElem}`
+
+ const last = (i === lastIndex)
+ parent.dirty = true
+ parent.cid = null
+ parent.size = null
+
+ if (last) {
+ await parent.put(pathElem, elem)
+ tree = await flatToShard(null, parent, options.shardSplitThreshold, options)
+ } else {
+ let dir = await parent.get(pathElem)
+
+ if (!dir || !(dir instanceof Dir)) {
+ dir = new DirFlat({
+ dir: true,
+ parent: parent,
+ parentKey: pathElem,
+ path: currentPath,
+ dirty: true,
+ flat: true
+ }, options)
+ }
+
+ await parent.put(pathElem, dir)
+
+ parent = dir
+ }
+ }
+
+ return tree
+}
+
+async function * treeBuilder (source, ipld, options) {
+ let tree = new DirFlat({
+ root: true,
+ dir: true,
+ path: '',
+ dirty: true,
+ flat: true
+ }, options)
+
+ for await (const entry of source) {
+ tree = await addToTree(entry, tree, options)
+
+ yield entry
+ }
+
+ if (tree) {
+ if (!options.wrapWithDirectory) {
+ if (tree.childCount() > 1) {
+ throw errCode(new Error('detected more than one root'), 'ERR_MORE_THAN_ONE_ROOT')
+ }
+
+ const unwrapped = await first(tree.eachChildSeries())
+
+ if (!unwrapped) {
+ return
+ }
+
+ tree = unwrapped.child
+ }
+
+ if (!tree.dir) {
+ return
+ }
+
+ for await (const entry of tree.flush(tree.path, ipld)) {
+ yield entry
+ }
+ }
+}
+
+module.exports = treeBuilder
+
+},{"./dir":429,"./dir-flat":427,"./flat-to-shard":430,"./utils/to-path-components":434,"async-iterator-first":32,"err-code":411}],433:[function(require,module,exports){
+'use strict'
+
+const mh = require('multihashes')
+const mc = require('multicodec')
+
+const persist = (node, ipld, options) => {
+ if (!options.codec && node.length) {
+ options.cidVersion = 1
+ options.codec = 'raw'
+ }
+
+ if (isNaN(options.hashAlg)) {
+ options.hashAlg = mh.names[options.hashAlg]
+ }
+
+ if (options.hashAlg !== mh.names['sha2-256']) {
+ options.cidVersion = 1
+ }
+
+ if (options.format) {
+ options.codec = options.format
+ }
+
+ const format = mc[options.codec.toUpperCase().replace(/-/g, '_')]
+
+ return ipld.put(node, format, options)
+}
+
+module.exports = persist
+
+},{"multicodec":1151,"multihashes":1157}],434:[function(require,module,exports){
+arguments[4][376][0].apply(exports,arguments)
+},{"dup":376}],435:[function(require,module,exports){
+'use strict'
+
+const protons = require('protons')
+const pb = protons(require('./unixfs.proto'))
+// encode/decode
+const unixfsData = pb.Data
+// const unixfsMetadata = pb.MetaData // encode/decode
+
+const types = [
+ 'raw',
+ 'directory',
+ 'file',
+ 'metadata',
+ 'symlink',
+ 'hamt-sharded-directory'
+]
+
+const dirTypes = [
+ 'directory',
+ 'hamt-sharded-directory'
+]
+
+function Data (type, data) {
+ if (!(this instanceof Data)) {
+ return new Data(type, data)
+ }
+ if (types.indexOf(type) === -1) {
+ throw new Error('Type: ' + type + ' is not valid')
+ }
+
+ this.type = type
+ this.data = data
+ this.blockSizes = []
+
+ this.addBlockSize = (size) => {
+ this.blockSizes.push(size)
+ }
+
+ this.removeBlockSize = (index) => {
+ this.blockSizes.splice(index, 1)
+ }
+
+ // data.length + blockSizes
+ this.fileSize = () => {
+ if (dirTypes.indexOf(this.type) >= 0) {
+ // dirs don't have file size
+ return undefined
+ }
+
+ let sum = 0
+ this.blockSizes.forEach((size) => {
+ sum += size
+ })
+ if (data) {
+ sum += data.length
+ }
+ return sum
+ }
+
+ // encode to protobuf
+ this.marshal = () => {
+ let type
+
+ switch (this.type) {
+ case 'raw': type = unixfsData.DataType.Raw; break
+ case 'directory': type = unixfsData.DataType.Directory; break
+ case 'file': type = unixfsData.DataType.File; break
+ case 'metadata': type = unixfsData.DataType.Metadata; break
+ case 'symlink': type = unixfsData.DataType.Symlink; break
+ case 'hamt-sharded-directory': type = unixfsData.DataType.HAMTShard; break
+ default:
+ throw new Error(`Unkown type: "${this.type}"`)
+ }
+ let fileSize = this.fileSize()
+
+ let data = this.data
+
+ if (!this.data || !this.data.length) {
+ data = undefined
+ }
+
+ let blockSizes = this.blockSizes
+
+ if (!this.blockSizes || !this.blockSizes.length) {
+ blockSizes = undefined
+ }
+
+ return unixfsData.encode({
+ Type: type,
+ Data: data,
+ filesize: fileSize,
+ blocksizes: blockSizes,
+ hashType: this.hashType,
+ fanout: this.fanout
+ })
+ }
+}
+
+// decode from protobuf https://github.com/ipfs/go-ipfs/blob/master/unixfs/format.go#L24
+Data.unmarshal = (marsheled) => {
+ const decoded = unixfsData.decode(marsheled)
+ if (!decoded.Data) {
+ decoded.Data = undefined
+ }
+ const obj = new Data(types[decoded.Type], decoded.Data)
+ obj.blockSizes = decoded.blocksizes
+ return obj
+}
+
+exports = module.exports = Data
+
+},{"./unixfs.proto":436,"protons":1274}],436:[function(require,module,exports){
+'use strict'
+
+module.exports = `message Data {
+ enum DataType {
+ Raw = 0;
+ Directory = 1;
+ File = 2;
+ Metadata = 3;
+ Symlink = 4;
+ HAMTShard = 5;
+ }
+
+ required DataType Type = 1;
+ optional bytes Data = 2;
+ optional uint64 filesize = 3;
+ repeated uint64 blocksizes = 4;
+
+ optional uint64 hashType = 5;
+ optional uint64 fanout = 6;
+}
+
+message Metadata {
+ optional string MimeType = 1;
+}`
+
+},{}],437:[function(require,module,exports){
+arguments[4][36][0].apply(exports,arguments)
+},{"dup":36}],438:[function(require,module,exports){
+arguments[4][37][0].apply(exports,arguments)
+},{"_process":1258,"dup":37}],439:[function(require,module,exports){
+arguments[4][38][0].apply(exports,arguments)
+},{"./_stream_readable":441,"./_stream_writable":443,"_process":1258,"dup":38,"inherits":317}],440:[function(require,module,exports){
+arguments[4][39][0].apply(exports,arguments)
+},{"./_stream_transform":442,"dup":39,"inherits":317}],441:[function(require,module,exports){
+arguments[4][40][0].apply(exports,arguments)
+},{"../errors":437,"../experimentalWarning":438,"./_stream_duplex":439,"./internal/streams/async_iterator":444,"./internal/streams/buffer_list":445,"./internal/streams/destroy":446,"./internal/streams/state":449,"./internal/streams/stream":450,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":453,"util":146}],442:[function(require,module,exports){
+arguments[4][41][0].apply(exports,arguments)
+},{"../errors":437,"./_stream_duplex":439,"dup":41,"inherits":317}],443:[function(require,module,exports){
+arguments[4][42][0].apply(exports,arguments)
+},{"../errors":437,"./_stream_duplex":439,"./internal/streams/destroy":446,"./internal/streams/state":449,"./internal/streams/stream":450,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],444:[function(require,module,exports){
+arguments[4][43][0].apply(exports,arguments)
+},{"./end-of-stream":447,"_process":1258,"dup":43}],445:[function(require,module,exports){
+arguments[4][44][0].apply(exports,arguments)
+},{"buffer":181,"dup":44,"util":146}],446:[function(require,module,exports){
+arguments[4][45][0].apply(exports,arguments)
+},{"_process":1258,"dup":45}],447:[function(require,module,exports){
+arguments[4][46][0].apply(exports,arguments)
+},{"../../../errors":437,"dup":46}],448:[function(require,module,exports){
+arguments[4][47][0].apply(exports,arguments)
+},{"../../../errors":437,"./end-of-stream":447,"dup":47}],449:[function(require,module,exports){
+arguments[4][48][0].apply(exports,arguments)
+},{"../../../errors":437,"dup":48}],450:[function(require,module,exports){
+arguments[4][49][0].apply(exports,arguments)
+},{"dup":49,"events":272}],451:[function(require,module,exports){
+arguments[4][50][0].apply(exports,arguments)
+},{"./lib/_stream_duplex.js":439,"./lib/_stream_passthrough.js":440,"./lib/_stream_readable.js":441,"./lib/_stream_transform.js":442,"./lib/_stream_writable.js":443,"./lib/internal/streams/end-of-stream.js":447,"./lib/internal/streams/pipeline.js":448,"dup":50}],452:[function(require,module,exports){
+arguments[4][51][0].apply(exports,arguments)
+},{"buffer":181,"dup":51}],453:[function(require,module,exports){
+arguments[4][52][0].apply(exports,arguments)
+},{"dup":52,"safe-buffer":452}],454:[function(require,module,exports){
+'use strict'
+
+const errCode = require('err-code')
+const { Buffer } = require('buffer')
+const pullStreamToIterable = require('pull-stream-to-async-iterator')
+const { isSource } = require('is-pull-stream')
+const globalThis = require('../globalthis')
+const { Readable } = require('stream')
+const Readable3 = require('readable-stream')
+
+/*
+ * Transform one of:
+ *
+ * ```
+ * Bytes (Buffer|ArrayBuffer|TypedArray) [single file]
+ * Bloby (Blob|File) [single file]
+ * String [single file]
+ * { path, content: Bytes } [single file]
+ * { path, content: Bloby } [single file]
+ * { path, content: String } [single file]
+ * { path, content: Iterable } [single file]
+ * { path, content: Iterable } [single file]
+ * { path, content: AsyncIterable } [single file]
+ * { path, content: PullStream } [single file]
+ * { path, content: Readable } [single file]
+ * Iterable [single file]
+ * Iterable [single file]
+ * Iterable [multiple files]
+ * Iterable [multiple files]
+ * Iterable<{ path, content: Bytes }> [multiple files]
+ * Iterable<{ path, content: Bloby }> [multiple files]
+ * Iterable<{ path, content: String }> [multiple files]
+ * Iterable<{ path, content: Iterable }> [multiple files]
+ * Iterable<{ path, content: Iterable }> [multiple files]
+ * Iterable<{ path, content: AsyncIterable }> [multiple files]
+ * Iterable<{ path, content: PullStream }> [multiple files]
+ * Iterable<{ path, content: Readable }> [multiple files]
+ * AsyncIterable [single file]
+ * AsyncIterable [multiple files]
+ * AsyncIterable [multiple files]
+ * AsyncIterable<{ path, content: Bytes }> [multiple files]
+ * AsyncIterable<{ path, content: Bloby }> [multiple files]
+ * AsyncIterable<{ path, content: String }> [multiple files]
+ * AsyncIterable<{ path, content: Iterable }> [multiple files]
+ * AsyncIterable<{ path, content: Iterable }> [multiple files]
+ * AsyncIterable<{ path, content: AsyncIterable }> [multiple files]
+ * AsyncIterable<{ path, content: PullStream }> [multiple files]
+ * AsyncIterable<{ path, content: Readable }> [multiple files]
+ * PullStream [single file]
+ * PullStream [multiple files]
+ * PullStream [multiple files]
+ * PullStream<{ path, content: Bytes }> [multiple files]
+ * PullStream<{ path, content: Bloby }> [multiple files]
+ * PullStream<{ path, content: String }> [multiple files]
+ * PullStream<{ path, content: Iterable }> [multiple files]
+ * PullStream<{ path, content: Iterable }> [multiple files]
+ * PullStream<{ path, content: AsyncIterable }> [multiple files]
+ * PullStream<{ path, content: PullStream }> [multiple files]
+ * PullStream<{ path, content: Readable }> [multiple files]
+ * Readable [single file]
+ * Readable [multiple files]
+ * Readable [multiple files]
+ * Readable<{ path, content: Bytes }> [multiple files]
+ * Readable<{ path, content: Bloby }> [multiple files]
+ * Readable<{ path, content: String }> [multiple files]
+ * Readable<{ path, content: Iterable }> [multiple files]
+ * Readable<{ path, content: Iterable }> [multiple files]
+ * Readable<{ path, content: AsyncIterable }> [multiple files]
+ * Readable<{ path, content: PullStream }> [multiple files]
+ * Readable<{ path, content: Readable }> [multiple files]
+ * ```
+ * Into:
+ *
+ * ```
+ * AsyncIterable<{ path, content: AsyncIterable }>
+ * ```
+ *
+ * @param input Object
+ * @return AsyncInterable<{ path, content: AsyncIterable }>
+ */
+module.exports = function normaliseInput (input) {
+ // must give us something
+ if (input === null || input === undefined) {
+ throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT'))
+ }
+
+ // String
+ if (typeof input === 'string' || input instanceof String) {
+ return (async function * () { // eslint-disable-line require-await
+ yield toFileObject(input)
+ })()
+ }
+
+ // Buffer|ArrayBuffer|TypedArray
+ // Blob|File
+ if (isBytes(input) || isBloby(input)) {
+ return (async function * () { // eslint-disable-line require-await
+ yield toFileObject(input)
+ })()
+ }
+
+ // Readable>
+ if (isOldReadable(input)) {
+ input = upgradeOldStream(input)
+ }
+
+ // Iterable>
+ if (input[Symbol.iterator]) {
+ return (async function * () { // eslint-disable-line require-await
+ const iterator = input[Symbol.iterator]()
+ const first = iterator.next()
+ if (first.done) return iterator
+
+ // Iterable
+ // Iterable
+ if (Number.isInteger(first.value) || isBytes(first.value)) {
+ yield toFileObject((function * () {
+ yield first.value
+ yield * iterator
+ })())
+ return
+ }
+
+ // Iterable
+ // Iterable
+ // Iterable<{ path, content }>
+ if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') {
+ yield toFileObject(first.value)
+ for (const obj of iterator) {
+ yield toFileObject(obj)
+ }
+ return
+ }
+
+ throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')
+ })()
+ }
+
+ // AsyncIterable>
+ if (input[Symbol.asyncIterator]) {
+ return (async function * () {
+ const iterator = input[Symbol.asyncIterator]()
+ const first = await iterator.next()
+ if (first.done) return iterator
+
+ // AsyncIterable
+ if (isBytes(first.value)) {
+ yield toFileObject((async function * () { // eslint-disable-line require-await
+ yield first.value
+ yield * iterator
+ })())
+ return
+ }
+
+ // AsyncIterable
+ // AsyncIterable
+ // AsyncIterable<{ path, content }>
+ if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') {
+ yield toFileObject(first.value)
+ for await (const obj of iterator) {
+ yield toFileObject(obj)
+ }
+ return
+ }
+
+ throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')
+ })()
+ }
+
+ // { path, content: ? }
+ // Note: Detected _after_ AsyncIterable> because Node.js streams have a
+ // `path` property that passes this check.
+ if (isFileObject(input)) {
+ return (async function * () { // eslint-disable-line require-await
+ yield toFileObject(input)
+ })()
+ }
+
+ // PullStream>
+ if (isSource(input)) {
+ return (async function * () {
+ const iterator = pullStreamToIterable(input)[Symbol.asyncIterator]()
+ const first = await iterator.next()
+ if (first.done) return iterator
+
+ // PullStream
+ if (isBytes(first.value)) {
+ yield toFileObject((async function * () { // eslint-disable-line require-await
+ yield first.value
+ yield * iterator
+ })())
+ return
+ }
+
+ // PullStream
+ // PullStream
+ // PullStream<{ path, content }>
+ if (isFileObject(first.value) || isBloby(first.value) || typeof first.value === 'string') {
+ yield toFileObject(first.value)
+ for await (const obj of iterator) {
+ yield toFileObject(obj)
+ }
+ return
+ }
+
+ throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')
+ })()
+ }
+
+ throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')
+}
+
+function toFileObject (input) {
+ const obj = { path: input.path || '' }
+
+ if (input.content) {
+ obj.content = toAsyncIterable(input.content)
+ } else if (!input.path) { // Not already a file object with path or content prop
+ obj.content = toAsyncIterable(input)
+ }
+
+ return obj
+}
+
+function toAsyncIterable (input) {
+ // Bytes | String
+ if (isBytes(input) || typeof input === 'string') {
+ return (async function * () { // eslint-disable-line require-await
+ yield toBuffer(input)
+ })()
+ }
+
+ // Bloby
+ if (isBloby(input)) {
+ return blobToAsyncGenerator(input)
+ }
+
+ // Readable>
+ if (isOldReadable(input)) {
+ input = upgradeOldStream(input)
+ }
+
+ // Iterator>
+ if (input[Symbol.iterator]) {
+ return (async function * () { // eslint-disable-line require-await
+ const iterator = input[Symbol.iterator]()
+ const first = iterator.next()
+ if (first.done) return iterator
+
+ // Iterable
+ if (Number.isInteger(first.value)) {
+ yield toBuffer(Array.from((function * () {
+ yield first.value
+ yield * iterator
+ })()))
+ return
+ }
+
+ // Iterable
+ if (isBytes(first.value)) {
+ yield toBuffer(first.value)
+ for (const chunk of iterator) {
+ yield toBuffer(chunk)
+ }
+ return
+ }
+
+ throw errCode(new Error('Unexpected input: ' + typeof input), 'ERR_UNEXPECTED_INPUT')
+ })()
+ }
+
+ // AsyncIterable
+ if (input[Symbol.asyncIterator]) {
+ return (async function * () {
+ for await (const chunk of input) {
+ yield toBuffer(chunk)
+ }
+ })()
+ }
+
+ // PullStream
+ if (isSource(input)) {
+ return pullStreamToIterable(input)
+ }
+
+ throw errCode(new Error(`Unexpected input: ${input}`, 'ERR_UNEXPECTED_INPUT'))
+}
+
+function isOldReadable (obj) {
+ if (obj[Symbol.iterator] || obj[Symbol.asyncIterator]) {
+ return false
+ }
+
+ return Boolean(obj.readable)
+}
+
+function toBuffer (chunk) {
+ return isBytes(chunk) ? chunk : Buffer.from(chunk)
+}
+
+function isBytes (obj) {
+ return Buffer.isBuffer(obj) || ArrayBuffer.isView(obj) || obj instanceof ArrayBuffer
+}
+
+function isBloby (obj) {
+ return typeof globalThis.Blob !== 'undefined' && obj instanceof globalThis.Blob
+}
+
+// An object with a path or content property
+function isFileObject (obj) {
+ return typeof obj === 'object' && (obj.path || obj.content)
+}
+
+function upgradeOldStream (stream) {
+ if (stream[Symbol.asyncIterator] || stream[Symbol.iterator]) {
+ return stream
+ }
+
+ // in the browser the stream.Readable is not an async iterator but readble-stream@3 is...
+ stream[Symbol.asyncIterator] = Readable.prototype[Symbol.asyncIterator] || Readable3.prototype[Symbol.asyncIterator]
+
+ return stream
+}
+
+function blobToAsyncGenerator (blob) {
+ if (typeof blob.stream === 'function') {
+ // firefox < 69 does not support blob.stream()
+ return streamBlob(blob)
+ }
+
+ return readBlob(blob)
+}
+
+async function * streamBlob (blob) {
+ const reader = blob.stream().getReader()
+
+ while (true) {
+ const result = await reader.read()
+
+ if (result.done) {
+ return
+ }
+
+ yield result.value
+ }
+}
+
+async function * readBlob (blob, options) {
+ options = options || {}
+
+ const reader = new globalThis.FileReader()
+ const chunkSize = options.chunkSize || 1024 * 1024
+ let offset = options.offset || 0
+
+ const getNextChunk = () => new Promise((resolve, reject) => {
+ reader.onloadend = e => {
+ const data = e.target.result
+ resolve(data.byteLength === 0 ? null : data)
+ }
+ reader.onerror = reject
+
+ const end = offset + chunkSize
+ const slice = blob.slice(offset, end)
+ reader.readAsArrayBuffer(slice)
+ offset = end
+ })
+
+ while (true) {
+ const data = await getNextChunk()
+
+ if (data == null) {
+ return
+ }
+
+ yield Buffer.from(data)
+ }
+}
+
+},{"../globalthis":455,"buffer":181,"err-code":268,"is-pull-stream":617,"pull-stream-to-async-iterator":1309,"readable-stream":451,"stream":1459}],455:[function(require,module,exports){
+/* eslint-disable no-undef */
+/* eslint-disable no-extend-native */
+/* eslint-disable strict */
+
+// polyfill for globalThis
+// https://v8.dev/features/globalthis
+// https://mathiasbynens.be/notes/globalthis
+(function () {
+ if (typeof globalThis === 'object') return
+ Object.defineProperty(Object.prototype, '__magic__', {
+ get: function () {
+ return this
+ },
+ configurable: true
+ })
+ __magic__.globalThis = __magic__
+ delete Object.prototype.__magic__
+}())
+
+module.exports = globalThis
+
+},{}],456:[function(require,module,exports){
+arguments[4][208][0].apply(exports,arguments)
+},{"./common":457,"_process":1258,"dup":208}],457:[function(require,module,exports){
+arguments[4][209][0].apply(exports,arguments)
+},{"dup":209,"ms":1136}],458:[function(require,module,exports){
+arguments[4][36][0].apply(exports,arguments)
+},{"dup":36}],459:[function(require,module,exports){
+arguments[4][37][0].apply(exports,arguments)
+},{"_process":1258,"dup":37}],460:[function(require,module,exports){
+arguments[4][38][0].apply(exports,arguments)
+},{"./_stream_readable":462,"./_stream_writable":464,"_process":1258,"dup":38,"inherits":317}],461:[function(require,module,exports){
+arguments[4][39][0].apply(exports,arguments)
+},{"./_stream_transform":463,"dup":39,"inherits":317}],462:[function(require,module,exports){
+arguments[4][40][0].apply(exports,arguments)
+},{"../errors":458,"../experimentalWarning":459,"./_stream_duplex":460,"./internal/streams/async_iterator":465,"./internal/streams/buffer_list":466,"./internal/streams/destroy":467,"./internal/streams/state":470,"./internal/streams/stream":471,"_process":1258,"buffer":181,"dup":40,"events":272,"inherits":317,"string_decoder/":474,"util":146}],463:[function(require,module,exports){
+arguments[4][41][0].apply(exports,arguments)
+},{"../errors":458,"./_stream_duplex":460,"dup":41,"inherits":317}],464:[function(require,module,exports){
+arguments[4][42][0].apply(exports,arguments)
+},{"../errors":458,"./_stream_duplex":460,"./internal/streams/destroy":467,"./internal/streams/state":470,"./internal/streams/stream":471,"_process":1258,"buffer":181,"dup":42,"inherits":317,"util-deprecate":1510}],465:[function(require,module,exports){
+arguments[4][43][0].apply(exports,arguments)
+},{"./end-of-stream":468,"_process":1258,"dup":43}],466:[function(require,module,exports){
+arguments[4][44][0].apply(exports,arguments)
+},{"buffer":181,"dup":44,"util":146}],467:[function(require,module,exports){
+arguments[4][45][0].apply(exports,arguments)
+},{"_process":1258,"dup":45}],468:[function(require,module,exports){
+arguments[4][46][0].apply(exports,arguments)
+},{"../../../errors":458,"dup":46}],469:[function(require,module,exports){
+arguments[4][47][0].apply(exports,arguments)
+},{"../../../errors":458,"./end-of-stream":468,"dup":47}],470:[function(require,module,exports){
+arguments[4][48][0].apply(exports,arguments)
+},{"../../../errors":458,"dup":48}],471:[function(require,module,exports){
+arguments[4][49][0].apply(exports,arguments)
+},{"dup":49,"events":272}],472:[function(require,module,exports){
+arguments[4][50][0].apply(exports,arguments)
+},{"./lib/_stream_duplex.js":460,"./lib/_stream_passthrough.js":461,"./lib/_stream_readable.js":462,"./lib/_stream_transform.js":463,"./lib/_stream_writable.js":464,"./lib/internal/streams/end-of-stream.js":468,"./lib/internal/streams/pipeline.js":469,"dup":50}],473:[function(require,module,exports){
+arguments[4][51][0].apply(exports,arguments)
+},{"buffer":181,"dup":51}],474:[function(require,module,exports){
+arguments[4][52][0].apply(exports,arguments)
+},{"dup":52,"safe-buffer":473}],475:[function(require,module,exports){
+module.exports={
+ "_args": [
+ [
+ "ipfs@0.38.0",
+ "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet"
+ ]
+ ],
+ "_from": "ipfs@0.38.0",
+ "_id": "ipfs@0.38.0",
+ "_inBundle": false,
+ "_integrity": "sha512-Yt4bTEqJ32zml6FbTIaEUZS4Wo8MI97Q/fqU3TgbflKln5YEY7nXcr4Y/fzC/2n6jZG7j7XZsP0LFM557WJ+Fw==",
+ "_location": "/ipfs",
+ "_phantomChildren": {
+ "@sindresorhus/is": "0.14.0",
+ "@szmarczak/http-timer": "1.1.2",
+ "ansi-styles": "3.2.1",
+ "cacheable-request": "6.1.0",
+ "chalk": "2.4.2",
+ "decamelize": "1.2.0",
+ "decompress-response": "3.3.0",
+ "dot-prop": "4.2.0",
+ "duplexer3": "0.1.4",
+ "emoji-regex": "7.0.3",
+ "find-up": "3.0.0",
+ "graceful-fs": "4.1.15",
+ "has-yarn": "2.1.0",
+ "import-lazy": "2.1.0",
+ "inherits": "2.0.3",
+ "is-ci": "2.0.0",
+ "is-installed-globally": "0.1.0",
+ "is-yarn-global": "0.3.0",
+ "lowercase-keys": "1.0.1",
+ "make-dir": "1.3.0",
+ "mimic-response": "1.0.1",
+ "ms": "2.1.1",
+ "p-cancelable": "1.1.0",
+ "pump": "3.0.0",
+ "rc": "1.2.8",
+ "require-directory": "2.1.1",
+ "semver-diff": "2.1.0",
+ "set-blocking": "2.0.0",
+ "term-size": "1.2.0",
+ "to-readable-stream": "1.0.0",
+ "type-fest": "0.3.1",
+ "unique-string": "1.0.0",
+ "util-deprecate": "1.0.2",
+ "which-module": "2.0.0",
+ "widest-line": "2.0.1",
+ "write-file-atomic": "2.4.2",
+ "xdg-basedir": "3.0.0",
+ "y18n": "4.0.0"
+ },
+ "_requested": {
+ "type": "version",
+ "registry": true,
+ "raw": "ipfs@0.38.0",
+ "name": "ipfs",
+ "escapedName": "ipfs",
+ "rawSpec": "0.38.0",
+ "saveSpec": null,
+ "fetchSpec": "0.38.0"
+ },
+ "_requiredBy": [
+ "/"
+ ],
+ "_resolved": "https://registry.npmjs.org/ipfs/-/ipfs-0.38.0.tgz",
+ "_spec": "0.38.0",
+ "_where": "C:\\Users\\user\\Documents\\Projects\\desktop-wallet\\Ether1DesktopWallet",
+ "bin": {
+ "jsipfs": "src/cli/bin.js"
+ },
+ "browser": {
+ "./src/core/components/init-assets.js": false,
+ "./src/core/runtime/add-from-fs-nodejs.js": "./src/core/runtime/add-from-fs-browser.js",
+ "./src/core/runtime/config-nodejs.js": "./src/core/runtime/config-browser.js",
+ "./src/core/runtime/dns-nodejs.js": "./src/core/runtime/dns-browser.js",
+ "./src/core/runtime/fetch-nodejs.js": "./src/core/runtime/fetch-browser.js",
+ "./src/core/runtime/libp2p-nodejs.js": "./src/core/runtime/libp2p-browser.js",
+ "./src/core/runtime/libp2p-pubsub-routers-nodejs.js": "./src/core/runtime/libp2p-pubsub-routers-browser.js",
+ "./src/core/runtime/preload-nodejs.js": "./src/core/runtime/preload-browser.js",
+ "./src/core/runtime/repo-nodejs.js": "./src/core/runtime/repo-browser.js",
+ "./src/core/runtime/ipld-nodejs.js": "./src/core/runtime/ipld-browser.js",
+ "./test/utils/create-repo-nodejs.js": "./test/utils/create-repo-browser.js",
+ "stream": "readable-stream"
+ },
+ "browser-all-ipld-formats": {
+ "./src/core/runtime/ipld-browser.js": "./src/core/runtime/ipld-browser-all.js"
+ },
+ "bugs": {
+ "url": "https://github.com/ipfs/js-ipfs/issues"
+ },
+ "contributors": [
+ {
+ "name": "0xflotus",
+ "email": "0xflotus@gmail.com"
+ },
+ {
+ "name": "A_A",
+ "email": "21040751+Otto-AA@users.noreply.github.com"
+ },
+ {
+ "name": "Alan Shaw",
+ "email": "alan.shaw@protocol.ai"
+ },
+ {
+ "name": "Alan Shaw",
+ "email": "alan@tableflip.io"
+ },
+ {
+ "name": "Alex North",
+ "email": "alex@alexnorth.me"
+ },
+ {
+ "name": "Andrew Nesbitt",
+ "email": "andrewnez@gmail.com"
+ },
+ {
+ "name": "Andrew de Andrade",
+ "email": "andrew@deandrade.com.br"
+ },
+ {
+ "name": "André Cruz",
+ "email": "andremiguelcruz@msn.com"
+ },
+ {
+ "name": "Arkadiy Kukarkin",
+ "email": "parkan@users.noreply.github.com"
+ },
+ {
+ "name": "Arpit Agarwal",
+ "email": "93arpit@gmail.com"
+ },
+ {
+ "name": "Arpit Agarwal",
+ "email": "atvanguard@users.noreply.github.com"
+ },
+ {
+ "name": "Bernard Mordan",
+ "email": "bernard@tableflip.io"
+ },
+ {
+ "name": "Brian Vander Schaaf",
+ "email": "bvs330@gmail.com"
+ },
+ {
+ "name": "Bruno Zell",
+ "email": "bruno.zzell@gmail.com"
+ },
+ {
+ "name": "CHEVALAY JOSSELIN",
+ "email": "josselin54.chevalay@gmail.com"
+ },
+ {
+ "name": "Caio Gondim",
+ "email": "me@caiogondim.com"
+ },
+ {
+ "name": "Chance Hudson",
+ "email": "jchancehud@gmail.com"
+ },
+ {
+ "name": "Chirag Shinde",
+ "email": "chirag-shinde@users.noreply.github.com"
+ },
+ {
+ "name": "Christian Couder",
+ "email": "chriscool@tuxfamily.org"
+ },
+ {
+ "name": "Dafeng",
+ "email": "dfguo.joe@gmail.com"
+ },
+ {
+ "name": "Dan Ordille",
+ "email": "dordille@gmail.com"
+ },
+ {
+ "name": "Dan Shields",
+ "email": "35669742+NukeManDan@users.noreply.github.com"
+ },
+ {
+ "name": "Daniel J. O'Quinn",
+ "email": "danieljoquinn@gmail.com"
+ },
+ {
+ "name": "Daniela Borges Matos de Carvalho",
+ "email": "alunassertiva@gmail.com"
+ },
+ {
+ "name": "David Dias",
+ "email": "daviddias.p@gmail.com"
+ },
+ {
+ "name": "David Gilbertson",
+ "email": "gilbertson.david@gmail.com"
+ },
+ {
+ "name": "David da Silva",
+ "email": "dasilvacontin@gmail.com"
+ },
+ {
+ "name": "Diogo Silva",
+ "email": "fsdiogo@gmail.com"
+ },
+ {
+ "name": "Dmitriy Ryajov",
+ "email": "dryajov@gmail.com"
+ },
+ {
+ "name": "Dominic Della Valle",
+ "email": "ddvpublic@Gmail.com"
+ },
+ {
+ "name": "Dzmitry Bachko",
+ "email": "dbachko@gmail.com"
+ },
+ {
+ "name": "Enrico Marino",
+ "email": "enrico.marino@email.com"
+ },
+ {
+ "name": "Faheel Ahmad",
+ "email": "faheel@live.in"
+ },
+ {
+ "name": "Felix Yan",
+ "email": "felixonmars@archlinux.org"
+ },
+ {
+ "name": "Francisco Baio Dias",
+ "email": "xicombd@gmail.com"
+ },
+ {
+ "name": "Francisco Baio Dias",
+ "email": "francisco@typeform.com"
+ },
+ {
+ "name": "Friedel Ziegelmayer",
+ "email": "dignifiedquire@gmail.com"
+ },
+ {
+ "name": "Gar",
+ "email": "gar+gh@danger.computer"
+ },
+ {
+ "name": "Georgios Rassias",
+ "email": "georassias@gmail.com"
+ },
+ {
+ "name": "Gorka Ludlow",
+ "email": "gorka@aquigorka.com"
+ },
+ {
+ "name": "Grant Herman",
+ "email": "grantlouisherman041@gmail.com"
+ },
+ {
+ "name": "Greenkeeper",
+ "email": "support@greenkeeper.io"
+ },
+ {
+ "name": "Haad",
+ "email": "haadcode@users.noreply.github.com"
+ },
+ {
+ "name": "Haoliang Yu",
+ "email": "haoliangyu@users.noreply.github.com"
+ },
+ {
+ "name": "Harsh Vakharia",
+ "email": "harshjv@users.noreply.github.com"
+ },
+ {
+ "name": "Henrique Dias",
+ "email": "hacdias@gmail.com"
+ },
+ {
+ "name": "Henry Rodrick",
+ "email": "moshisushi@gmail.com"
+ },
+ {
+ "name": "Heo Sangmin",
+ "email": "heo@mapiacompany.com"
+ },
+ {
+ "name": "Hugo Dias",
+ "email": "hugomrdias@gmail.com"
+ },
+ {
+ "name": "Hugo Dias",
+ "email": "mail@hugodias.me"
+ },
+ {
+ "name": "Irakli Gozalishvili",
+ "email": "contact@gozala.io"
+ },
+ {
+ "name": "Jacob Heun",
+ "email": "jacobheun@gmail.com"
+ },
+ {
+ "name": "Jacob Heun",
+ "email": "jake@andyet.net"
+ },
+ {
+ "name": "Jade Meskill",
+ "email": "jade.meskill@gmail.com"
+ },
+ {
+ "name": "Johannes Wikner",
+ "email": "johannes.wikner@gmail.com"
+ },
+ {
+ "name": "Jon Schlinkert",
+ "email": "dev@sellside.com"
+ },
+ {
+ "name": "Jonathan",
+ "email": "jkrone@vt.edu"
+ },
+ {
+ "name": "Jonybang",
+ "email": "Jonybange@gmail.com"
+ },
+ {
+ "name": "João Antunes",
+ "email": "j.goncalo.antunes@gmail.com"
+ },
+ {
+ "name": "João Santos",
+ "email": "joaosantos15@users.noreply.github.com"
+ },
+ {
+ "name": "Kevin Wang",
+ "email": "kevin@fossa.io"
+ },
+ {
+ "name": "Lars Gierth",
+ "email": "larsg@systemli.org"
+ },
+ {
+ "name": "Lukas Drgon",
+ "email": "lukas.drgon@gmail.com"
+ },
+ {
+ "name": "Maciej Krüger",
+ "email": "mkg20001@gmail.com"
+ },
+ {
+ "name": "Marcin Rataj",
+ "email": "lidel@lidel.org"
+ },
+ {
+ "name": "Marius Darila",
+ "email": "marius.darila@gmail.com"
+ },
+ {
+ "name": "Mat Kelly",
+ "email": "machawk1@gmail.com"
+ },
+ {
+ "name": "Michelle Lee",
+ "email": "michelle@protocol.ai"
+ },
+ {
+ "name": "Mikeal Rogers",
+ "email": "mikeal.rogers@gmail.com"
+ },
+ {
+ "name": "Mithgol",
+ "email": "getgit@mithgol.ru"
+ },
+ {
+ "name": "Molly",
+ "email": "momack2@users.noreply.github.com"
+ },
+ {
+ "name": "Mounish Sai",
+ "email": "pvsmounish@gmail.com"
+ },
+ {
+ "name": "My9Bot",
+ "email": "34904312+My9Bot@users.noreply.github.com"
+ },
+ {
+ "name": "Nick Poulden",
+ "email": "nick@poulden.com"
+ },
+ {
+ "name": "Nitin Patel",
+ "email": "31539366+niinpatel@users.noreply.github.com"
+ },
+ {
+ "name": "Nuno Nogueira",
+ "email": "nunofmn@gmail.com"
+ },
+ {
+ "name": "Oli Evans",
+ "email": "oli@tableflip.io"
+ },
+ {
+ "name": "Oskar Nyberg",
+ "email": "oskar@oskarnyberg.com"
+ },
+ {
+ "name": "Pascal Precht",
+ "email": "pascal.precht@googlemail.com"
+ },
+ {
+ "name": "Pau Ramon Revilla",
+ "email": "masylum@gmail.com"
+ },
+ {
+ "name": "Paulo Rodrigues",
+ "email": "me@paulogr.com"
+ },
+ {
+ "name": "Pedro Teixeira",
+ "email": "i@pgte.me"
+ },
+ {
+ "name": "Portia Burton",
+ "email": "plburton@gmail.com"
+ },
+ {
+ "name": "Prabhakar Poudel",
+ "email": "yuvrajzohan@gmail.com"
+ },
+ {
+ "name": "Qmstream",
+ "email": "51881352+Qmstream@users.noreply.github.com"
+ },
+ {
+ "name": "Raoul Millais",
+ "email": "raoul@raoulmillais.com"
+ },
+ {
+ "name": "RasmusErik Voel Jensen",
+ "email": "github@solsort.com"
+ },
+ {
+ "name": "Richard Littauer",
+ "email": "richard.littauer@gmail.com"
+ },
+ {
+ "name": "Richard Schneider",
+ "email": "makaretu@gmail.com"
+ },
+ {
+ "name": "Rob Brackett",
+ "email": "rob@robbrackett.com"
+ },
+ {
+ "name": "Rod Keys",
+ "email": "rod@zokos.com"
+ },
+ {
+ "name": "Sangwon Hong",
+ "email": "qpakzk@gmail.com"
+ },
+ {
+ "name": "Sid Harder",
+ "email": "sideharder@gmail.com"
+ },
+ {
+ "name": "SidHarder",
+ "email": "softwarenavigator@gmail.com"
+ },
+ {
+ "name": "Stephen Whitmore",
+ "email": "stephen.whitmore@gmail.com"
+ },
+ {
+ "name": "Stephen Whitmore",
+ "email": "noffle@users.noreply.github.com"
+ },
+ {
+ "name": "Steven Allen",
+ "email": "steven@stebalien.com"
+ },
+ {
+ "name": "Terence Pae",
+ "email": "terencepae@gmail.com"
+ },
+ {
+ "name": "Teri Chadbourne",
+ "email": "terichadbourne@users.noreply.github.com"
+ },
+ {
+ "name": "Uroš Jurglič",
+ "email": "jurglic@gmail.com"
+ },
+ {
+ "name": "Vasco Santos",
+ "email": "vasco.santos@moxy.studio"
+ },
+ {
+ "name": "Vasco Santos",
+ "email": "vasco.santos@ua.pt"
+ },
+ {
+ "name": "Volker Mische",
+ "email": "volker.mische@gmail.com"
+ },
+ {
+ "name": "Xiao Liang",
+ "email": "yxliang01@users.noreply.github.com"
+ },
+ {
+ "name": "Yahya",
+ "email": "ya7yaz@gmail.com"
+ },
+ {
+ "name": "Yole",
+ "email": "yole@ultiledger.io"
+ },
+ {
+ "name": "achingbrain",
+ "email": "alex@achingbrain.net"
+ },
+ {
+ "name": "bitspill",
+ "email": "bitspill+github@bitspill.net"
+ },
+ {
+ "name": "datafatmunger",
+ "email": "jbg@peerparty.org"
+ },
+ {
+ "name": "dirkmc",
+ "email": "dirkmdev@gmail.com"
+ },
+ {
+ "name": "dirkmc",
+ "email": "dirk@mccormick.cx"
+ },
+ {
+ "name": "greenkeeper[bot]",
+ "email": "23040076+greenkeeper[bot]@users.noreply.github.com"
+ },
+ {
+ "name": "greenkeeper[bot]",
+ "email": "greenkeeper[bot]@users.noreply.github.com"
+ },
+ {
+ "name": "haad",
+ "email": "haad@headbanggames.com"
+ },
+ {
+ "name": "hapsody",
+ "email": "hapsody@gmail.com"
+ },
+ {
+ "name": "jbenet",
+ "email": "juan@benet.ai"
+ },
+ {
+ "name": "jonahweissman",
+ "email": "19804455+jonahweissman@users.noreply.github.com"
+ },
+ {
+ "name": "kevingzhang",
+ "email": "kevin.zhang.canada@gmail.com"
+ },
+ {
+ "name": "kumavis",
+ "email": "kumavis@users.noreply.github.com"
+ },
+ {
+ "name": "nginnever",
+ "email": "ginneversource@gmail.com"
+ },
+ {
+ "name": "npmcdn-to-unpkg-bot",
+ "email": "npmcdn-to-unpkg-bot@users.noreply.github.com"
+ },
+ {
+ "name": "robbsolter",
+ "email": "35879806+robbsolter@users.noreply.github.com"
+ },
+ {
+ "name": "seungwon-kang",
+ "email": "ksw3894@gmail.com"
+ },
+ {
+ "name": "tcme",
+ "email": "hi@this-connect.me"
+ },
+ {
+ "name": "victorbjelkholm",
+ "email": "victorbjelkholm@gmail.com"
+ },
+ {
+ "name": "Łukasz Magiera",
+ "email": "magik6k@users.noreply.github.com"
+ },
+ {
+ "name": "Максим Ильин",
+ "email": "negamaxi@gmail.com"
+ }
+ ],
+ "dependencies": {
+ "@hapi/ammo": "^3.1.1",
+ "@hapi/boom": "^7.4.3",
+ "@hapi/hapi": "^18.3.2",
+ "@hapi/joi": "^15.0.1",
+ "array-shuffle": "^1.0.1",
+ "async": "^2.6.1",
+ "async-iterator-all": "^1.0.0",
+ "async-iterator-to-pull-stream": "^1.3.0",
+ "async-iterator-to-stream": "^1.1.0",
+ "base32.js": "~0.1.0",
+ "bignumber.js": "^9.0.0",
+ "binary-querystring": "~0.1.2",
+ "bl": "^3.0.0",
+ "bs58": "^4.0.1",
+ "buffer-peek-stream": "^1.0.1",
+ "byteman": "^1.3.5",
+ "cid-tool": "~0.3.0",
+ "cids": "~0.7.1",
+ "class-is": "^1.1.0",
+ "datastore-core": "~0.6.0",
+ "datastore-pubsub": "~0.1.1",
+ "debug": "^4.1.0",
+ "dlv": "^1.1.3",
+ "err-code": "^2.0.0",
+ "explain-error": "^1.0.4",
+ "file-type": "^12.0.1",
+ "fnv1a": "^1.0.1",
+ "fsm-event": "^2.1.0",
+ "get-folder-size": "^2.0.0",
+ "glob": "^7.1.3",
+ "hapi-pino": "^6.1.0",
+ "hashlru": "^2.3.0",
+ "human-to-milliseconds": "^2.0.0",
+ "interface-datastore": "~0.6.0",
+ "ipfs-bitswap": "~0.25.1",
+ "ipfs-block": "~0.8.1",
+ "ipfs-block-service": "~0.15.2",
+ "ipfs-http-client": "^37.0.1",
+ "ipfs-http-response": "~0.3.1",
+ "ipfs-mfs": "^0.12.2",
+ "ipfs-multipart": "^0.2.0",
+ "ipfs-repo": "~0.26.6",
+ "ipfs-unixfs": "~0.1.16",
+ "ipfs-unixfs-exporter": "~0.37.7",
+ "ipfs-unixfs-importer": "~0.39.11",
+ "ipfs-utils": "^0.3.0",
+ "ipld": "~0.24.1",
+ "ipld-bitcoin": "~0.3.0",
+ "ipld-dag-cbor": "~0.15.0",
+ "ipld-dag-pb": "~0.17.4",
+ "ipld-ethereum": "^4.0.0",
+ "ipld-git": "~0.5.0",
+ "ipld-raw": "^4.0.0",
+ "ipld-zcash": "~0.3.0",
+ "ipns": "~0.5.2",
+ "is-domain-name": "^1.0.1",
+ "is-ipfs": "~0.6.1",
+ "is-pull-stream": "~0.0.0",
+ "is-stream": "^2.0.0",
+ "iso-url": "~0.4.6",
+ "it-pipe": "^1.0.1",
+ "it-to-stream": "^0.1.1",
+ "just-safe-set": "^2.1.0",
+ "kind-of": "^6.0.2",
+ "libp2p": "~0.26.1",
+ "libp2p-bootstrap": "~0.9.3",
+ "libp2p-crypto": "~0.16.0",
+ "libp2p-delegated-content-routing": "^0.2.4",
+ "libp2p-delegated-peer-routing": "^0.2.4",
+ "libp2p-floodsub": "^0.18.0",
+ "libp2p-gossipsub": "~0.0.5",
+ "libp2p-kad-dht": "~0.15.3",
+ "libp2p-keychain": "~0.4.2",
+ "libp2p-mdns": "~0.12.0",
+ "libp2p-record": "~0.6.3",
+ "libp2p-secio": "~0.11.0",
+ "libp2p-tcp": "~0.13.1",
+ "libp2p-webrtc-star": "~0.16.0",
+ "libp2p-websocket-star-multi": "~0.4.3",
+ "libp2p-websockets": "~0.12.3",
+ "lodash": "^4.17.15",
+ "mafmt": "^6.0.10",
+ "merge-options": "^1.0.1",
+ "mime-types": "^2.1.21",
+ "mkdirp": "~0.5.1",
+ "mortice": "^2.0.0",
+ "multiaddr": "^6.1.0",
+ "multiaddr-to-uri": "^5.0.0",
+ "multibase": "~0.6.0",
+ "multicodec": "~0.5.5",
+ "multihashes": "~0.4.14",
+ "multihashing-async": "~0.6.0",
+ "node-fetch": "^2.3.0",
+ "peer-book": "~0.9.0",
+ "peer-id": "~0.12.3",
+ "peer-info": "~0.15.0",
+ "progress": "^2.0.1",
+ "prom-client": "^11.5.3",
+ "prometheus-gc-stats": "~0.6.0",
+ "promise-nodeify": "^3.0.1",
+ "promisify-es6": "^1.0.3",
+ "protons": "^1.0.1",
+ "pull-abortable": "^4.1.1",
+ "pull-cat": "^1.1.11",
+ "pull-defer": "~0.2.3",
+ "pull-file": "^1.1.0",
+ "pull-mplex": "~0.1.1",
+ "pull-ndjson": "~0.1.1",
+ "pull-pushable": "^2.2.0",
+ "pull-sort": "^1.0.1",
+ "pull-stream": "^3.6.14",
+ "pull-stream-to-async-iterator": "^1.0.2",
+ "pull-stream-to-stream": "^1.3.4",
+ "pull-traverse": "^1.0.3",
+ "readable-stream": "^3.4.0",
+ "receptacle": "^1.3.2",
+ "semver": "^6.3.0",
+ "stream-to-pull-stream": "^1.7.3",
+ "superstruct": "~0.6.2",
+ "tar-stream": "^2.0.0",
+ "temp": "~0.9.0",
+ "update-notifier": "^3.0.1",
+ "uri-to-multiaddr": "^3.0.1",
+ "varint": "^5.0.0",
+ "yargs": "^14.0.0",
+ "yargs-promise": "^1.1.0"
+ },
+ "description": "JavaScript implementation of the IPFS specification",
+ "devDependencies": {
+ "aegir": "^20.1.0",
+ "base64url": "^3.0.1",
+ "chai": "^4.2.0",
+ "clear-module": "^4.0.0",
+ "delay": "^4.1.0",
+ "detect-node": "^2.0.4",
+ "dir-compare": "^1.7.3",
+ "dirty-chai": "^2.0.1",
+ "execa": "^2.0.4",
+ "form-data": "^2.5.1",
+ "hat": "0.0.3",
+ "interface-ipfs-core": "^0.113.0",
+ "ipfs-interop": "~0.1.0",
+ "ipfsd-ctl": "0.46.0",
+ "libp2p-websocket-star": "~0.10.2",
+ "ncp": "^2.0.0",
+ "p-event": "^4.1.0",
+ "qs": "^6.5.2",
+ "rimraf": "^3.0.0",
+ "sinon": "^7.4.2",
+ "stream-to-promise": "^2.2.0"
+ },
+ "engines": {
+ "node": ">=10.0.0",
+ "npm": ">=6.0.0"
+ },
+ "files": [
+ "src",
+ "dist"
+ ],
+ "homepage": "https://js.ipfs.io",
+ "keywords": [
+ "IPFS"
+ ],
+ "leadMaintainer": "Alan Shaw ",
+ "license": "MIT",
+ "main": "src/core/index.js",
+ "name": "ipfs",
+ "optionalDependencies": {
+ "prom-client": "^11.5.3",
+ "prometheus-gc-stats": "~0.6.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ipfs/js-ipfs.git"
+ },
+ "scripts": {
+ "benchmark": "echo \"Error: no benchmarks yet\" && exit 1",
+ "benchmark:browser": "echo \"Error: no benchmarks yet\" && exit 1",
+ "benchmark:node": "echo \"Error: no benchmarks yet\" && exit 1",
+ "benchmark:node:core": "echo \"Error: no benchmarks yet\" && exit 1",
+ "benchmark:node:http": "echo \"Error: no benchmarks yet\" && exit 1",
+ "build": "aegir build",
+ "coverage": "nyc --reporter=text --reporter=lcov npm run test:node",
+ "lint": "aegir lint",
+ "release": "aegir release -t node -t browser",
+ "release-major": "aegir release --type major -t node -t browser",
+ "release-minor": "aegir release --type minor -t node -t browser",
+ "test": "aegir test",
+ "test:bootstrapers": "IPFS_TEST=bootstrapers aegir test -t browser -f test/bootstrapers.js",
+ "test:browser": "aegir test -t browser",
+ "test:external": "aegir test-external",
+ "test:interop": "IPFS_JS_EXEC=$PWD/src/cli/bin.js ipfs-interop",
+ "test:node": "aegir test -t node",
+ "test:node:cli": "aegir test -t node -f test/cli/index.js",
+ "test:node:core": "aegir test -t node -f test/core/**/*.js",
+ "test:node:gateway": "aegir test -t node -f test/gateway/index.js",
+ "test:node:http": "aegir test -t node -f test/http-api/index.js",
+ "test:node:interface": "aegir test -t node -f test/core/interface.spec.js",
+ "test:webworker": "aegir test -t webworker"
+ },
+ "version": "0.38.0"
+}
+
+},{}],476:[function(require,module,exports){
+'use strict'
+
+const waterfall = require('async/waterfall')
+const RepoErrors = require('ipfs-repo').errors
+
+// Boot an IPFS node depending on the options set
+module.exports = (self) => {
+ self.log('booting')
+ const options = self._options
+ const doInit = options.init
+ const doStart = options.start
+
+ // Do the actual boot sequence
+ waterfall([
+ // Checks if a repo exists, and if so opens it
+ // Will return callback with a bool indicating the existence
+ // of the repo
+ (cb) => {
+ // nothing to do
+ if (!self._repo.closed) {
+ return cb(null, true)
+ }
+
+ self._repo.open((err, res) => {
+ if (isRepoUninitializedError(err)) return cb(null, false)
+ if (err) return cb(err)
+ cb(null, true)
+ })
+ },
+ (repoOpened, cb) => {
+ // Init with existing initialized, opened, repo
+ if (repoOpened) {
+ return self.init({ repo: self._repo }, (err) => {
+ if (err) return cb(Object.assign(err, { emitted: true }))
+ cb()
+ })
+ }
+
+ if (doInit) {
+ const initOptions = Object.assign(
+ { bits: 2048, pass: self._options.pass },
+ typeof options.init === 'object' ? options.init : {}
+ )
+ return self.init(initOptions, (err) => {
+ if (err) return cb(Object.assign(err, { emitted: true }))
+ cb()
+ })
+ }
+
+ cb()
+ },
+ (cb) => {
+ // No problem, we don't have to start the node
+ if (!doStart) {
+ return cb()
+ }
+
+ self.start((err) => {
+ if (err) return cb(Object.assign(err, { emitted: true }))
+ cb()
+ })
+ }
+ ], (err) => {
+ if (err) {
+ if (!err.emitted) {
+ self.emit('error', err)
+ }
+ return
+ }
+ self.log('booted')
+ self.emit('ready')
+ })
+}
+
+function isRepoUninitializedError (err) {
+ if (!err) {
+ return false
+ }
+
+ // If the error is that no repo exists,
+ // which happens when the version file is not found
+ // we just want to signal that no repo exist, not
+ // fail the whole process.
+
+ // Use standardized errors as much as possible
+ if (err.code === RepoErrors.ERR_REPO_NOT_INITIALIZED) {
+ return true
+ }
+
+ // TODO: As error codes continue to be standardized, this logic can be phase out;
+ // it is here to maintain compatibility
+ if (err.message.match(/not found/) || // indexeddb
+ err.message.match(/ENOENT/) || // fs
+ err.message.match(/No value/) // memory
+ ) {
+ return true
+ }
+
+ return false
+}
+
+},{"async/waterfall":102,"ipfs-repo":395}],477:[function(require,module,exports){
+'use strict'
+
+const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR
+const promisify = require('promisify-es6')
+const setImmediate = require('async/setImmediate')
+const Big = require('bignumber.js')
+const CID = require('cids')
+const PeerId = require('peer-id')
+const errCode = require('err-code')
+
+function formatWantlist (list, cidBase) {
+ return Array.from(list).map((e) => ({ '/': e[1].cid.toBaseEncodedString(cidBase) }))
+}
+
+module.exports = function bitswap (self) {
+ return {
+ wantlist: promisify((peerId, callback) => {
+ if (typeof peerId === 'function') {
+ callback = peerId
+ peerId = null
+ }
+
+ if (!self.isOnline()) {
+ return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
+ }
+
+ let list
+ if (peerId) {
+ try {
+ peerId = PeerId.createFromB58String(peerId)
+ } catch (e) {
+ peerId = null
+ }
+ if (!peerId) {
+ return setImmediate(() => callback(new Error('Invalid peerId')))
+ }
+ list = self._bitswap.wantlistForPeer(peerId)
+ } else {
+ list = self._bitswap.getWantlist()
+ }
+
+ setImmediate(() => callback(null, { Keys: formatWantlist(list) }))
+ }),
+
+ stat: promisify((callback) => {
+ if (!self.isOnline()) {
+ return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
+ }
+
+ const snapshot = self._bitswap.stat().snapshot
+
+ setImmediate(() => {
+ callback(null, {
+ provideBufLen: parseInt(snapshot.providesBufferLength.toString()),
+ blocksReceived: new Big(snapshot.blocksReceived),
+ wantlist: formatWantlist(self._bitswap.getWantlist()),
+ peers: self._bitswap.peers().map((id) => id.toB58String()),
+ dupBlksReceived: new Big(snapshot.dupBlksReceived),
+ dupDataReceived: new Big(snapshot.dupDataReceived),
+ dataReceived: new Big(snapshot.dataReceived),
+ blocksSent: new Big(snapshot.blocksSent),
+ dataSent: new Big(snapshot.dataSent)
+ })
+ })
+ }),
+
+ unwant: promisify((keys, callback) => {
+ if (!self.isOnline()) {
+ return setImmediate(() => callback(new Error(OFFLINE_ERROR)))
+ }
+
+ if (!Array.isArray(keys)) {
+ keys = [keys]
+ }
+
+ try {
+ keys = keys.map((key) => {
+ if (CID.isCID(key)) {
+ return key
+ }
+ return new CID(key)
+ })
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ setImmediate(() => callback(null, self._bitswap.unwant(keys)))
+ })
+ }
+}
+
+},{"../utils":560,"async/setImmediate":96,"bignumber.js":110,"cids":185,"err-code":268,"peer-id":1253,"promisify-es6":1263}],478:[function(require,module,exports){
+'use strict'
+
+const Block = require('ipfs-block')
+const multihashing = require('multihashing-async')
+const CID = require('cids')
+const waterfall = require('async/waterfall')
+const setImmediate = require('async/setImmediate')
+const promisify = require('promisify-es6')
+const errCode = require('err-code')
+
+module.exports = function block (self) {
+ return {
+ get: promisify((cid, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ try {
+ cid = cleanCid(cid)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ self._blockService.get(cid, callback)
+ }),
+ put: promisify((block, options, callback) => {
+ callback = callback || function noop () {}
+
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ if (Array.isArray(block)) {
+ return callback(new Error('Array is not supported'))
+ }
+
+ waterfall([
+ (cb) => {
+ if (Block.isBlock(block)) {
+ return cb(null, block)
+ }
+
+ if (options.cid && CID.isCID(options.cid)) {
+ return cb(null, new Block(block, options.cid))
+ }
+
+ const mhtype = options.mhtype || 'sha2-256'
+ const format = options.format || 'dag-pb'
+ let cidVersion
+ // const mhlen = options.mhlen || 0
+
+ if (options.version == null) {
+ // Pick appropriate CID version
+ cidVersion = mhtype === 'sha2-256' && format === 'dag-pb' ? 0 : 1
+ } else {
+ cidVersion = options.version
+ }
+
+ multihashing(block, mhtype, (err, multihash) => {
+ if (err) {
+ return cb(err)
+ }
+
+ let cid
+ try {
+ cid = new CID(cidVersion, format, multihash)
+ } catch (err) {
+ return cb(err)
+ }
+
+ cb(null, new Block(block, cid))
+ })
+ },
+ (block, cb) => self._gcLock.readLock((_cb) => {
+ self._blockService.put(block, (err) => {
+ if (err) {
+ return _cb(err)
+ }
+
+ if (options.preload !== false) {
+ self._preload(block.cid)
+ }
+
+ _cb(null, block)
+ })
+ }, cb)
+ ], callback)
+ }),
+ rm: promisify((cid, callback) => {
+ try {
+ cid = cleanCid(cid)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ // We need to take a write lock here to ensure that adding and removing
+ // blocks are exclusive operations
+ self._gcLock.writeLock((cb) => self._blockService.delete(cid, cb), callback)
+ }),
+ stat: promisify((cid, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ try {
+ cid = cleanCid(cid)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ self._blockService.get(cid, (err, block) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, {
+ key: cid.toString(),
+ size: block.data.length
+ })
+ })
+ })
+ }
+}
+
+function cleanCid (cid) {
+ if (CID.isCID(cid)) {
+ return cid
+ }
+
+ // CID constructor knows how to do the cleaning :)
+ return new CID(cid)
+}
+
+},{"async/setImmediate":96,"async/waterfall":102,"cids":185,"err-code":268,"ipfs-block":353,"multihashing-async":1161,"promisify-es6":1263}],479:[function(require,module,exports){
+(function (setImmediate){
+'use strict'
+
+const defaultConfig = require('../runtime/config-nodejs.js')
+const isMultiaddr = require('mafmt').IPFS.matches
+const promisify = require('promisify-es6')
+
+function isValidMultiaddr (ma) {
+ try {
+ return isMultiaddr(ma)
+ } catch (err) {
+ return false
+ }
+}
+
+function invalidMultiaddrError (ma) {
+ return new Error(`${ma} is not a valid Multiaddr`)
+}
+
+module.exports = function bootstrap (self) {
+ return {
+ list: promisify((callback) => {
+ self._repo.config.get((err, config) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, { Peers: config.Bootstrap })
+ })
+ }),
+ add: promisify((multiaddr, args, callback) => {
+ if (typeof args === 'function') {
+ callback = args
+ args = { default: false }
+ }
+
+ if (multiaddr && !isValidMultiaddr(multiaddr)) {
+ return setImmediate(() => callback(invalidMultiaddrError(multiaddr)))
+ }
+
+ self._repo.config.get((err, config) => {
+ if (err) {
+ return callback(err)
+ }
+ if (args.default) {
+ config.Bootstrap = defaultConfig().Bootstrap
+ } else if (multiaddr && config.Bootstrap.indexOf(multiaddr) === -1) {
+ config.Bootstrap.push(multiaddr)
+ }
+ self._repo.config.set(config, (err) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, {
+ Peers: args.default ? defaultConfig().Bootstrap : [multiaddr]
+ })
+ })
+ })
+ }),
+ rm: promisify((multiaddr, args, callback) => {
+ if (typeof args === 'function') {
+ callback = args
+ args = { all: false }
+ }
+ if (multiaddr && !isValidMultiaddr(multiaddr)) {
+ return setImmediate(() => callback(invalidMultiaddrError(multiaddr)))
+ }
+
+ self._repo.config.get((err, config) => {
+ if (err) {
+ return callback(err)
+ }
+ if (args.all) {
+ config.Bootstrap = []
+ } else {
+ config.Bootstrap = config.Bootstrap.filter((mh) => mh !== multiaddr)
+ }
+
+ self._repo.config.set(config, (err) => {
+ if (err) {
+ return callback(err)
+ }
+
+ const res = []
+ if (!args.all && multiaddr) {
+ res.push(multiaddr)
+ }
+
+ callback(null, { Peers: res })
+ })
+ })
+ })
+ }
+}
+
+}).call(this,require("timers").setImmediate)
+},{"../runtime/config-nodejs.js":551,"mafmt":1125,"promisify-es6":1263,"timers":1500}],480:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+
+module.exports = function config (self) {
+ return {
+ get: promisify((key, callback) => {
+ if (typeof key === 'function') {
+ callback = key
+ key = undefined
+ }
+
+ return self._repo.config.get(key, callback)
+ }),
+ set: promisify((key, value, callback) => {
+ self._repo.config.set(key, value, callback)
+ }),
+ replace: promisify((config, callback) => {
+ self._repo.config.set(config, callback)
+ })
+ }
+}
+
+},{"promisify-es6":1263}],481:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const promisify = require('promisify-es6')
+const CID = require('cids')
+const pull = require('pull-stream')
+const iterToPull = require('async-iterator-to-pull-stream')
+const setImmediate = require('async/setImmediate')
+const errCode = require('err-code')
+const multicodec = require('multicodec')
+
+module.exports = function dag (self) {
+ return {
+ put: promisify((dagNode, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ if (options.cid && (options.format || options.hashAlg)) {
+ return callback(new Error('Can\'t put dag node. Please provide either `cid` OR `format` and `hashAlg` options.'))
+ } else if (((options.format && !options.hashAlg) || (!options.format && options.hashAlg))) {
+ return callback(new Error('Can\'t put dag node. Please provide `format` AND `hashAlg` options.'))
+ }
+
+ const optionDefaults = {
+ format: multicodec.DAG_CBOR,
+ hashAlg: multicodec.SHA2_256
+ }
+
+ // The IPLD expects the format and hashAlg as constants
+ if (options.format && typeof options.format === 'string') {
+ const constantName = options.format.toUpperCase().replace(/-/g, '_')
+ options.format = multicodec[constantName]
+ }
+ if (options.hashAlg && typeof options.hashAlg === 'string') {
+ const constantName = options.hashAlg.toUpperCase().replace(/-/g, '_')
+ options.hashAlg = multicodec[constantName]
+ }
+
+ options = options.cid ? options : Object.assign({}, optionDefaults, options)
+
+ // js-ipld defaults to verion 1 CIDs. Hence set version 0 explicitly for
+ // dag-pb nodes
+ if (options.version === undefined) {
+ if (options.format === multicodec.DAG_PB && options.hashAlg === multicodec.SHA2_256) {
+ options.version = 0
+ } else {
+ options.version = 1
+ }
+ }
+
+ self._ipld.put(dagNode, options.format, {
+ hashAlg: options.hashAlg,
+ cidVersion: options.version
+ }).then(
+ (cid) => {
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+ return callback(null, cid)
+ },
+ (error) => callback(error)
+ )
+ }),
+
+ get: promisify((cid, path, options, callback) => {
+ if (typeof path === 'function') {
+ callback = path
+ path = undefined
+ }
+
+ if (typeof options === 'function') {
+ callback = options
+
+ // Allow options in path position
+ if (typeof path !== 'string') {
+ options = path
+ path = undefined
+ } else {
+ options = {}
+ }
+ }
+
+ options = options || {}
+
+ if (typeof cid === 'string') {
+ const split = cid.split('/')
+
+ try {
+ cid = new CID(split[0])
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ split.shift()
+
+ if (split.length > 0) {
+ path = split.join('/')
+ } else {
+ path = path || '/'
+ }
+ } else if (Buffer.isBuffer(cid)) {
+ try {
+ cid = new CID(cid)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+ }
+
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ if (path == null || path === '/') {
+ self._ipld.get(cid).then(
+ (value) => {
+ callback(null, {
+ value,
+ remainderPath: ''
+ })
+ },
+ (error) => callback(error)
+ )
+ } else {
+ const result = self._ipld.resolve(cid, path)
+ const promisedValue = options.localResolve ? result.first() : result.last()
+ promisedValue.then(
+ (value) => callback(null, value),
+ (error) => callback(error)
+ )
+ }
+ }),
+
+ tree: promisify((cid, path, options, callback) => {
+ if (typeof path === 'object') {
+ callback = options
+ options = path
+ path = undefined
+ }
+
+ if (typeof path === 'function') {
+ callback = path
+ path = undefined
+ }
+
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ if (typeof cid === 'string') {
+ const split = cid.split('/')
+
+ try {
+ cid = new CID(split[0])
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ split.shift()
+
+ if (split.length > 0) {
+ path = split.join('/')
+ } else {
+ path = undefined
+ }
+ }
+
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ pull(
+ iterToPull(self._ipld.tree(cid, path, options)),
+ pull.collect(callback)
+ )
+ })
+ }
+}
+
+}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")})
+},{"../../../../is-buffer/index.js":608,"async-iterator-to-pull-stream":34,"async/setImmediate":96,"cids":185,"err-code":268,"multicodec":1151,"promisify-es6":1263,"pull-stream":1311}],482:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const promisify = require('promisify-es6')
+const every = require('async/every')
+const PeerId = require('peer-id')
+const PeerInfo = require('peer-info')
+const CID = require('cids')
+const each = require('async/each')
+const nextTick = require('async/nextTick')
+
+const errcode = require('err-code')
+
+const debug = require('debug')
+const log = debug('ipfs:dht')
+log.error = debug('ipfs:dht:error')
+
+module.exports = (self) => {
+ return {
+ /**
+ * Given a key, query the DHT for its best value.
+ *
+ * @param {Buffer} key
+ * @param {Object} options - get options
+ * @param {number} options.timeout - optional timeout
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ get: promisify((key, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ if (!Buffer.isBuffer(key)) {
+ try {
+ key = (new CID(key)).buffer
+ } catch (err) {
+ log.error(err)
+
+ return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID')))
+ }
+ }
+
+ self.libp2p.dht.get(key, options, callback)
+ }),
+
+ /**
+ * Write a key/value pair to the DHT.
+ *
+ * Given a key of the form /foo/bar and a value of any
+ * form, this will write that value to the DHT with
+ * that key.
+ *
+ * @param {Buffer} key
+ * @param {Buffer} value
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ put: promisify((key, value, callback) => {
+ if (!Buffer.isBuffer(key)) {
+ try {
+ key = (new CID(key)).buffer
+ } catch (err) {
+ log.error(err)
+
+ return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID')))
+ }
+ }
+
+ self.libp2p.dht.put(key, value, callback)
+ }),
+
+ /**
+ * Find peers in the DHT that can provide a specific value, given a key.
+ *
+ * @param {CID} key - They key to find providers for.
+ * @param {Object} options - findProviders options
+ * @param {number} options.timeout - how long the query should maximally run, in milliseconds (default: 60000)
+ * @param {number} options.maxNumProviders - maximum number of providers to find
+ * @param {function(Error, Array)} [callback]
+ * @returns {Promise|void}
+ */
+ findProvs: promisify((key, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ if (typeof key === 'string') {
+ try {
+ key = new CID(key)
+ } catch (err) {
+ log.error(err)
+
+ return nextTick(() => callback(errcode(err, 'ERR_INVALID_CID')))
+ }
+ }
+
+ self.libp2p.contentRouting.findProviders(key, options, callback)
+ }),
+
+ /**
+ * Query the DHT for all multiaddresses associated with a `PeerId`.
+ *
+ * @param {PeerId} peer - The id of the peer to search for.
+ * @param {function(Error, PeerInfo)} [callback]
+ * @returns {Promise|void}
+ */
+ findPeer: promisify((peer, callback) => {
+ if (typeof peer === 'string') {
+ peer = PeerId.createFromB58String(peer)
+ }
+
+ self.libp2p.peerRouting.findPeer(peer, callback)
+ }),
+
+ /**
+ * Announce to the network that we are providing given values.
+ *
+ * @param {CID|Array} keys - The keys that should be announced.
+ * @param {Object} options - provide options
+ * @param {bool} [options.recursive=false] - Provide not only the given object but also all objects linked from it.
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ provide: promisify((keys, options, callback) => {
+ if (!Array.isArray(keys)) {
+ keys = [keys]
+ }
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ // ensure blocks are actually local
+ every(keys, (key, cb) => {
+ self._repo.blocks.has(key, cb)
+ }, (err, has) => {
+ if (err) {
+ return callback(err)
+ }
+
+ if (!has) {
+ const errMsg = 'block(s) not found locally, cannot provide'
+
+ log.error(errMsg)
+ return callback(errcode(errMsg, 'ERR_BLOCK_NOT_FOUND'))
+ }
+
+ if (options.recursive) {
+ // TODO: Implement recursive providing
+ return callback(errcode('not implemented yet', 'ERR_NOT_IMPLEMENTED_YET'))
+ } else {
+ each(keys, (cid, cb) => {
+ self.libp2p.contentRouting.provide(cid, cb)
+ }, callback)
+ }
+ })
+ }),
+
+ /**
+ * Find the closest peers to a given `PeerId`, by querying the DHT.
+ *
+ * @param {PeerId} peer - The `PeerId` to run the query agains.
+ * @param {function(Error, Array)} [callback]
+ * @returns {Promise>|void}
+ */
+ query: promisify((peerId, callback) => {
+ if (typeof peerId === 'string') {
+ try {
+ peerId = PeerId.createFromB58String(peerId)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+ }
+
+ // TODO expose this method in peerRouting
+ self.libp2p._dht.getClosestPeers(peerId.toBytes(), (err, peerIds) => {
+ if (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ callback(null, peerIds.map((id) => new PeerInfo(id)))
+ })
+ })
+ }
+}
+
+}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")})
+},{"../../../../is-buffer/index.js":608,"async/each":56,"async/every":62,"async/nextTick":90,"cids":185,"debug":456,"err-code":268,"peer-id":1253,"peer-info":1254,"promisify-es6":1263}],483:[function(require,module,exports){
+'use strict'
+
+// dns-nodejs gets replaced by dns-browser when webpacked/browserified
+const dns = require('../runtime/dns-nodejs')
+const promisify = require('promisify-es6')
+
+function fqdnFixups (domain) {
+ // Allow resolution of .eth names via .eth.link
+ // More context at the go-ipfs counterpart: https://github.com/ipfs/go-ipfs/pull/6448
+ if (domain.endsWith('.eth')) {
+ domain = domain.replace(/.eth$/, '.eth.link')
+ }
+ return domain
+}
+
+module.exports = () => {
+ return promisify((domain, opts, callback) => {
+ if (typeof domain !== 'string') {
+ return callback(new Error('Invalid arguments, domain must be a string'))
+ }
+
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ opts = opts || {}
+ domain = fqdnFixups(domain)
+
+ dns(domain, opts, callback)
+ })
+}
+
+},{"../runtime/dns-nodejs":552,"promisify-es6":1263}],484:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const mfs = require('ipfs-mfs/core')
+const isPullStream = require('is-pull-stream')
+const toPullStream = require('async-iterator-to-pull-stream')
+const toReadableStream = require('async-iterator-to-stream')
+const pullStreamToAsyncIterator = require('pull-stream-to-async-iterator')
+const all = require('async-iterator-all')
+const nodeify = require('promise-nodeify')
+const PassThrough = require('stream').PassThrough
+const pull = require('pull-stream/pull')
+const map = require('pull-stream/throughs/map')
+const isIpfs = require('is-ipfs')
+const { cidToString } = require('../../utils/cid')
+
+/**
+ * @typedef { import("readable-stream").Readable } ReadableStream
+ * @typedef { import("pull-stream") } PullStream
+ */
+
+const mapLsFile = (options = {}) => {
+ const long = options.long || options.l
+
+ return (file) => {
+ return {
+ hash: long ? cidToString(file.cid, { base: options.cidBase }) : '',
+ name: file.name,
+ type: long ? file.type : 0,
+ size: long ? file.size || 0 : 0
+ }
+ }
+}
+
+module.exports = (/** @type { import("../index") } */ ipfs) => {
+ const methodsOriginal = mfs({
+ ipld: ipfs._ipld,
+ blocks: ipfs._blockService,
+ datastore: ipfs._repo.root,
+ repoOwner: ipfs._options.repoOwner
+ })
+
+ const withPreload = fn => (...args) => {
+ const paths = args.filter(arg => isIpfs.ipfsPath(arg) || isIpfs.cid(arg))
+
+ if (paths.length) {
+ const options = args[args.length - 1]
+ if (options.preload !== false) {
+ paths.forEach(path => ipfs._preload(path))
+ }
+ }
+
+ return fn(...args)
+ }
+
+ const methods = {
+ ...methodsOriginal,
+ cp: withPreload(methodsOriginal.cp),
+ ls: withPreload(methodsOriginal.ls),
+ mv: withPreload(methodsOriginal.mv),
+ read: withPreload(methodsOriginal.read),
+ stat: withPreload(methodsOriginal.stat)
+ }
+
+ return {
+ /**
+ * Copy files
+ *
+ * @param {String | Array} from - The path(s) of the source to copy.
+ * @param {String} to - The path of the destination to copy to.
+ * @param {Object} [opts] - Options for copy.
+ * @param {boolean} [opts.parents=false] - Whether or not to make the parent directories if they don't exist. (default: false)
+ * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb)
+ * @param {String} [opts.hashAlg=sha2-256] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values}
+ * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true).
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ cp: (from, to, opts, cb) => {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(methods.cp(from, to, opts), cb)
+ },
+
+ /**
+ * Make a directory
+ *
+ * @param {String} path - The path to the directory to make.
+ * @param {Object} [opts] - Options for mkdir.
+ * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false)
+ * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb).
+ * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values}
+ * @param {boolean} [opts.flush=true] - Whether or not to immediately flush MFS changes to disk (default: true).
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ mkdir: (path, opts, cb) => {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(methods.mkdir(path, opts), cb)
+ },
+
+ /**
+ * @typedef {Object} StatOutput
+ * @prop {String} hash - Output hash.
+ * @prop {number} size - File size in bytes.
+ * @prop {number} cumulativeSize - Integer with the size of the DAGNodes making up the file in Bytes.
+ * @prop {string} type - Output type either 'directory' or 'file'.
+ * @prop {number} blocks - If type is directory, this is the number of files in the directory. If it is file it is the number of blocks that make up the file.
+ * @prop {boolean} withLocality - Indicate if locality information is present.
+ * @prop {boolean} local - Indicate if the queried dag is fully present locally.
+ * @prop {number} sizeLocal - Integer indicating the cumulative size of the data present locally.
+ */
+
+ /**
+ * Get file or directory status.
+ *
+ * @param {String} path - Path to the file or directory to stat.
+ * @param {Object} [opts] - Options for stat.
+ * @param {boolean} [opts.hash=false] - Return only the hash. (default: false)
+ * @param {boolean} [opts.size=false] - Return only the size. (default: false)
+ * @param {boolean} [opts.withLocal=false] - Compute the amount of the dag that is local, and if possible the total size. (default: false)
+ * @param {String} [opts.cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc)
+ * @param {function(Error, StatOutput): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ stat: (path, opts, cb) => {
+ const stat = async (path, opts = {}) => {
+ const stats = await methods.stat(path, opts)
+
+ stats.hash = stats.cid.toBaseEncodedString(opts && opts.cidBase)
+ delete stats.cid
+
+ return stats
+ }
+
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+
+ return nodeify(stat(path, opts), cb)
+ },
+
+ /**
+ * Remove a file or directory.
+ *
+ * @param {String | Array} paths - One or more paths to remove.
+ * @param {Object} [opts] - Options for remove.
+ * @param {boolean} [opts.recursive=false] - Whether or not to remove directories recursively. (default: false)
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ rm: (paths, opts, cb) => {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(methods.rm(paths, opts), cb)
+ },
+
+ /**
+ * @typedef {Object} ReadOptions
+ * @prop {number} [opts.offset=0] - Integer with the byte offset to begin reading from (default: 0).
+ * @prop {number} [opts.length] - Integer with the maximum number of bytes to read (default: Read to the end of stream).
+ */
+
+ /**
+ * Read a file into a Buffer.
+ *
+ * @param {string} path - Path of the file to read and must point to a file (and not a directory).
+ * @param {ReadOptions} [opts] - Object for read.
+ * @param {function(Error, Buffer): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ read: (path, opts, cb) => {
+ const read = async (path, opts = {}) => {
+ return Buffer.concat(await all(methods.read(path, opts)))
+ }
+
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(read(path, opts), cb)
+ },
+
+ /**
+ * Read a file into a ReadableStream.
+ *
+ * @param {string} path - Path of the file to read and must point to a file (and not a directory).
+ * @param {ReadOptions} [opts] - Object for read.
+ * @returns {ReadableStream} Returns a ReadableStream with the contents of path.
+ */
+ readReadableStream: (path, opts = {}) => toReadableStream(methods.read(path, opts)),
+
+ /**
+ * Read a file into a PullStrean.
+ *
+ * @param {string} path - Path of the file to read and must point to a file (and not a directory).
+ * @param {ReadOptions} [opts] - Object for read.
+ * @returns {PullStream} Returns a PullStream with the contents of path.
+ */
+ readPullStream: (path, opts = {}) => toPullStream.source(methods.read(path, opts)),
+
+ /**
+ * Write to a file.
+ *
+ * @param {string} path - Path of the file to write.
+ * @param {Buffer | PullStream | ReadableStream | Blob | string} content - Content to write.
+ * @param {Object} opts - Options for write.
+ * @param {number} [opts.offset=0] - Integer with the byte offset to begin writing at. (default: 0)
+ * @param {boolean} [opts.create=false] - Indicate to create the file if it doesn't exist. (default: false)
+ * @param {boolean} [opts.truncate=false] - Indicate if the file should be truncated after writing all the bytes from content. (default: false)
+ * @param {boolena} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false)
+ * @param {number} [opts.length] - Maximum number of bytes to read. (default: Read all bytes from content)
+ * @param {boolean} [opts.rawLeaves=false] - If true, DAG leaves will contain raw file data and not be wrapped in a protobuf. (default: false)
+ * @param {number} [opts.cidVersion=0] - The CID version to use when storing the data (storage keys are based on the CID, including its version). (default: 0)
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ write: (path, content, opts, cb) => {
+ const write = async (path, content, opts = {}) => {
+ if (isPullStream.isSource(content)) {
+ content = pullStreamToAsyncIterator(content)
+ }
+
+ await methods.write(path, content, opts)
+ }
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(write(path, content, opts), cb)
+ },
+
+ /**
+ * Move files.
+ *
+ * @param {string | Array} from - Path(s) of the source to move.
+ * @param {string} to - Path of the destination to move to.
+ * @param {Object} opts - Options for mv.
+ * @param {boolean} [opts.parents=false] - Value to decide whether or not to make the parent directories if they don't exist. (default: false)
+ * @param {String} [opts.format=dag-pb] - Format of nodes to write any newly created directories as. (default: dag-pb).
+ * @param {String} [opts.hashAlg] - Algorithm to use when creating CIDs for newly created directories. (default: sha2-256) {@link https://github.com/multiformats/js-multihash/blob/master/src/constants.js#L5-L343 The list of all possible values}
+ * @param {boolean} [opts.flush=true] - Value to decide whether or not to immediately flush MFS changes to disk. (default: true)
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ * @description
+ * If from has multiple values then to must be a directory.
+ *
+ * If from has a single value and to exists and is a directory, from will be moved into to.
+ *
+ * If from has a single value and to exists and is a file, from must be a file and the contents of to will be replaced with the contents of from otherwise an error will be returned.
+ *
+ * If from is an IPFS path, and an MFS path exists with the same name, the IPFS path will be chosen.
+ *
+ * All values of from will be removed after the operation is complete unless they are an IPFS path.
+ */
+ mv: (from, to, opts, cb) => {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(methods.mv(from, to, opts), cb)
+ },
+
+ /**
+ * Flush a given path's data to the disk.
+ *
+ * @param {string | Array} [paths] - String paths to flush. (default: /)
+ * @param {function(Error): void} [cb] - Callback function.
+ * @returns {Promise | void} When callback is provided nothing is returned.
+ */
+ flush: (paths, cb) => {
+ if (typeof paths === 'function') {
+ cb = paths
+ paths = undefined
+ }
+ return nodeify(methods.flush(paths), cb)
+ },
+
+ /**
+ * @typedef {Object} ListOutputFile
+ * @prop {string} name - Which is the file's name.
+ * @prop {string} type - Which is the object's type (directory or file).
+ * @prop {number} size - The size of the file in bytes.
+ * @prop {string} hash - The hash of the file.
+ */
+
+ /**
+ * @typedef {Object} ListOptions
+ * @prop {boolean} [long=false] - Value to decide whether or not to populate type, size and hash. (default: false)
+ * @prop {string} [cidBase=base58btc] - Which number base to use to format hashes - e.g. base32, base64 etc. (default: base58btc)
+ * @prop {boolean} [sort=false] - If true entries will be sorted by filename. (default: false)
+ */
+
+ /**
+ * List directories in the local mutable namespace.
+ *
+ * @param {string} [path="/"] - String to show listing for. (default: /)
+ * @param {ListOptions} [opts] - Options for list.
+ * @param {function(Error, Array): void} [cb] - Callback function.
+ * @returns {Promise> | void} When callback is provided nothing is returned.
+ */
+ ls: (path, opts, cb) => {
+ const ls = async (path, opts = {}) => {
+ const files = await all(methods.ls(path, opts))
+
+ return files.map(mapLsFile(opts))
+ }
+
+ if (typeof path === 'function') {
+ cb = path
+ path = '/'
+ opts = {}
+ }
+
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(ls(path, opts), cb)
+ },
+
+ /**
+ * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as Readable Streams.
+ *
+ * @param {string} [path="/"] - String to show listing for. (default: /)
+ * @param {ListOptions} [opts] - Options for list.
+ * @returns {ReadableStream} It returns a Readable Stream in Object mode that will yield {@link ListOutputFile}
+ */
+ lsReadableStream: (path, opts = {}) => {
+ const stream = toReadableStream.obj(methods.ls(path, opts))
+ const through = new PassThrough({
+ objectMode: true
+ })
+ stream.on('data', (file) => {
+ through.write(mapLsFile(opts)(file))
+ })
+ stream.on('error', (err) => {
+ through.destroy(err)
+ })
+ stream.on('end', (file, enc, cb) => {
+ if (file) {
+ file = mapLsFile(opts)(file)
+ }
+
+ through.end(file, enc, cb)
+ })
+
+ return through
+ },
+
+ /**
+ * Lists a directory from the local mutable namespace that is addressed by a valid IPFS Path. The list will be yielded as PullStreams.
+ *
+ * @param {string} [path="/"] - String to show listing for. (default: /)
+ * @param {ListOptions} [opts] - Options for list.
+ * @returns {PullStream} It returns a PullStream that will yield {@link ListOutputFile}
+ */
+ lsPullStream: (path, opts = {}) => {
+ return pull(
+ toPullStream.source(methods.ls(path, opts)),
+ map(mapLsFile(opts))
+ )
+ }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"../../utils/cid":561,"async-iterator-all":30,"async-iterator-to-pull-stream":34,"async-iterator-to-stream":35,"buffer":181,"ipfs-mfs/core":354,"is-ipfs":614,"is-pull-stream":617,"promise-nodeify":1259,"pull-stream-to-async-iterator":1309,"pull-stream/pull":1312,"pull-stream/throughs/map":1334,"stream":472}],485:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const importer = require('ipfs-unixfs-importer')
+const normaliseAddInput = require('ipfs-utils/src/files/normalise-input')
+const { parseChunkerString } = require('./utils')
+const pipe = require('it-pipe')
+const log = require('debug')('ipfs:add')
+log.error = require('debug')('ipfs:add:error')
+
+function noop () {}
+
+module.exports = function (self) {
+ // Internal add func that gets used by all add funcs
+ return async function * addAsyncIterator (source, options) {
+ options = options || {}
+
+ const chunkerOptions = parseChunkerString(options.chunker)
+
+ const opts = Object.assign({}, {
+ shardSplitThreshold: self._options.EXPERIMENTAL.sharding
+ ? 1000
+ : Infinity
+ }, options, {
+ chunker: chunkerOptions.chunker,
+ chunkerOptions: chunkerOptions.chunkerOptions
+ })
+
+ // CID v0 is for multihashes encoded with sha2-256
+ if (opts.hashAlg && opts.cidVersion !== 1) {
+ opts.cidVersion = 1
+ }
+
+ let total = 0
+
+ const prog = opts.progress || noop
+ const progress = (bytes) => {
+ total += bytes
+ prog(total)
+ }
+
+ opts.progress = progress
+
+ const iterator = pipe(
+ normaliseAddInput(source),
+ doImport(self, opts),
+ transformFile(self, opts),
+ preloadFile(self, opts),
+ pinFile(self, opts)
+ )
+
+ const releaseLock = await self._gcLock.readLock()
+
+ try {
+ yield * iterator
+ } finally {
+ releaseLock()
+ }
+ }
+}
+
+function doImport (ipfs, opts) {
+ return async function * (source) { // eslint-disable-line require-await
+ yield * importer(source, ipfs._ipld, opts)
+ }
+}
+
+function transformFile (ipfs, opts) {
+ return async function * (source) {
+ for await (const file of source) {
+ let cid = file.cid
+ const hash = cid.toBaseEncodedString()
+ let path = file.path ? file.path : hash
+
+ if (opts.wrapWithDirectory && !file.path) {
+ path = ''
+ }
+
+ if (opts.onlyHash) {
+ yield {
+ path,
+ hash,
+ size: file.unixfs.fileSize()
+ }
+
+ return
+ }
+
+ const node = await ipfs.object.get(file.cid, Object.assign({}, opts, { preload: false }))
+
+ if (opts.cidVersion === 1) {
+ cid = cid.toV1()
+ }
+
+ let size = node.size
+
+ if (Buffer.isBuffer(node)) {
+ size = node.length
+ }
+
+ yield {
+ path,
+ hash,
+ size
+ }
+ }
+ }
+}
+
+function preloadFile (ipfs, opts) {
+ return async function * (source) {
+ for await (const file of source) {
+ const isRootFile = !file.path || opts.wrapWithDirectory
+ ? file.path === ''
+ : !file.path.includes('/')
+
+ const shouldPreload = isRootFile && !opts.onlyHash && opts.preload !== false
+
+ if (shouldPreload) {
+ ipfs._preload(file.hash)
+ }
+
+ yield file
+ }
+ }
+}
+
+function pinFile (ipfs, opts) {
+ return async function * (source) {
+ for await (const file of source) {
+ // Pin a file if it is the root dir of a recursive add or the single file
+ // of a direct add.
+ const pin = 'pin' in opts ? opts.pin : true
+ const isRootDir = !file.path.includes('/')
+ const shouldPin = pin && isRootDir && !opts.onlyHash && !opts.hashAlg
+
+ if (shouldPin) {
+ // Note: addAsyncIterator() has already taken a GC lock, so tell
+ // pin.add() not to take a (second) GC lock
+ await ipfs.pin.add(file.hash, {
+ preload: false,
+ lock: false
+ })
+ }
+
+ yield file
+ }
+ }
+}
+
+}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
+},{"../../../../../is-buffer/index.js":608,"./utils":508,"debug":456,"ipfs-unixfs-importer":431,"ipfs-utils/src/files/normalise-input":454,"it-pipe":644}],486:[function(require,module,exports){
+'use strict'
+
+module.exports = (self) => require('../../runtime/add-from-fs-nodejs')(self)
+
+},{"../../runtime/add-from-fs-nodejs":550}],487:[function(require,module,exports){
+'use strict'
+
+module.exports = self => require('./add')(self)
+
+},{"./add":491}],488:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const { URL } = require('iso-url')
+const fetch = require('../../runtime/fetch-nodejs')
+
+module.exports = (self) => {
+ return async (url, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ let files
+
+ try {
+ const parsedUrl = new URL(url)
+ const res = await fetch(url)
+
+ if (!res.ok) {
+ throw new Error('unexpected status code: ' + res.status)
+ }
+
+ // TODO: use res.body when supported
+ const content = Buffer.from(await res.arrayBuffer())
+ const path = decodeURIComponent(parsedUrl.pathname.split('/').pop())
+
+ files = await self.add({ content, path }, options)
+ } catch (err) {
+ if (callback) {
+ return callback(err)
+ }
+ throw err
+ }
+
+ if (callback) {
+ callback(null, files)
+ }
+
+ return files
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"../../runtime/fetch-nodejs":553,"buffer":181,"iso-url":641}],489:[function(require,module,exports){
+'use strict'
+
+const toPullStream = require('async-iterator-to-pull-stream')
+
+module.exports = function (self) {
+ return function addPullStream (options) {
+ return toPullStream.transform((source) => {
+ return self._addAsyncIterator(source, options)
+ })
+ }
+}
+
+},{"async-iterator-to-pull-stream":34}],490:[function(require,module,exports){
+'use strict'
+
+const toStream = require('it-to-stream')
+
+module.exports = function (self) {
+ return function addReadableStream (options) {
+ return toStream.transform(source => {
+ return self._addAsyncIterator(source, options)
+ }, {
+ objectMode: true
+ })
+ }
+}
+
+},{"it-to-stream":664}],491:[function(require,module,exports){
+'use strict'
+
+const all = require('async-iterator-all')
+
+module.exports = function (self) {
+ // can't use callbackify because if `data` is a pull stream
+ // it thinks we are passing a callback. This is why we can't have nice things.
+ return (data, options, callback) => {
+ if (!callback && typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ const result = all(self._addAsyncIterator(data, options))
+
+ if (!callback) {
+ return result
+ }
+
+ result.then((result) => callback(null, result), callback)
+ }
+}
+
+},{"async-iterator-all":30}],492:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const deferred = require('pull-defer')
+const toPullStream = require('async-iterator-to-pull-stream')
+const { normalizePath } = require('./utils')
+
+module.exports = function (self) {
+ return function catPullStream (ipfsPath, options) {
+ if (typeof ipfsPath === 'function') {
+ throw new Error('You must supply an ipfsPath')
+ }
+
+ options = options || {}
+
+ ipfsPath = normalizePath(ipfsPath)
+ const pathComponents = ipfsPath.split('/')
+
+ if (options.preload !== false) {
+ self._preload(pathComponents[0])
+ }
+
+ const d = deferred.source()
+
+ exporter(ipfsPath, self._ipld, options)
+ .then(file => {
+ // File may not have unixfs prop if small & imported with rawLeaves true
+ if (file.unixfs && file.unixfs.type.includes('dir')) {
+ return d.abort(new Error('this dag node is a directory'))
+ }
+
+ if (!file.content) {
+ return d.abort(new Error('this dag node has no content'))
+ }
+
+ d.resolve(toPullStream.source(file.content(options)))
+ }, err => {
+ d.abort(err)
+ })
+
+ return d
+ }
+}
+
+},{"./utils":508,"async-iterator-to-pull-stream":34,"ipfs-unixfs-exporter":400,"pull-defer":1285}],493:[function(require,module,exports){
+'use strict'
+
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => toStream.source(self.catPullStream(ipfsPath, options))
+}
+
+},{"pull-stream-to-stream":1310}],494:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream')
+
+module.exports = function (self) {
+ return promisify((ipfsPath, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ pull(
+ self.catPullStream(ipfsPath, options),
+ pull.collect((err, buffers) => {
+ if (err) { return callback(err) }
+ callback(null, Buffer.concat(buffers))
+ })
+ )
+ })
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"promisify-es6":1263,"pull-stream":1311}],495:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const toPullStream = require('async-iterator-to-pull-stream')
+const errCode = require('err-code')
+const pull = require('pull-stream/pull')
+const pullError = require('pull-stream/sources/error')
+const map = require('pull-stream/throughs/map')
+const { normalizePath, mapFile } = require('./utils')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => {
+ options = options || {}
+
+ if (options.preload !== false) {
+ let pathComponents
+
+ try {
+ pathComponents = normalizePath(ipfsPath).split('/')
+ } catch (err) {
+ return pullError(errCode(err, 'ERR_INVALID_PATH'))
+ }
+
+ self._preload(pathComponents[0])
+ }
+
+ return pull(
+ toPullStream.source(exporter.recursive(ipfsPath, self._ipld, options)),
+ map(mapFile({
+ ...options,
+ includeContent: true
+ }))
+ )
+ }
+}
+
+},{"./utils":508,"async-iterator-to-pull-stream":34,"err-code":268,"ipfs-unixfs-exporter":400,"pull-stream/pull":1312,"pull-stream/sources/error":1323,"pull-stream/throughs/map":1334}],496:[function(require,module,exports){
+'use strict'
+
+const pull = require('pull-stream')
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => {
+ options = options || {}
+
+ return toStream.source(
+ pull(
+ self.getPullStream(ipfsPath, options),
+ pull.map((file) => {
+ if (file.content) {
+ file.content = toStream.source(file.content)
+ file.content.pause()
+ }
+
+ return file
+ })
+ )
+ )
+ }
+}
+
+},{"pull-stream":1311,"pull-stream-to-stream":1310}],497:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream')
+
+module.exports = function (self) {
+ return promisify((ipfsPath, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ pull(
+ self.getPullStream(ipfsPath, options),
+ pull.asyncMap((file, cb) => {
+ if (file.content) {
+ pull(
+ file.content,
+ pull.collect((err, buffers) => {
+ if (err) { return cb(err) }
+ file.content = Buffer.concat(buffers)
+ cb(null, file)
+ })
+ )
+ } else {
+ cb(null, file)
+ }
+ }),
+ pull.collect(callback)
+ )
+ })
+}
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"promisify-es6":1263,"pull-stream":1311}],498:[function(require,module,exports){
+'use strict'
+
+module.exports = (self) => {
+ const filesRegular = {
+ add: require('./add')(self),
+ addFromFs: require('./add-from-fs')(self),
+ addFromStream: require('./add-from-stream')(self),
+ addFromURL: require('./add-from-url')(self),
+ addPullStream: require('./add-pull-stream')(self),
+ addReadableStream: require('./add-readable-stream')(self),
+ _addAsyncIterator: require('./add-async-iterator')(self),
+ cat: require('./cat')(self),
+ catPullStream: require('./cat-pull-stream')(self),
+ catReadableStream: require('./cat-readable-stream')(self),
+ get: require('./get')(self),
+ getPullStream: require('./get-pull-stream')(self),
+ getReadableStream: require('./get-readable-stream')(self),
+ ls: require('./ls')(self),
+ lsPullStream: require('./ls-pull-stream')(self),
+ lsReadableStream: require('./ls-readable-stream')(self),
+ refs: require('./refs')(self),
+ refsReadableStream: require('./refs-readable-stream')(self),
+ refsPullStream: require('./refs-pull-stream')(self)
+ }
+ filesRegular.refs.local = require('./refs-local')(self)
+ filesRegular.refs.localReadableStream = require('./refs-local-readable-stream')(self)
+ filesRegular.refs.localPullStream = require('./refs-local-pull-stream')(self)
+ return filesRegular
+}
+
+},{"./add":491,"./add-async-iterator":485,"./add-from-fs":486,"./add-from-stream":487,"./add-from-url":488,"./add-pull-stream":489,"./add-readable-stream":490,"./cat":494,"./cat-pull-stream":492,"./cat-readable-stream":493,"./get":497,"./get-pull-stream":495,"./get-readable-stream":496,"./ls":501,"./ls-pull-stream":499,"./ls-readable-stream":500,"./refs":507,"./refs-local":504,"./refs-local-pull-stream":502,"./refs-local-readable-stream":503,"./refs-pull-stream":505,"./refs-readable-stream":506}],499:[function(require,module,exports){
+'use strict'
+
+const exporter = require('ipfs-unixfs-exporter')
+const deferred = require('pull-defer')
+const pull = require('pull-stream/pull')
+const once = require('pull-stream/sources/once')
+const map = require('pull-stream/throughs/map')
+const filter = require('pull-stream/throughs/filter')
+const errCode = require('err-code')
+const toPullStream = require('async-iterator-to-pull-stream')
+const { normalizePath, mapFile } = require('./utils')
+
+module.exports = function (self) {
+ return function (ipfsPath, options) {
+ options = options || {}
+
+ const path = normalizePath(ipfsPath)
+ const recursive = options.recursive
+ const pathComponents = path.split('/')
+
+ if (options.preload !== false) {
+ self._preload(pathComponents[0])
+ }
+
+ const d = deferred.source()
+
+ exporter(ipfsPath, self._ipld, options)
+ .then(file => {
+ if (!file.unixfs) {
+ return d.abort(errCode(new Error('dag node was not a UnixFS node'), 'ENOTUNIXFS'))
+ }
+
+ if (file.unixfs.type === 'file') {
+ return d.resolve(once(mapFile(options)(file)))
+ }
+
+ if (file.unixfs.type.includes('dir')) {
+ if (recursive) {
+ return d.resolve(pull(
+ toPullStream.source(exporter.recursive(file.cid, self._ipld, options)),
+ filter(child => file.cid.toBaseEncodedString() !== child.cid.toBaseEncodedString()),
+ map(mapFile(options))
+ ))
+ }
+
+ return d.resolve(pull(
+ toPullStream.source(file.content()),
+ map(mapFile(options)),
+ map((file) => {
+ file.depth--
+
+ return file
+ })
+ ))
+ }
+
+ d.abort(errCode(new Error(`Unknown UnixFS type ${file.unixfs.type}`), 'EUNKNOWNUNIXFSTYPE'))
+ }, err => {
+ d.abort(err)
+ })
+
+ return d
+ }
+}
+
+},{"./utils":508,"async-iterator-to-pull-stream":34,"err-code":268,"ipfs-unixfs-exporter":400,"pull-defer":1285,"pull-stream/pull":1312,"pull-stream/sources/once":1327,"pull-stream/throughs/filter":1331,"pull-stream/throughs/map":1334}],500:[function(require,module,exports){
+'use strict'
+
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => {
+ return toStream.source(self.lsPullStream(ipfsPath, options))
+ }
+}
+
+},{"pull-stream-to-stream":1310}],501:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream')
+
+module.exports = function (self) {
+ return promisify((ipfsPath, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ pull(
+ self.lsPullStream(ipfsPath, options),
+ pull.collect((err, values) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, values)
+ })
+ )
+ })
+}
+
+},{"promisify-es6":1263,"pull-stream":1311}],502:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+const base32 = require('base32.js')
+const pull = require('pull-stream')
+const pullDefer = require('pull-defer')
+
+module.exports = function (self) {
+ return () => {
+ const deferred = pullDefer.source()
+
+ self._repo.blocks.query({ keysOnly: true }, (err, blocks) => {
+ if (err) {
+ return deferred.resolve(pull.error(err))
+ }
+
+ const refs = blocks.map(b => dsKeyToRef(b.key))
+ deferred.resolve(pull.values(refs))
+ })
+
+ return deferred
+ }
+}
+
+function dsKeyToRef (key) {
+ try {
+ // Block key is of the form /
+ const decoder = new base32.Decoder()
+ const buff = Buffer.from(decoder.write(key.toString().slice(1)).finalize())
+ return { ref: new CID(buff).toString() }
+ } catch (err) {
+ return { err: `Could not convert block with key '${key}' to CID: ${err.message}` }
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"base32.js":107,"buffer":181,"cids":185,"pull-defer":1285,"pull-stream":1311}],503:[function(require,module,exports){
+'use strict'
+
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => {
+ return toStream.source(self.refs.localPullStream())
+ }
+}
+
+},{"pull-stream-to-stream":1310}],504:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream')
+
+module.exports = function (self) {
+ return promisify((callback) => {
+ pull(
+ self.refs.localPullStream(),
+ pull.collect((err, values) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, values)
+ })
+ )
+ })
+}
+
+},{"promisify-es6":1263,"pull-stream":1311}],505:[function(require,module,exports){
+'use strict'
+
+const pull = require('pull-stream')
+const pullDefer = require('pull-defer')
+const pullTraverse = require('pull-traverse')
+const pullCat = require('pull-cat')
+const isIpfs = require('is-ipfs')
+const CID = require('cids')
+const { DAGNode } = require('ipld-dag-pb')
+const { normalizePath } = require('./utils')
+const { Format } = require('./refs')
+
+module.exports = function (self) {
+ return function (ipfsPath, options = {}) {
+ if (options.maxDepth === 0) {
+ return pull.empty()
+ }
+ if (options.edges && options.format && options.format !== Format.default) {
+ return pull.error(new Error('Cannot set edges to true and also specify format'))
+ }
+
+ options.format = options.edges ? Format.edges : options.format || Format.default
+
+ if (typeof options.maxDepth !== 'number') {
+ options.maxDepth = options.recursive ? Infinity : 1
+ }
+
+ let paths
+ try {
+ const rawPaths = Array.isArray(ipfsPath) ? ipfsPath : [ipfsPath]
+ paths = rawPaths.map(p => getFullPath(self, p, options))
+ } catch (err) {
+ return pull.error(err)
+ }
+
+ return pullCat(paths.map(p => refsStream(self, p, options)))
+ }
+}
+
+function getFullPath (ipfs, ipfsPath, options) {
+ // normalizePath() strips /ipfs/ off the front of the path so the CID will
+ // be at the front of the path
+ const path = normalizePath(ipfsPath)
+ const pathComponents = path.split('/')
+ const cid = pathComponents[0]
+ if (!isIpfs.cid(cid)) {
+ throw new Error(`Error resolving path '${path}': '${cid}' is not a valid CID`)
+ }
+
+ if (options.preload !== false) {
+ ipfs._preload(cid)
+ }
+
+ return '/ipfs/' + path
+}
+
+// Get a stream of refs at the given path
+function refsStream (ipfs, path, options) {
+ const deferred = pullDefer.source()
+
+ // Resolve to the target CID of the path
+ ipfs.resolve(path, (err, resPath) => {
+ if (err) {
+ return deferred.resolve(pull.error(err))
+ }
+
+ // path is /ipfs/
+ const parts = resPath.split('/')
+ const cid = parts[2]
+ deferred.resolve(pull(
+ // Traverse the DAG, converting it into a stream
+ objectStream(ipfs, cid, options.maxDepth, options.unique),
+ // Root object will not have a parent
+ pull.filter(obj => Boolean(obj.parent)),
+ // Filter out duplicates (isDuplicate flag is only set if options.unique is set)
+ pull.filter(obj => !obj.isDuplicate),
+ // Format the links
+ pull.map(obj => formatLink(obj.parent.cid, obj.node.cid, obj.node.name, options.format)),
+ // Clients expect refs to be in the format { ref: [ }
+ pull.map(ref => ({ ref }))
+ ))
+ })
+
+ return deferred
+}
+
+// Get formatted link
+function formatLink (srcCid, dstCid, linkName, format) {
+ let out = format.replace(//g, srcCid.toString())
+ out = out.replace(//g, dstCid.toString())
+ out = out.replace(//g, linkName)
+ return out
+}
+
+// Do a depth first search of the DAG, starting from the given root cid
+function objectStream (ipfs, rootCid, maxDepth, isUnique) {
+ const uniques = new Set()
+
+ const root = { node: { cid: rootCid }, depth: 0 }
+ const traverseLevel = (obj) => {
+ const { node, depth } = obj
+
+ // Check the depth
+ const nextLevelDepth = depth + 1
+ if (nextLevelDepth > maxDepth) {
+ return pull.empty()
+ }
+
+ // If unique option is enabled, check if the CID has been seen before.
+ // Note we need to do this here rather than before adding to the stream
+ // so that the unique check happens in the order that items are examined
+ // in the DAG.
+ if (isUnique) {
+ if (uniques.has(node.cid.toString())) {
+ // Mark this object as a duplicate so we can filter it out later
+ obj.isDuplicate = true
+ return pull.empty()
+ }
+ uniques.add(node.cid.toString())
+ }
+
+ const deferred = pullDefer.source()
+
+ // Get this object's links
+ getLinks(ipfs, node.cid, (err, links) => {
+ if (err) {
+ if (err.code === 'ERR_NOT_FOUND') {
+ err.message = `Could not find object with CID: ${node.cid}`
+ }
+ return deferred.resolve(pull.error(err))
+ }
+
+ // Add to the stream each link, parent and the new depth
+ const vals = links.map(link => ({
+ parent: node,
+ node: link,
+ depth: nextLevelDepth
+ }))
+
+ deferred.resolve(pull.values(vals))
+ })
+
+ return deferred
+ }
+
+ return pullTraverse.depthFirst(root, traverseLevel)
+}
+
+// Fetch a node from IPLD then get all its links
+function getLinks (ipfs, cid, callback) {
+ ipfs._ipld.get(new CID(cid))
+ .then(node => {
+ let links
+ if (DAGNode.isDAGNode(node)) {
+ links = node.Links.map(({ Name, Hash }) => {
+ return { name: Name, cid: new CID(Hash) }
+ })
+ } else {
+ links = getNodeLinks(node)
+ }
+ callback(null, links)
+ })
+ .catch(callback)
+}
+
+// Recursively search the node for CIDs
+function getNodeLinks (node, path = '') {
+ let links = []
+ for (const [name, value] of Object.entries(node)) {
+ if (CID.isCID(value)) {
+ links.push({
+ name: path + name,
+ cid: value
+ })
+ } else if (typeof value === 'object') {
+ links = links.concat(getNodeLinks(value, path + name + '/'))
+ }
+ }
+ return links
+}
+
+},{"./refs":507,"./utils":508,"cids":185,"ipld-dag-pb":589,"is-ipfs":614,"pull-cat":1283,"pull-defer":1285,"pull-stream":1311,"pull-traverse":1343}],506:[function(require,module,exports){
+'use strict'
+
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function (self) {
+ return (ipfsPath, options) => {
+ return toStream.source(self.refsPullStream(ipfsPath, options))
+ }
+}
+
+},{"pull-stream-to-stream":1310}],507:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream')
+
+module.exports = function (self) {
+ return promisify((ipfsPath, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ pull(
+ self.refsPullStream(ipfsPath, options),
+ pull.collect((err, values) => {
+ if (err) {
+ return callback(err)
+ }
+ callback(null, values)
+ })
+ )
+ })
+}
+
+// Preset format strings
+module.exports.Format = {
+ default: '',
+ edges: ' -> '
+}
+
+},{"promisify-es6":1263,"pull-stream":1311}],508:[function(require,module,exports){
+'use strict'
+
+const CID = require('cids')
+const { Buffer } = require('buffer')
+const { cidToString } = require('../../../utils/cid')
+const toPullStream = require('async-iterator-to-pull-stream')
+
+const normalizePath = (path) => {
+ if (Buffer.isBuffer(path)) {
+ return new CID(path).toString()
+ }
+ if (CID.isCID(path)) {
+ return path.toString()
+ }
+ if (path.indexOf('/ipfs/') === 0) {
+ path = path.substring('/ipfs/'.length)
+ }
+ if (path.charAt(path.length - 1) === '/') {
+ path = path.substring(0, path.length - 1)
+ }
+ return path
+}
+
+/**
+ * Parses chunker string into options used by DAGBuilder in ipfs-unixfs-engine
+ *
+ *
+ * @param {String} chunker Chunker algorithm supported formats:
+ * "size-{size}"
+ * "rabin"
+ * "rabin-{avg}"
+ * "rabin-{min}-{avg}-{max}"
+ *
+ * @return {Object} Chunker options for DAGBuilder
+ */
+const parseChunkerString = (chunker) => {
+ if (!chunker) {
+ return {
+ chunker: 'fixed'
+ }
+ } else if (chunker.startsWith('size-')) {
+ const sizeStr = chunker.split('-')[1]
+ const size = parseInt(sizeStr)
+ if (isNaN(size)) {
+ throw new Error('Chunker parameter size must be an integer')
+ }
+ return {
+ chunker: 'fixed',
+ chunkerOptions: {
+ maxChunkSize: size
+ }
+ }
+ } else if (chunker.startsWith('rabin')) {
+ return {
+ chunker: 'rabin',
+ chunkerOptions: parseRabinString(chunker)
+ }
+ } else {
+ throw new Error(`Unrecognized chunker option: ${chunker}`)
+ }
+}
+
+/**
+ * Parses rabin chunker string
+ *
+ * @param {String} chunker Chunker algorithm supported formats:
+ * "rabin"
+ * "rabin-{avg}"
+ * "rabin-{min}-{avg}-{max}"
+ *
+ * @return {Object} rabin chunker options
+ */
+const parseRabinString = (chunker) => {
+ const options = {}
+ const parts = chunker.split('-')
+ switch (parts.length) {
+ case 1:
+ options.avgChunkSize = 262144
+ break
+ case 2:
+ options.avgChunkSize = parseChunkSize(parts[1], 'avg')
+ break
+ case 4:
+ options.minChunkSize = parseChunkSize(parts[1], 'min')
+ options.avgChunkSize = parseChunkSize(parts[2], 'avg')
+ options.maxChunkSize = parseChunkSize(parts[3], 'max')
+ break
+ default:
+ throw new Error('Incorrect chunker format (expected "rabin" "rabin-[avg]" or "rabin-[min]-[avg]-[max]"')
+ }
+
+ return options
+}
+
+const parseChunkSize = (str, name) => {
+ const size = parseInt(str)
+ if (isNaN(size)) {
+ throw new Error(`Chunker parameter ${name} must be an integer`)
+ }
+
+ return size
+}
+
+const mapFile = (options = {}) => {
+ return (file) => {
+ let size = 0
+ let type = 'dir'
+
+ if (file.unixfs && file.unixfs.type === 'file') {
+ size = file.unixfs.fileSize()
+ type = 'file'
+ }
+
+ const output = {
+ hash: cidToString(file.cid, { base: options.cidBase }),
+ path: file.path,
+ name: file.name,
+ depth: file.path.split('/').length,
+ size,
+ type
+ }
+
+ if (options.includeContent && file.unixfs && file.unixfs.type === 'file') {
+ output.content = toPullStream.source(file.content())
+ }
+
+ return output
+ }
+}
+
+module.exports = {
+ normalizePath,
+ parseChunkSize,
+ parseRabinString,
+ parseChunkerString,
+ mapFile
+}
+
+},{"../../../utils/cid":561,"async-iterator-to-pull-stream":34,"buffer":181,"cids":185}],509:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const setImmediate = require('async/setImmediate')
+const pkgversion = require('../../../package.json').version
+
+module.exports = function id (self) {
+ return promisify((opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ setImmediate(() => callback(null, {
+ id: self._peerInfo.id.toB58String(),
+ publicKey: self._peerInfo.id.pubKey.bytes.toString('base64'),
+ addresses: self._peerInfo.multiaddrs
+ .toArray()
+ .map((ma) => ma.toString())
+ .filter((ma) => ma.indexOf('ipfs') >= 0)
+ .sort(),
+ agentVersion: `js-ipfs/${pkgversion}`,
+ protocolVersion: '9000'
+ }))
+ })
+}
+
+},{"../../../package.json":475,"async/setImmediate":96,"promisify-es6":1263}],510:[function(require,module,exports){
+'use strict'
+
+exports.preStart = require('./pre-start')
+exports.start = require('./start')
+exports.stop = require('./stop')
+exports.isOnline = require('./is-online')
+exports.version = require('./version')
+exports.id = require('./id')
+exports.repo = require('./repo')
+exports.init = require('./init')
+exports.bootstrap = require('./bootstrap')
+exports.config = require('./config')
+exports.block = require('./block')
+exports.object = require('./object')
+exports.dag = require('./dag')
+exports.libp2p = require('./libp2p')
+exports.swarm = require('./swarm')
+exports.ping = require('./ping')
+exports.pingPullStream = require('./ping-pull-stream')
+exports.pingReadableStream = require('./ping-readable-stream')
+exports.pin = require('./pin')
+exports.filesRegular = require('./files-regular')
+exports.filesMFS = require('./files-mfs')
+exports.bitswap = require('./bitswap')
+exports.pubsub = require('./pubsub')
+exports.dht = require('./dht')
+exports.dns = require('./dns')
+exports.key = require('./key')
+exports.stats = require('./stats')
+exports.resolve = require('./resolve')
+exports.name = require('./name')
+
+},{"./bitswap":477,"./block":478,"./bootstrap":479,"./config":480,"./dag":481,"./dht":482,"./dns":483,"./files-mfs":484,"./files-regular":498,"./id":509,"./init":511,"./is-online":512,"./key":513,"./libp2p":514,"./name":516,"./object":518,"./pin":519,"./ping":527,"./ping-pull-stream":525,"./ping-readable-stream":526,"./pre-start":528,"./pubsub":529,"./repo":530,"./resolve":531,"./start":532,"./stats":533,"./stop":534,"./swarm":535,"./version":536}],511:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const peerId = require('peer-id')
+const mergeOptions = require('merge-options')
+const waterfall = require('async/waterfall')
+const parallel = require('async/parallel')
+const promisify = require('promisify-es6')
+const defaultConfig = require('../runtime/config-nodejs.js')
+const Keychain = require('libp2p-keychain')
+const {
+ DAGNode
+} = require('ipld-dag-pb')
+const UnixFs = require('ipfs-unixfs')
+const multicodec = require('multicodec')
+
+const IPNS = require('../ipns')
+const OfflineDatastore = require('../ipns/routing/offline-datastore')
+
+const addDefaultAssets = require('./init-assets')
+
+module.exports = function init (self) {
+ return promisify((opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ const done = (err, res) => {
+ if (err) {
+ self.emit('error', err)
+ return callback(err)
+ }
+
+ self.preStart((err) => {
+ if (err) {
+ self.emit('error', err)
+ return callback(err)
+ }
+
+ self.state.initialized()
+ self.emit('init')
+ callback(null, res)
+ })
+ }
+
+ if (self.state.state() !== 'uninitialized') {
+ return done(new Error('Not able to init from state: ' + self.state.state()))
+ }
+
+ self.state.init()
+ self.log('init')
+
+ // An initialized, open repo was passed, use this one!
+ if (opts.repo) {
+ self._repo = opts.repo
+ return done(null, true)
+ }
+
+ opts.emptyRepo = opts.emptyRepo || false
+ opts.bits = Number(opts.bits) || 2048
+ opts.log = opts.log || function () {}
+
+ const config = mergeOptions(defaultConfig(), self._options.config)
+ let privateKey
+
+ waterfall([
+ // Verify repo does not yet exist.
+ (cb) => self._repo.exists(cb),
+ (exists, cb) => {
+ self.log('repo exists?', exists)
+ if (exists === true) {
+ return cb(new Error('repo already exists'))
+ }
+
+ if (opts.privateKey) {
+ self.log('using user-supplied private-key')
+ if (typeof opts.privateKey === 'object') {
+ cb(null, opts.privateKey)
+ } else {
+ peerId.createFromPrivKey(Buffer.from(opts.privateKey, 'base64'), cb)
+ }
+ } else {
+ // Generate peer identity keypair + transform to desired format + add to config.
+ opts.log(`generating ${opts.bits}-bit RSA keypair...`, false)
+ self.log('generating peer id: %s bits', opts.bits)
+ peerId.create({ bits: opts.bits }, cb)
+ }
+ },
+ (peerId, cb) => {
+ self.log('identity generated')
+ config.Identity = {
+ PeerID: peerId.toB58String(),
+ PrivKey: peerId.privKey.bytes.toString('base64')
+ }
+ privateKey = peerId.privKey
+ if (opts.pass) {
+ config.Keychain = Keychain.generateOptions()
+ }
+ opts.log('done')
+ opts.log('peer identity: ' + config.Identity.PeerID)
+
+ self._repo.init(config, cb)
+ },
+ (_, cb) => self._repo.open(cb),
+ (cb) => {
+ self.log('repo opened')
+ if (opts.pass) {
+ self.log('creating keychain')
+ const keychainOptions = Object.assign({ passPhrase: opts.pass }, config.Keychain)
+ self._keychain = new Keychain(self._repo.keys, keychainOptions)
+ self._keychain.importPeer('self', { privKey: privateKey }, cb)
+ } else {
+ cb(null, true)
+ }
+ },
+ // Setup the offline routing for IPNS.
+ // This is primarily used for offline ipns modifications, such as the initializeKeyspace feature.
+ (_, cb) => {
+ const offlineDatastore = new OfflineDatastore(self._repo)
+
+ self._ipns = new IPNS(offlineDatastore, self._repo.datastore, self._peerInfo, self._keychain, self._options)
+ cb(null, true)
+ },
+ // add empty unixfs dir object (go-ipfs assumes this exists)
+ (_, cb) => {
+ if (opts.emptyRepo) {
+ return cb(null, true)
+ }
+
+ const tasks = [
+ (cb) => {
+ waterfall([
+ (cb) => {
+ try {
+ cb(null, DAGNode.create(new UnixFs('directory').marshal()))
+ } catch (err) {
+ cb(err)
+ }
+ },
+ (node, cb) => self.dag.put(node, {
+ version: 0,
+ format: multicodec.DAG_PB,
+ hashAlg: multicodec.SHA2_256
+ }).then(
+ (cid) => cb(null, cid),
+ (error) => cb(error)
+ ),
+ (cid, cb) => self._ipns.initializeKeyspace(privateKey, cid.toBaseEncodedString(), cb)
+ ], cb)
+ }
+ ]
+
+ if (typeof addDefaultAssets === 'function') {
+ // addDefaultAssets is undefined on browsers.
+ // See package.json browser config
+ tasks.push((cb) => addDefaultAssets(self, opts.log, cb))
+ }
+
+ self.log('adding assets')
+ parallel(tasks, (err) => {
+ if (err) {
+ cb(err)
+ } else {
+ cb(null, true)
+ }
+ })
+ }
+ ], done)
+ })
+}
+
+}).call(this,require("buffer").Buffer)
+},{"../ipns":539,"../ipns/routing/offline-datastore":545,"../runtime/config-nodejs.js":551,"./init-assets":146,"async/parallel":91,"async/waterfall":102,"buffer":181,"ipfs-unixfs":435,"ipld-dag-pb":589,"libp2p-keychain":926,"merge-options":1127,"multicodec":1151,"peer-id":1253,"promisify-es6":1263}],512:[function(require,module,exports){
+'use strict'
+
+module.exports = function isOnline (self) {
+ return () => {
+ return Boolean(self._bitswap && self.libp2p && self.libp2p.isStarted())
+ }
+}
+
+},{}],513:[function(require,module,exports){
+'use strict'
+
+// See https://github.com/ipfs/specs/tree/master/keystore
+
+const promisify = require('promisify-es6')
+
+module.exports = function key (self) {
+ return {
+ gen: promisify((name, opts, callback) => {
+ opts = opts || {}
+ self._keychain.createKey(name, opts.type, opts.size, callback)
+ }),
+
+ info: promisify((name, callback) => {
+ self._keychain.findKeyByName(name, callback)
+ }),
+
+ list: promisify((callback) => {
+ self._keychain.listKeys(callback)
+ }),
+
+ rm: promisify((name, callback) => {
+ self._keychain.removeKey(name, callback)
+ }),
+
+ rename: promisify((oldName, newName, callback) => {
+ self._keychain.renameKey(oldName, newName, (err, key) => {
+ if (err) return callback(err)
+ const result = {
+ was: oldName,
+ now: key.name,
+ id: key.id,
+ overwrite: false
+ }
+ callback(null, result)
+ })
+ }),
+
+ import: promisify((name, pem, password, callback) => {
+ self._keychain.importKey(name, pem, password, callback)
+ }),
+
+ export: promisify((name, password, callback) => {
+ self._keychain.exportKey(name, password, callback)
+ })
+ }
+}
+
+},{"promisify-es6":1263}],514:[function(require,module,exports){
+'use strict'
+
+const get = require('dlv')
+const mergeOptions = require('merge-options')
+const errCode = require('err-code')
+const ipnsUtils = require('../ipns/routing/utils')
+const multiaddr = require('multiaddr')
+const DelegatedPeerRouter = require('libp2p-delegated-peer-routing')
+const DelegatedContentRouter = require('libp2p-delegated-content-routing')
+const PubsubRouters = require('../runtime/libp2p-pubsub-routers-nodejs')
+
+module.exports = function libp2p (self, config) {
+ const options = self._options || {}
+ config = config || {}
+
+ // Always create libp2p via a bundle function
+ const createBundle = typeof options.libp2p === 'function'
+ ? options.libp2p
+ : defaultBundle
+
+ const { datastore } = self._repo
+ const peerInfo = self._peerInfo
+ const peerBook = self._peerInfoBook
+ const libp2p = createBundle({ options, config, datastore, peerInfo, peerBook })
+
+ libp2p.on('stop', () => {
+ // Clear our addresses so we can start clean
+ peerInfo.multiaddrs.clear()
+ })
+
+ libp2p.on('start', () => {
+ peerInfo.multiaddrs.forEach((ma) => {
+ self._print('Swarm listening on', ma.toString())
+ })
+ })
+
+ libp2p.on('peer:connect', peerInfo => peerBook.put(peerInfo))
+
+ return libp2p
+}
+
+function defaultBundle ({ datastore, peerInfo, peerBook, options, config }) {
+ // Set up Delegate Routing based on the presence of Delegates in the config
+ let contentRouting
+ let peerRouting
+ const delegateHosts = get(options, 'config.Addresses.Delegates',
+ get(config, 'Addresses.Delegates', [])
+ )
+ if (delegateHosts.length > 0) {
+ // Pick a random delegate host
+ const delegateString = delegateHosts[Math.floor(Math.random() * delegateHosts.length)]
+ const delegateAddr = multiaddr(delegateString).toOptions()
+ const delegatedApiOptions = {
+ host: delegateAddr.host,
+ // port is a string atm, so we need to convert for the check
+ protocol: parseInt(delegateAddr.port) === 443 ? 'https' : 'http',
+ port: delegateAddr.port
+ }
+ contentRouting = [new DelegatedContentRouter(peerInfo.id, delegatedApiOptions)]
+ peerRouting = [new DelegatedPeerRouter(delegatedApiOptions)]
+ }
+
+ const getPubsubRouter = () => {
+ let router = get(config, 'Pubsub.Router', 'gossipsub')
+
+ if (!router) {
+ router = 'gossipsub'
+ }
+
+ if (!PubsubRouters[router]) {
+ throw errCode(new Error(`Router unavailable. Configure libp2p.modules.pubsub to use the ${router} router.`), 'ERR_NOT_SUPPORTED')
+ }
+
+ return PubsubRouters[router]
+ }
+
+ const libp2pDefaults = {
+ datastore,
+ peerInfo,
+ peerBook,
+ modules: {
+ contentRouting,
+ peerRouting,
+ pubsub: getPubsubRouter()
+ },
+ config: {
+ peerDiscovery: {
+ mdns: {
+ enabled: get(options, 'config.Discovery.MDNS.Enabled',
+ get(config, 'Discovery.MDNS.Enabled', true))
+ },
+ webRTCStar: {
+ enabled: get(options, 'config.Discovery.webRTCStar.Enabled',
+ get(config, 'Discovery.webRTCStar.Enabled', true))
+ },
+ bootstrap: {
+ list: get(options, 'config.Bootstrap',
+ get(config, 'Bootstrap', []))
+ }
+ },
+ relay: {
+ enabled: get(options, 'relay.enabled',
+ get(config, 'relay.enabled', true)),
+ hop: {
+ enabled: get(options, 'relay.hop.enabled',
+ get(config, 'relay.hop.enabled', false)),
+ active: get(options, 'relay.hop.active',
+ get(config, 'relay.hop.active', false))
+ }
+ },
+ dht: {
+ kBucketSize: get(options, 'dht.kBucketSize', 20),
+ // enabled: !get(options, 'offline', false), // disable if offline, on by default
+ enabled: false,
+ randomWalk: {
+ enabled: false // disabled waiting for https://github.com/libp2p/js-libp2p-kad-dht/issues/86
+ },
+ validators: {
+ ipns: ipnsUtils.validator
+ },
+ selectors: {
+ ipns: ipnsUtils.selector
+ }
+ },
+ pubsub: {
+ enabled: get(config, 'Pubsub.Enabled', true)
+ }
+ },
+ connectionManager: get(options, 'connectionManager',
+ {
+ maxPeers: get(config, 'Swarm.ConnMgr.HighWater'),
+ minPeers: get(config, 'Swarm.ConnMgr.LowWater')
+ })
+ }
+
+ const libp2pOptions = mergeOptions(libp2pDefaults, get(options, 'libp2p', {}))
+ // Required inline to reduce startup time
+ // Note: libp2p-nodejs gets replaced by libp2p-browser when webpacked/browserified
+ const Node = require('../runtime/libp2p-nodejs')
+ return new Node(libp2pOptions)
+}
+
+},{"../ipns/routing/utils":547,"../runtime/libp2p-nodejs":555,"../runtime/libp2p-pubsub-routers-nodejs":556,"dlv":233,"err-code":268,"libp2p-delegated-content-routing":808,"libp2p-delegated-peer-routing":844,"merge-options":1127,"multiaddr":1140}],515:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const errcode = require('err-code')
+const promisify = require('promisify-es6')
+
+const IpnsPubsubDatastore = require('../ipns/routing/pubsub-datastore')
+
+const log = debug('ipfs:name-pubsub')
+log.error = debug('ipfs:name-pubsub:error')
+
+// Is pubsub enabled
+const isNamePubsubEnabled = (node) => {
+ try {
+ return Boolean(getPubsubRouting(node))
+ } catch (err) {
+ return false
+ }
+}
+
+// Get pubsub from IPNS routing
+const getPubsubRouting = (node) => {
+ if (!node._ipns || !node._options.EXPERIMENTAL.ipnsPubsub) {
+ throw errcode(new Error('IPNS pubsub subsystem is not enabled'), 'ERR_IPNS_PUBSUB_NOT_ENABLED')
+ }
+
+ // Only one store and it is pubsub
+ if (IpnsPubsubDatastore.isIpnsPubsubDatastore(node._ipns.routing)) {
+ return node._ipns.routing
+ }
+
+ // Find in tiered
+ const pubsub = (node._ipns.routing.stores || []).find(s => IpnsPubsubDatastore.isIpnsPubsubDatastore(s))
+
+ if (!pubsub) {
+ throw errcode(new Error('IPNS pubsub datastore not found'), 'ERR_PUBSUB_DATASTORE_NOT_FOUND')
+ }
+
+ return pubsub
+}
+
+module.exports = function namePubsub (self) {
+ return {
+ /**
+ * Query the state of IPNS pubsub.
+ *
+ * @returns {Promise|void}
+ */
+ state: promisify((callback) => {
+ callback(null, {
+ enabled: isNamePubsubEnabled(self)
+ })
+ }),
+ /**
+ * Cancel a name subscription.
+ *
+ * @param {String} name subscription name.
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ cancel: promisify((name, callback) => {
+ let pubsub
+ try {
+ pubsub = getPubsubRouting(self)
+ } catch (err) {
+ return callback(err)
+ }
+
+ pubsub.cancel(name, callback)
+ }),
+ /**
+ * Show current name subscriptions.
+ *
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ subs: promisify((callback) => {
+ let pubsub
+ try {
+ pubsub = getPubsubRouting(self)
+ } catch (err) {
+ return callback(err)
+ }
+
+ pubsub.getSubscriptions(callback)
+ })
+ }
+}
+
+},{"../ipns/routing/pubsub-datastore":546,"debug":456,"err-code":268,"promisify-es6":1263}],516:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const promisify = require('promisify-es6')
+const waterfall = require('async/waterfall')
+const parallel = require('async/parallel')
+const human = require('human-to-milliseconds')
+const crypto = require('libp2p-crypto')
+const errcode = require('err-code')
+const mergeOptions = require('merge-options')
+const mh = require('multihashes')
+const isDomain = require('is-domain-name')
+
+const log = debug('ipfs:name')
+log.error = debug('ipfs:name:error')
+
+const namePubsub = require('./name-pubsub')
+const utils = require('../utils')
+const path = require('../ipns/path')
+
+const keyLookup = (ipfsNode, kname, callback) => {
+ if (kname === 'self') {
+ return callback(null, ipfsNode._peerInfo.id.privKey)
+ }
+
+ const pass = ipfsNode._options.pass
+
+ waterfall([
+ (cb) => ipfsNode._keychain.exportKey(kname, pass, cb),
+ (pem, cb) => crypto.keys.import(pem, pass, cb)
+ ], (err, privateKey) => {
+ if (err) {
+ log.error(err)
+ return callback(errcode(err, 'ERR_CANNOT_GET_KEY'))
+ }
+
+ return callback(null, privateKey)
+ })
+}
+
+const appendRemainder = (cb, remainder) => {
+ return (err, result) => {
+ if (err) {
+ return cb(err)
+ }
+ if (remainder.length) {
+ return cb(null, result + '/' + remainder.join('/'))
+ }
+ return cb(null, result)
+ }
+}
+
+/**
+ * @typedef { import("../index") } IPFS
+ */
+
+/**
+ * IPNS - Inter-Planetary Naming System
+ *
+ * @param {IPFS} self
+ * @returns {Object}
+ */
+module.exports = function name (self) {
+ return {
+ /**
+ * IPNS is a PKI namespace, where names are the hashes of public keys, and
+ * the private key enables publishing new (signed) values. In both publish
+ * and resolve, the default name used is the node's own PeerID,
+ * which is the hash of its public key.
+ *
+ * @param {String} value ipfs path of the object to be published.
+ * @param {Object} options ipfs publish options.
+ * @param {boolean} options.resolve resolve given path before publishing.
+ * @param {String} options.lifetime time duration that the record will be valid for.
+ This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are
+ "ns", "ms", "s", "m", "h". Default is 24h.
+ * @param {String} options.ttl time duration this record should be cached for (NOT IMPLEMENTED YET).
+ * This accepts durations such as "300s", "1.5h" or "2h45m". Valid time units are
+ "ns", "ms", "s", "m", "h" (caution: experimental).
+ * @param {String} options.key name of the key to be used, as listed by 'ipfs key list -l'.
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ publish: promisify((value, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+ const resolve = !(options.resolve === false)
+ const lifetime = options.lifetime || '24h'
+ const key = options.key || 'self'
+
+ if (!self.isOnline()) {
+ return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR'))
+ }
+
+ // TODO: params related logic should be in the core implementation
+
+ // Normalize path value
+ try {
+ value = utils.normalizePath(value)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ let pubLifetime
+ try {
+ pubLifetime = human(lifetime)
+
+ // Calculate lifetime with nanoseconds precision
+ pubLifetime = pubLifetime.toFixed(6)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ // TODO: ttl human for cache
+
+ parallel([
+ (cb) => keyLookup(self, key, cb),
+ // verify if the path exists, if not, an error will stop the execution
+ (cb) => resolve.toString() === 'true' ? path.resolvePath(self, value, cb) : cb()
+ ], (err, results) => {
+ if (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ // Start publishing process
+ self._ipns.publish(results[0], value, pubLifetime, callback)
+ })
+ }),
+
+ /**
+ * Given a key, query the DHT for its best value.
+ *
+ * @param {String} name ipns name to resolve. Defaults to your node's peerID.
+ * @param {Object} options ipfs resolve options.
+ * @param {boolean} options.nocache do not use cached entries.
+ * @param {boolean} options.recursive resolve until the result is not an IPNS name.
+ * @param {function(Error)} [callback]
+ * @returns {Promise|void}
+ */
+ resolve: promisify((name, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = mergeOptions({
+ nocache: false,
+ recursive: true
+ }, options)
+
+ const offline = self._options.offline
+
+ // TODO: params related logic should be in the core implementation
+ if (offline && options.nocache) {
+ return callback(errcode(new Error('cannot specify both offline and nocache'), 'ERR_NOCACHE_AND_OFFLINE'))
+ }
+
+ // Set node id as name for being resolved, if it is not received
+ if (!name) {
+ name = self._peerInfo.id.toB58String()
+ }
+
+ if (!name.startsWith('/ipns/')) {
+ name = `/ipns/${name}`
+ }
+
+ const [namespace, hash, ...remainder] = name.slice(1).split('/')
+ try {
+ mh.fromB58String(hash)
+ } catch (err) {
+ // lets check if we have a domain ex. /ipns/ipfs.io and resolve with dns
+ if (isDomain(hash)) {
+ return self.dns(hash, options, appendRemainder(callback, remainder))
+ }
+
+ log.error(err)
+ return callback(errcode(new Error('Invalid IPNS name'), 'ERR_IPNS_INVALID_NAME'))
+ }
+
+ // multihash is valid lets resolve with IPNS
+ // IPNS resolve needs a online daemon
+ if (!self.isOnline() && !offline) {
+ return callback(errcode(new Error(utils.OFFLINE_ERROR), 'OFFLINE_ERROR'))
+ }
+
+ self._ipns.resolve(`/${namespace}/${hash}`, options, appendRemainder(callback, remainder))
+ }),
+ pubsub: namePubsub(self)
+ }
+}
+
+},{"../ipns/path":540,"../utils":560,"./name-pubsub":515,"async/parallel":91,"async/waterfall":102,"debug":456,"err-code":268,"human-to-milliseconds":312,"is-domain-name":611,"libp2p-crypto":745,"merge-options":1127,"multihashes":1157,"promisify-es6":1263}],517:[function(require,module,exports){
+'use strict'
+
+function fail () {
+ throw new Error('Key management requires \'--pass ...\' option')
+}
+
+class NoKeychain {
+ static get options () { fail() }
+
+ static generateOptions () { fail() }
+
+ createKey () { fail() }
+
+ listKeys () { fail() }
+
+ findKeyById () { fail() }
+
+ findKeyByName () { fail() }
+
+ renameKey () { fail() }
+
+ removeKey () { fail() }
+
+ exportKey () { fail() }
+
+ importKey () { fail() }
+
+ importPeer () { fail() }
+
+ get cms () { fail() }
+}
+
+module.exports = NoKeychain
+
+},{}],518:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const waterfall = require('async/waterfall')
+const parallel = require('async/parallel')
+const setImmediate = require('async/setImmediate')
+const promisify = require('promisify-es6')
+const dagPB = require('ipld-dag-pb')
+const DAGNode = dagPB.DAGNode
+const DAGLink = dagPB.DAGLink
+const CID = require('cids')
+const mh = require('multihashes')
+const multicodec = require('multicodec')
+const Unixfs = require('ipfs-unixfs')
+const errCode = require('err-code')
+
+function normalizeMultihash (multihash, enc) {
+ if (typeof multihash === 'string') {
+ if (enc === 'base58' || !enc) {
+ return multihash
+ }
+
+ return Buffer.from(multihash, enc)
+ } else if (Buffer.isBuffer(multihash)) {
+ return multihash
+ } else if (CID.isCID(multihash)) {
+ return multihash.buffer
+ } else {
+ throw new Error('unsupported multihash')
+ }
+}
+
+function parseBuffer (buf, encoding, callback) {
+ switch (encoding) {
+ case 'json':
+ return parseJSONBuffer(buf, callback)
+ case 'protobuf':
+ return parseProtoBuffer(buf, callback)
+ default:
+ callback(new Error(`unkown encoding: ${encoding}`))
+ }
+}
+
+function parseJSONBuffer (buf, callback) {
+ let data
+ let links
+
+ try {
+ const parsed = JSON.parse(buf.toString())
+
+ links = (parsed.Links || []).map((link) => {
+ return new DAGLink(
+ link.Name || link.name,
+ link.Size || link.size,
+ mh.fromB58String(link.Hash || link.hash || link.multihash)
+ )
+ })
+ data = Buffer.from(parsed.Data)
+ } catch (err) {
+ return callback(new Error('failed to parse JSON: ' + err))
+ }
+
+ try {
+ callback(null, DAGNode.create(data, links))
+ } catch (err) {
+ callback(err)
+ }
+}
+
+function parseProtoBuffer (buf, callback) {
+ let obj
+ try {
+ obj = dagPB.util.deserialize(buf)
+ } catch (err) {
+ return callback(err)
+ }
+ callback(null, obj)
+}
+
+function findLinks (node, links = []) {
+ for (const key in node) {
+ const val = node[key]
+
+ if (key === '/' && Object.keys(node).length === 1) {
+ try {
+ links.push(new DAGLink('', 0, new CID(val)))
+ continue
+ } catch (_) {
+ // not a CID
+ }
+ }
+
+ if (CID.isCID(val)) {
+ links.push(new DAGLink('', 0, val))
+
+ continue
+ }
+
+ if (Array.isArray(val)) {
+ findLinks(val, links)
+ }
+
+ if (typeof val === 'object' && !(val instanceof String)) {
+ findLinks(val, links)
+ }
+ }
+
+ return links
+}
+
+module.exports = function object (self) {
+ function editAndSave (edit) {
+ return (multihash, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ waterfall([
+ (cb) => {
+ self.object.get(multihash, options, cb)
+ },
+ (node, cb) => {
+ // edit applies the edit func passed to
+ // editAndSave
+ edit(node, (err, node) => {
+ if (err) {
+ return cb(err)
+ }
+
+ self._ipld.put(node, multicodec.DAG_PB, {
+ cidVersion: 0,
+ hashAlg: multicodec.SHA2_256
+ }).then(
+ (cid) => {
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ cb(null, cid)
+ },
+ (error) => cb(error)
+ )
+ })
+ }
+ ], callback)
+ }
+ }
+
+ return {
+ new: promisify((template, options, callback) => {
+ if (typeof template === 'function') {
+ callback = template
+ template = undefined
+ options = {}
+ }
+
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ let data
+
+ if (template) {
+ if (template !== 'unixfs-dir') {
+ return setImmediate(() => callback(new Error('unknown template')))
+ }
+ data = (new Unixfs('directory')).marshal()
+ } else {
+ data = Buffer.alloc(0)
+ }
+
+ let node
+
+ try {
+ node = DAGNode.create(data)
+ } catch (err) {
+ return callback(err)
+ }
+
+ self._ipld.put(node, multicodec.DAG_PB, {
+ cidVersion: 0,
+ hashAlg: multicodec.SHA2_256
+ }).then(
+ (cid) => {
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ callback(null, cid)
+ },
+ (error) => callback(error)
+ )
+ }),
+ put: promisify((obj, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ const encoding = options.enc
+ let node
+
+ if (Buffer.isBuffer(obj)) {
+ if (encoding) {
+ parseBuffer(obj, encoding, (err, _node) => {
+ if (err) {
+ return callback(err)
+ }
+ node = _node
+ next()
+ })
+ } else {
+ try {
+ node = DAGNode.create(obj)
+ } catch (err) {
+ return callback(err)
+ }
+
+ next()
+ }
+ } else if (DAGNode.isDAGNode(obj)) {
+ // already a dag node
+ node = obj
+ next()
+ } else if (typeof obj === 'object') {
+ try {
+ node = DAGNode.create(obj.Data, obj.Links)
+ } catch (err) {
+ return callback(err)
+ }
+
+ next()
+ } else {
+ return callback(new Error('obj not recognized'))
+ }
+
+ function next () {
+ self._gcLock.readLock((cb) => {
+ self._ipld.put(node, multicodec.DAG_PB, {
+ cidVersion: 0,
+ hashAlg: multicodec.SHA2_256
+ }).then(
+ (cid) => {
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ cb(null, cid)
+ },
+ cb
+ )
+ }, callback)
+ }
+ }),
+
+ get: promisify((multihash, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ let mh, cid
+
+ try {
+ mh = normalizeMultihash(multihash, options.enc)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_MULTIHASH')))
+ }
+
+ try {
+ cid = new CID(mh)
+ } catch (err) {
+ return setImmediate(() => callback(errCode(err, 'ERR_INVALID_CID')))
+ }
+
+ if (options.cidVersion === 1) {
+ cid = cid.toV1()
+ }
+
+ if (options.preload !== false) {
+ self._preload(cid)
+ }
+
+ self._ipld.get(cid).then(
+ (node) => callback(null, node),
+ (error) => callback(error)
+ )
+ }),
+
+ data: promisify((multihash, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ self.object.get(multihash, options, (err, node) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, node.Data)
+ })
+ }),
+
+ links: promisify((multihash, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ const cid = new CID(multihash)
+
+ self.dag.get(cid, options, (err, result) => {
+ if (err) {
+ return callback(err)
+ }
+
+ if (cid.codec === 'raw') {
+ return callback(null, [])
+ }
+
+ if (cid.codec === 'dag-pb') {
+ return callback(null, result.value.Links)
+ }
+
+ if (cid.codec === 'dag-cbor') {
+ const links = findLinks(result)
+
+ return callback(null, links)
+ }
+
+ callback(new Error(`Cannot resolve links from codec ${cid.codec}`))
+ })
+ }),
+
+ stat: promisify((multihash, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ waterfall([
+ (cb) => self.object.get(multihash, options, cb),
+ (node, cb) => {
+ cb(null, {
+ node,
+ serialized: dagPB.util.serialize(node)
+ })
+ },
+ ({ node, serialized }, cb) => {
+ parallel({
+ serialized: (next) => next(null, serialized),
+ cid: (next) => dagPB.util.cid(serialized, {
+ cidVersion: 0
+ }).then((cid) => next(null, cid), next),
+ node: (next) => next(null, node)
+ }, cb)
+ }
+ ], (err, result) => {
+ if (err) {
+ return callback(err)
+ }
+
+ const blockSize = result.serialized.length
+ const linkLength = result.node.Links.reduce((a, l) => a + l.Tsize, 0)
+
+ callback(null, {
+ Hash: result.cid.toBaseEncodedString(),
+ NumLinks: result.node.Links.length,
+ BlockSize: blockSize,
+ LinksSize: blockSize - result.node.Data.length,
+ DataSize: result.node.Data.length,
+ CumulativeSize: blockSize + linkLength
+ })
+ })
+ }),
+
+ patch: promisify({
+ addLink (multihash, link, options, callback) {
+ editAndSave((node, cb) => {
+ DAGNode.addLink(node, link).then((node) => {
+ cb(null, node)
+ }, cb)
+ })(multihash, options, callback)
+ },
+
+ rmLink (multihash, linkRef, options, callback) {
+ editAndSave((node, cb) => {
+ linkRef = linkRef.Name || linkRef.name
+
+ try {
+ node = DAGNode.rmLink(node, linkRef)
+ } catch (err) {
+ return cb(err)
+ }
+
+ cb(null, node)
+ })(multihash, options, callback)
+ },
+
+ appendData (multihash, data, options, callback) {
+ editAndSave((node, cb) => {
+ const newData = Buffer.concat([node.Data, data])
+
+ try {
+ node = DAGNode.create(newData, node.Links)
+ } catch (err) {
+ return cb(err)
+ }
+
+ cb(null, node)
+ })(multihash, options, callback)
+ },
+
+ setData (multihash, data, options, callback) {
+ editAndSave((node, cb) => {
+ try {
+ node = DAGNode.create(data, node.Links)
+ } catch (err) {
+ return cb(err)
+ }
+
+ cb(null, node)
+ })(multihash, options, callback)
+ }
+ })
+ }
+}
+
+}).call(this,require("buffer").Buffer)
+},{"async/parallel":91,"async/setImmediate":96,"async/waterfall":102,"buffer":181,"cids":185,"err-code":268,"ipfs-unixfs":435,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157,"promisify-es6":1263}],519:[function(require,module,exports){
+/* eslint max-nested-callbacks: ["error", 8] */
+'use strict'
+
+const promisify = require('promisify-es6')
+const CID = require('cids')
+const map = require('async/map')
+const mapSeries = require('async/mapSeries')
+const waterfall = require('async/waterfall')
+const setImmediate = require('async/setImmediate')
+const errCode = require('err-code')
+const multibase = require('multibase')
+
+const { resolvePath } = require('../utils')
+const PinManager = require('./pin/pin-manager')
+const PinTypes = PinManager.PinTypes
+
+function toB58String (hash) {
+ return new CID(hash).toBaseEncodedString()
+}
+
+module.exports = (self) => {
+ const dag = self.dag
+ const pinManager = new PinManager(self._repo, dag)
+
+ const pin = {
+ add: promisify((paths, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ const recursive = options.recursive == null ? true : options.recursive
+
+ resolvePath(self.object, paths, (err, mhs) => {
+ if (err) { return callback(err) }
+
+ const pinAdd = (pinComplete) => {
+ // verify that each hash can be pinned
+ map(mhs, (multihash, cb) => {
+ const cid = new CID(multihash)
+ const key = cid.toBaseEncodedString()
+
+ if (recursive) {
+ if (pinManager.recursivePins.has(key)) {
+ // it's already pinned recursively
+ return cb(null, key)
+ }
+
+ // entire graph of nested links should be pinned,
+ // so make sure we have all the objects
+ pinManager.fetchCompleteDag(key, { preload: options.preload }, (err) => {
+ if (err) { return cb(err) }
+ // found all objects, we can add the pin
+ return cb(null, key)
+ })
+ } else {
+ if (pinManager.recursivePins.has(key)) {
+ // recursive supersedes direct, can't have both
+ return cb(new Error(`${key} already pinned recursively`))
+ }
+ if (pinManager.directPins.has(key)) {
+ // already directly pinned
+ return cb(null, key)
+ }
+
+ // make sure we have the object
+ dag.get(cid, { preload: options.preload }, (err) => {
+ if (err) { return cb(err) }
+ // found the object, we can add the pin
+ return cb(null, key)
+ })
+ }
+ }, (err, results) => {
+ if (err) { return pinComplete(err) }
+
+ // update the pin sets in memory
+ const pinset = recursive ? pinManager.recursivePins : pinManager.directPins
+ results.forEach(key => pinset.add(key))
+
+ // persist updated pin sets to datastore
+ pinManager.flushPins((err, root) => {
+ if (err) { return pinComplete(err) }
+ pinComplete(null, results.map(hash => ({ hash })))
+ })
+ })
+ }
+
+ // When adding a file, we take a lock that gets released after pinning
+ // is complete, so don't take a second lock here
+ const lock = options.lock !== false
+ if (lock) {
+ self._gcLock.readLock(pinAdd, callback)
+ } else {
+ pinAdd(callback)
+ }
+ })
+ }),
+
+ rm: promisify((paths, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ }
+
+ options = options || {}
+
+ const recursive = options.recursive == null ? true : options.recursive
+
+ if (options.cidBase && !multibase.names.includes(options.cidBase)) {
+ return setImmediate(() => {
+ callback(errCode(new Error('invalid multibase'), 'ERR_INVALID_MULTIBASE'))
+ })
+ }
+
+ resolvePath(self.object, paths, (err, mhs) => {
+ if (err) { return callback(err) }
+
+ self._gcLock.readLock((lockCb) => {
+ // verify that each hash can be unpinned
+ map(mhs, (multihash, cb) => {
+ pinManager.isPinnedWithType(multihash, PinTypes.all, (err, res) => {
+ if (err) { return cb(err) }
+ const { pinned, reason } = res
+ const key = toB58String(multihash)
+ if (!pinned) {
+ return cb(new Error(`${key} is not pinned`))
+ }
+
+ switch (reason) {
+ case (PinTypes.recursive):
+ if (recursive) {
+ return cb(null, key)
+ } else {
+ return cb(new Error(`${key} is pinned recursively`))
+ }
+ case (PinTypes.direct):
+ return cb(null, key)
+ default:
+ return cb(new Error(
+ `${key} is pinned indirectly under ${reason}`
+ ))
+ }
+ })
+ }, (err, results) => {
+ if (err) { return lockCb(err) }
+
+ // update the pin sets in memory
+ results.forEach(key => {
+ if (recursive && pinManager.recursivePins.has(key)) {
+ pinManager.recursivePins.delete(key)
+ } else {
+ pinManager.directPins.delete(key)
+ }
+ })
+
+ // persist updated pin sets to datastore
+ pinManager.flushPins((err, root) => {
+ if (err) { return lockCb(err) }
+ self.log(`Removed pins: ${results}`)
+ lockCb(null, results.map(hash => ({ hash })))
+ })
+ })
+ }, callback)
+ })
+ }),
+
+ ls: promisify((paths, options, callback) => {
+ let type = PinTypes.all
+ if (typeof paths === 'function') {
+ callback = paths
+ options = {}
+ paths = null
+ }
+ if (typeof options === 'function') {
+ callback = options
+ }
+ if (paths && paths.type) {
+ options = paths
+ paths = null
+ }
+
+ options = options || {}
+
+ if (options.type) {
+ type = options.type
+ if (typeof options.type === 'string') {
+ type = options.type.toLowerCase()
+ }
+ const err = PinManager.checkPinType(type)
+ if (err) {
+ return setImmediate(() => callback(err))
+ }
+ }
+
+ if (paths) {
+ // check the pinned state of specific hashes
+ waterfall([
+ (cb) => resolvePath(self.object, paths, cb),
+ (hashes, cb) => mapSeries(hashes, (hash, done) => pinManager.isPinnedWithType(hash, type, done), cb),
+ (results, cb) => {
+ results = results
+ .filter(result => result.pinned)
+ .map(({ key, reason }) => {
+ switch (reason) {
+ case PinTypes.direct:
+ case PinTypes.recursive:
+ return {
+ hash: key,
+ type: reason
+ }
+ default:
+ return {
+ hash: key,
+ type: `${PinTypes.indirect} through ${reason}`
+ }
+ }
+ })
+
+ if (!results.length) {
+ return cb(new Error(`path '${paths}' is not pinned`))
+ }
+
+ cb(null, results)
+ }
+ ], (err, results) => err ? callback(err) : callback(null, results)) // we don't want results equal [undefined] when err is present
+ } else {
+ // show all pinned items of type
+ let pins = []
+
+ if (type === PinTypes.direct || type === PinTypes.all) {
+ pins = pins.concat(
+ Array.from(pinManager.directPins).map(hash => ({
+ type: PinTypes.direct,
+ hash
+ }))
+ )
+ }
+
+ if (type === PinTypes.recursive || type === PinTypes.all) {
+ pins = pins.concat(
+ Array.from(pinManager.recursivePins).map(hash => ({
+ type: PinTypes.recursive,
+ hash
+ }))
+ )
+ }
+
+ if (type === PinTypes.indirect || type === PinTypes.all) {
+ pinManager.getIndirectKeys(options, (err, indirects) => {
+ if (err) { return callback(err) }
+ pins = pins
+ // if something is pinned both directly and indirectly,
+ // report the indirect entry
+ .filter(({ hash }) =>
+ !indirects.includes(hash) ||
+ (indirects.includes(hash) && !pinManager.directPins.has(hash))
+ )
+ .concat(indirects.map(hash => ({
+ type: PinTypes.indirect,
+ hash
+ })))
+ return callback(null, pins)
+ })
+ } else {
+ callback(null, pins)
+ }
+ }
+ }),
+
+ _isPinnedWithType: promisify(pinManager.isPinnedWithType.bind(pinManager)),
+ _getInternalBlocks: promisify(pinManager.getInternalBlocks.bind(pinManager)),
+ _load: promisify(pinManager.load.bind(pinManager))
+ }
+
+ return pin
+}
+
+},{"../utils":560,"./pin/pin-manager":522,"async/map":87,"async/mapSeries":89,"async/setImmediate":96,"async/waterfall":102,"cids":185,"err-code":268,"multibase":1148,"promisify-es6":1263}],520:[function(require,module,exports){
+'use strict'
+
+const pull = require('pull-stream/pull')
+const pullThrough = require('pull-stream/throughs/through')
+const pullAsyncMap = require('pull-stream/throughs/async-map')
+const Mutex = require('../../../utils/mutex')
+const log = require('debug')('ipfs:gc:lock')
+
+class GCLock {
+ constructor (repoOwner, options = {}) {
+ this.mutex = new Mutex(repoOwner, { ...options, log })
+ }
+
+ readLock (lockedFn, cb) {
+ return this.mutex.readLock(lockedFn, cb)
+ }
+
+ writeLock (lockedFn, cb) {
+ return this.mutex.writeLock(lockedFn, cb)
+ }
+
+ pullReadLock (lockedPullFn) {
+ return this.pullLock('readLock', lockedPullFn)
+ }
+
+ pullWriteLock (lockedPullFn) {
+ return this.pullLock('writeLock', lockedPullFn)
+ }
+
+ pullLock (type, lockedPullFn) {
+ const pullLocker = new PullLocker(this.mutex, type)
+
+ return pull(
+ pullLocker.take(),
+ lockedPullFn(),
+ pullLocker.release()
+ )
+ }
+}
+
+class PullLocker {
+ constructor (mutex, type) {
+ this.mutex = mutex
+ this.type = type
+
+ // The function to call to release the lock. It is set when the lock is taken
+ this.releaseLock = null
+ }
+
+ take () {
+ return pullAsyncMap((i, cb) => {
+ // Check if the lock has already been acquired.
+ // Note: new items will only come through the pull stream once the first
+ // item has acquired a lock.
+ if (this.releaseLock) {
+ // The lock has been acquired so return immediately
+ return cb(null, i)
+ }
+
+ // Request the lock
+ this.mutex[this.type]()
+ .then(release => {
+ // Save the release function to be called when the stream completes
+ this.releaseLock = release
+
+ // The lock has been granted, so run the locked piece of code
+ cb(null, i)
+ }, cb)
+ })
+ }
+
+ // Releases the lock
+ release () {
+ return pullThrough(null, (err) => {
+ // When the stream completes, release the lock
+ this.releaseLock(err)
+ })
+ }
+}
+
+module.exports = GCLock
+
+},{"../../../utils/mutex":562,"debug":456,"pull-stream/pull":1312,"pull-stream/throughs/async-map":1329,"pull-stream/throughs/through":1337}],521:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const promisify = require('promisify-es6')
+const CID = require('cids')
+const base32 = require('base32.js')
+const parallel = require('async/parallel')
+const mapLimit = require('async/mapLimit')
+const expErr = require('explain-error')
+const { cidToString } = require('../../../utils/cid')
+const log = require('debug')('ipfs:gc')
+// TODO: Use exported key from root when upgraded to ipfs-mfs@>=13
+// https://github.com/ipfs/js-ipfs-mfs/pull/58
+const { MFS_ROOT_KEY } = require('ipfs-mfs/src/core/utils/constants')
+
+// Limit on the number of parallel block remove operations
+const BLOCK_RM_CONCURRENCY = 256
+
+// Perform mark and sweep garbage collection
+module.exports = function gc (self) {
+ return promisify((callback) => {
+ const start = Date.now()
+ log('Creating set of marked blocks')
+
+ self._gcLock.writeLock((lockCb) => {
+ parallel([
+ // Get all blocks keys from the blockstore
+ (cb) => self._repo.blocks.query({ keysOnly: true }, cb),
+ // Mark all blocks that are being used
+ (cb) => createMarkedSet(self, cb)
+ ], (err, [blockKeys, markedSet]) => {
+ if (err) {
+ log('GC failed to fetch all block keys and created marked set', err)
+ return lockCb(err)
+ }
+
+ // Delete blocks that are not being used
+ deleteUnmarkedBlocks(self, markedSet, blockKeys, (err, res) => {
+ log(`Complete (${Date.now() - start}ms)`)
+
+ if (err) {
+ log('GC failed to delete unmarked blocks', err)
+ return lockCb(err)
+ }
+
+ lockCb(null, res)
+ })
+ })
+ }, callback)
+ })
+}
+
+// Get Set of CIDs of blocks to keep
+function createMarkedSet (ipfs, callback) {
+ parallel([
+ // All pins, direct and indirect
+ (cb) => ipfs.pin.ls((err, pins) => {
+ if (err) {
+ return cb(expErr(err, 'Could not list pinned blocks'))
+ }
+ log(`Found ${pins.length} pinned blocks`)
+ const cids = pins.map(p => new CID(p.hash))
+ // log(' ' + cids.join('\n '))
+ cb(null, cids)
+ }),
+
+ // Blocks used internally by the pinner
+ (cb) => ipfs.pin._getInternalBlocks((err, cids) => {
+ if (err) {
+ return cb(expErr(err, 'Could not list pinner internal blocks'))
+ }
+ log(`Found ${cids.length} pinner internal blocks`)
+ // log(' ' + cids.join('\n '))
+ cb(null, cids)
+ }),
+
+ // The MFS root and all its descendants
+ (cb) => ipfs._repo.root.get(MFS_ROOT_KEY, (err, mh) => {
+ if (err) {
+ if (err.code === 'ERR_NOT_FOUND') {
+ log('No blocks in MFS')
+ return cb(null, [])
+ }
+ return cb(expErr(err, 'Could not get MFS root from datastore'))
+ }
+
+ getDescendants(ipfs, new CID(mh), cb)
+ })
+ ], (err, res) => {
+ if (err) {
+ return callback(err)
+ }
+
+ const cids = [].concat(...res).map(cid => cidToString(cid, { base: 'base32' }))
+ return callback(null, new Set(cids))
+ })
+}
+
+// Recursively get descendants of the given CID
+function getDescendants (ipfs, cid, callback) {
+ ipfs.refs(cid, { recursive: true }, (err, refs) => {
+ if (err) {
+ return callback(expErr(err, 'Could not get MFS root descendants from store'))
+ }
+ const cids = [cid, ...refs.map(r => new CID(r.ref))]
+ log(`Found ${cids.length} MFS blocks`)
+ // log(' ' + cids.join('\n '))
+ callback(null, cids)
+ })
+}
+
+// Delete all blocks that are not marked as in use
+function deleteUnmarkedBlocks (ipfs, markedSet, blockKeys, callback) {
+ // Iterate through all blocks and find those that are not in the marked set
+ // The blockKeys variable has the form [ { key: Key() }, { key: Key() }, ... ]
+ const unreferenced = []
+ const res = []
+ let errCount = 0
+ for (const { key: k } of blockKeys) {
+ try {
+ const cid = dsKeyToCid(k)
+ const b32 = cid.toV1().toString('base32')
+ if (!markedSet.has(b32)) {
+ unreferenced.push(cid)
+ }
+ } catch (err) {
+ errCount++
+ const msg = `Could not convert block with key '${k}' to CID`
+ log(msg, err)
+ res.push({ err: new Error(msg + `: ${err.message}`) })
+ }
+ }
+
+ const msg = `Marked set has ${markedSet.size} unique blocks. Blockstore has ${blockKeys.length} blocks. ` +
+ `Deleting ${unreferenced.length} blocks.` + (errCount ? ` (${errCount} errors)` : '')
+ log(msg)
+ // log(' ' + unreferenced.join('\n '))
+
+ mapLimit(unreferenced, BLOCK_RM_CONCURRENCY, (cid, cb) => {
+ // Delete blocks from blockstore
+ ipfs._repo.blocks.delete(cid, (err) => {
+ const res = {
+ cid,
+ err: err && new Error(`Could not delete block with CID ${cid}: ${err.message}`)
+ }
+ cb(null, res)
+ })
+ }, (_, delRes) => {
+ callback(null, res.concat(delRes))
+ })
+}
+
+// TODO: Use exported utility when upgrade to ipfs-repo@>=0.27.1
+// https://github.com/ipfs/js-ipfs-repo/pull/206
+function dsKeyToCid (key) {
+ // Block key is of the form /
+ const decoder = new base32.Decoder()
+ const buff = decoder.write(key.toString().slice(1)).finalize()
+ return new CID(Buffer.from(buff))
+}
+
+}).call(this,require("buffer").Buffer)
+},{"../../../utils/cid":561,"async/mapLimit":88,"async/parallel":91,"base32.js":107,"buffer":181,"cids":185,"debug":456,"explain-error":274,"ipfs-mfs/src/core/utils/constants":369,"promisify-es6":1263}],522:[function(require,module,exports){
+(function (Buffer){
+/* eslint max-nested-callbacks: ["error", 8] */
+'use strict'
+
+const { DAGNode, DAGLink } = require('ipld-dag-pb')
+const CID = require('cids')
+const series = require('async/series')
+const parallel = require('async/parallel')
+const eachLimit = require('async/eachLimit')
+const waterfall = require('async/waterfall')
+const detectLimit = require('async/detectLimit')
+const queue = require('async/queue')
+const { Key } = require('interface-datastore')
+const errCode = require('err-code')
+const multicodec = require('multicodec')
+const debug = require('debug')
+const { cidToString } = require('../../../utils/cid')
+
+const createPinSet = require('./pin-set')
+
+// arbitrary limit to the number of concurrent dag operations
+const concurrencyLimit = 300
+const PIN_DS_KEY = new Key('/local/pins')
+
+function invalidPinTypeErr (type) {
+ const errMsg = `Invalid type '${type}', must be one of {direct, indirect, recursive, all}`
+ return errCode(new Error(errMsg), 'ERR_INVALID_PIN_TYPE')
+}
+
+const PinTypes = {
+ direct: 'direct',
+ recursive: 'recursive',
+ indirect: 'indirect',
+ all: 'all'
+}
+
+class PinManager {
+ constructor (repo, dag) {
+ this.repo = repo
+ this.dag = dag
+ this.log = debug('ipfs:pin')
+ this.pinset = createPinSet(dag)
+ this.directPins = new Set()
+ this.recursivePins = new Set()
+ }
+
+ _walkDag ({ cid, preload = false, onCid = () => {} }, cb) {
+ const q = queue(({ cid }, done) => {
+ this.dag.get(cid, { preload }, (err, result) => {
+ if (err) {
+ return done(err)
+ }
+
+ onCid(cid)
+
+ if (result.value.Links) {
+ q.push(result.value.Links.map(link => ({
+ cid: link.Hash
+ })))
+ }
+
+ done()
+ })
+ }, concurrencyLimit)
+ q.drain = () => {
+ cb()
+ }
+ q.error = (err) => {
+ q.kill()
+ cb(err)
+ }
+ q.push({ cid })
+ }
+
+ directKeys () {
+ return Array.from(this.directPins, key => new CID(key).buffer)
+ }
+
+ recursiveKeys () {
+ return Array.from(this.recursivePins, key => new CID(key).buffer)
+ }
+
+ getIndirectKeys ({ preload }, callback) {
+ const indirectKeys = new Set()
+ eachLimit(this.recursiveKeys(), concurrencyLimit, (multihash, cb) => {
+ this._walkDag({
+ cid: new CID(multihash),
+ preload: preload || false,
+ onCid: (cid) => {
+ cid = cid.toString()
+
+ // recursive pins pre-empt indirect pins
+ if (!this.recursivePins.has(cid)) {
+ indirectKeys.add(cid)
+ }
+ }
+ }, cb)
+ }, (err) => {
+ if (err) { return callback(err) }
+ callback(null, Array.from(indirectKeys))
+ })
+ }
+
+ // Encode and write pin key sets to the datastore:
+ // a DAGLink for each of the recursive and direct pinsets
+ // a DAGNode holding those as DAGLinks, a kind of root pin
+ flushPins (callback) {
+ let dLink, rLink, root
+ series([
+ // create a DAGLink to the node with direct pins
+ cb => waterfall([
+ cb => this.pinset.storeSet(this.directKeys(), cb),
+ ({ node, cid }, cb) => {
+ try {
+ cb(null, new DAGLink(PinTypes.direct, node.size, cid))
+ } catch (err) {
+ cb(err)
+ }
+ },
+ (link, cb) => { dLink = link; cb(null) }
+ ], cb),
+
+ // create a DAGLink to the node with recursive pins
+ cb => waterfall([
+ cb => this.pinset.storeSet(this.recursiveKeys(), cb),
+ ({ node, cid }, cb) => {
+ try {
+ cb(null, new DAGLink(PinTypes.recursive, node.size, cid))
+ } catch (err) {
+ cb(err)
+ }
+ },
+ (link, cb) => { rLink = link; cb(null) }
+ ], cb),
+
+ // the pin-set nodes link to a special 'empty' node, so make sure it exists
+ cb => {
+ let empty
+
+ try {
+ empty = DAGNode.create(Buffer.alloc(0))
+ } catch (err) {
+ return cb(err)
+ }
+
+ this.dag.put(empty, {
+ version: 0,
+ format: multicodec.DAG_PB,
+ hashAlg: multicodec.SHA2_256,
+ preload: false
+ }, cb)
+ },
+
+ // create a root node with DAGLinks to the direct and recursive DAGs
+ cb => {
+ let node
+
+ try {
+ node = DAGNode.create(Buffer.alloc(0), [dLink, rLink])
+ } catch (err) {
+ return cb(err)
+ }
+
+ root = node
+ this.dag.put(root, {
+ version: 0,
+ format: multicodec.DAG_PB,
+ hashAlg: multicodec.SHA2_256,
+ preload: false
+ }, (err, cid) => {
+ if (!err) {
+ root.multihash = cid.buffer
+ }
+ cb(err)
+ })
+ },
+
+ // save root to datastore under a consistent key
+ cb => this.repo.datastore.put(PIN_DS_KEY, root.multihash, cb)
+ ], (err, res) => {
+ if (err) { return callback(err) }
+ this.log(`Flushed pins with root: ${root}`)
+ return callback(null, root)
+ })
+ }
+
+ load (callback) {
+ waterfall([
+ (cb) => this.repo.datastore.has(PIN_DS_KEY, cb),
+ (has, cb) => has ? cb() : cb(new Error('No pins to load')),
+ (cb) => this.repo.datastore.get(PIN_DS_KEY, cb),
+ (mh, cb) => {
+ this.dag.get(new CID(mh), '', { preload: false }, cb)
+ }
+ ], (err, pinRoot) => {
+ if (err) {
+ if (err.message === 'No pins to load') {
+ this.log('No pins to load')
+ return callback()
+ } else {
+ return callback(err)
+ }
+ }
+
+ parallel([
+ cb => this.pinset.loadSet(pinRoot.value, PinTypes.recursive, cb),
+ cb => this.pinset.loadSet(pinRoot.value, PinTypes.direct, cb)
+ ], (err, keys) => {
+ if (err) { return callback(err) }
+ const [rKeys, dKeys] = keys
+
+ this.directPins = new Set(dKeys.map(k => cidToString(k)))
+ this.recursivePins = new Set(rKeys.map(k => cidToString(k)))
+
+ this.log('Loaded pins from the datastore')
+ return callback(null)
+ })
+ })
+ }
+
+ isPinnedWithType (multihash, type, callback) {
+ const key = cidToString(multihash)
+ const { recursive, direct, all } = PinTypes
+
+ // recursive
+ if ((type === recursive || type === all) && this.recursivePins.has(key)) {
+ return callback(null, {
+ key,
+ pinned: true,
+ reason: recursive
+ })
+ }
+
+ if (type === recursive) {
+ return callback(null, {
+ key,
+ pinned: false
+ })
+ }
+
+ // direct
+ if ((type === direct || type === all) && this.directPins.has(key)) {
+ return callback(null, {
+ key,
+ pinned: true,
+ reason: direct
+ })
+ }
+
+ if (type === direct) {
+ return callback(null, {
+ key,
+ pinned: false
+ })
+ }
+
+ // indirect (default)
+ // check each recursive key to see if multihash is under it
+ // arbitrary limit, enables handling 1000s of pins.
+ detectLimit(this.recursiveKeys().map(key => new CID(key)), concurrencyLimit, (cid, cb) => {
+ waterfall([
+ (done) => this.dag.get(cid, '', { preload: false }, done),
+ (result, done) => done(null, result.value),
+ (node, done) => this.pinset.hasDescendant(node, key, done)
+ ], cb)
+ }, (err, cid) => callback(err, {
+ key,
+ pinned: Boolean(cid),
+ reason: cid
+ }))
+ }
+
+ // Gets CIDs of blocks used internally by the pinner
+ getInternalBlocks (callback) {
+ this.repo.datastore.get(PIN_DS_KEY, (err, mh) => {
+ if (err) {
+ if (err.code === 'ERR_NOT_FOUND') {
+ this.log('No pinned blocks')
+ return callback(null, [])
+ }
+ return callback(new Error(`Could not get pin sets root from datastore: ${err.message}`))
+ }
+
+ const cid = new CID(mh)
+ this.dag.get(cid, '', { preload: false }, (err, obj) => {
+ if (err) {
+ return callback(new Error(`Could not get pin sets from store: ${err.message}`))
+ }
+
+ // The pinner stores an object that has two links to pin sets:
+ // 1. The directly pinned CIDs
+ // 2. The recursively pinned CIDs
+ // If large enough, these pin sets may have links to buckets to hold
+ // the pins
+ this.pinset.getInternalCids(obj.value, (err, cids) => {
+ if (err) {
+ return callback(new Error(`Could not get pinner internal cids: ${err.message}`))
+ }
+
+ callback(null, cids.concat(cid))
+ })
+ })
+ })
+ }
+
+ fetchCompleteDag (cid, options, callback) {
+ this._walkDag({
+ cid,
+ preload: options.preload
+ }, callback)
+ }
+
+ // Returns an error if the pin type is invalid
+ static checkPinType (type) {
+ if (typeof type !== 'string' || !Object.keys(PinTypes).includes(type)) {
+ return invalidPinTypeErr(type)
+ }
+ }
+}
+
+PinManager.PinTypes = PinTypes
+
+module.exports = PinManager
+
+}).call(this,require("buffer").Buffer)
+},{"../../../utils/cid":561,"./pin-set":523,"async/detectLimit":55,"async/eachLimit":57,"async/parallel":91,"async/queue":92,"async/series":95,"async/waterfall":102,"buffer":181,"cids":185,"debug":456,"err-code":268,"interface-datastore":322,"ipld-dag-pb":589,"multicodec":1151}],523:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const multihashes = require('multihashes')
+const CID = require('cids')
+const protobuf = require('protons')
+const fnv1a = require('fnv1a')
+const varint = require('varint')
+const { DAGNode, DAGLink } = require('ipld-dag-pb')
+const multicodec = require('multicodec')
+const someSeries = require('async/someSeries')
+const eachSeries = require('async/eachSeries')
+const eachOfSeries = require('async/eachOfSeries')
+
+const pbSchema = require('./pin.proto')
+
+const emptyKeyHash = 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'
+const emptyKey = multihashes.fromB58String(emptyKeyHash)
+const defaultFanout = 256
+const maxItems = 8192
+const pb = protobuf(pbSchema)
+
+function toB58String (hash) {
+ return new CID(hash).toBaseEncodedString()
+}
+
+function readHeader (rootNode) {
+ // rootNode.data should be a buffer of the format:
+ // < varint(headerLength) | header | itemData... >
+ const rootData = rootNode.Data
+ const hdrLength = varint.decode(rootData)
+ const vBytes = varint.decode.bytes
+ if (vBytes <= 0) {
+ throw new Error('Invalid Set header length')
+ }
+ if (vBytes + hdrLength > rootData.length) {
+ throw new Error('Impossibly large set header length')
+ }
+ const hdrSlice = rootData.slice(vBytes, hdrLength + vBytes)
+ const header = pb.Set.decode(hdrSlice)
+ if (header.version !== 1) {
+ throw new Error(`Unsupported Set version: ${header.version}`)
+ }
+ if (header.fanout > rootNode.Links.length) {
+ throw new Error('Impossibly large fanout')
+ }
+ return {
+ header: header,
+ data: rootData.slice(hdrLength + vBytes)
+ }
+}
+
+function hash (seed, key) {
+ const buf = Buffer.alloc(4)
+ buf.writeUInt32LE(seed, 0)
+ const data = Buffer.concat([
+ buf, Buffer.from(toB58String(key))
+ ])
+ return fnv1a(data.toString('binary'))
+}
+
+exports = module.exports = function (dag) {
+ const pinSet = {
+ // should this be part of `object` API?
+ hasDescendant: (root, childhash, callback) => {
+ const seen = {}
+
+ if (CID.isCID(childhash) || Buffer.isBuffer(childhash)) {
+ childhash = toB58String(childhash)
+ }
+
+ return searchChildren(root, callback)
+
+ function searchChildren (root, cb) {
+ someSeries(root.Links, (link, done) => {
+ const cid = link.Hash
+ const bs58Link = toB58String(cid)
+
+ if (bs58Link === childhash) {
+ return done(null, true)
+ }
+
+ if (bs58Link in seen) {
+ return done(null, false)
+ }
+
+ seen[bs58Link] = true
+
+ dag.get(cid, '', { preload: false }, (err, res) => {
+ if (err) {
+ return done(err)
+ }
+
+ searchChildren(res.value, done)
+ })
+ }, cb)
+ }
+ },
+
+ storeSet: (keys, callback) => {
+ const pins = keys.map(key => {
+ if (typeof key === 'string' || Buffer.isBuffer(key)) {
+ key = new CID(key)
+ }
+
+ return {
+ key: key,
+ data: null
+ }
+ })
+
+ pinSet.storeItems(pins, (err, rootNode) => {
+ if (err) { return callback(err) }
+
+ dag.put(rootNode, {
+ version: 0,
+ format: multicodec.DAG_PB,
+ hashAlg: multicodec.SHA2_256,
+ preload: false
+ }, (err, cid) => {
+ if (err) { return callback(err, cid) }
+ callback(null, { node: rootNode, cid })
+ })
+ })
+ },
+
+ storeItems: (items, callback) => {
+ return storePins(items, 0, callback)
+
+ function storePins (pins, depth, storePinsCb) {
+ const pbHeader = pb.Set.encode({
+ version: 1,
+ fanout: defaultFanout,
+ seed: depth
+ })
+ const headerBuf = Buffer.concat([
+ Buffer.from(varint.encode(pbHeader.length)), pbHeader
+ ])
+ const fanoutLinks = []
+ for (let i = 0; i < defaultFanout; i++) {
+ fanoutLinks.push(new DAGLink('', 1, emptyKey))
+ }
+
+ if (pins.length <= maxItems) {
+ const nodes = pins
+ .map(item => {
+ return ({
+ link: new DAGLink('', 1, item.key),
+ data: item.data || Buffer.alloc(0)
+ })
+ })
+ // sorting makes any ordering of `pins` produce the same DAGNode
+ .sort((a, b) => Buffer.compare(a.link.Hash.buffer, b.link.Hash.buffer))
+
+ const rootLinks = fanoutLinks.concat(nodes.map(item => item.link))
+ const rootData = Buffer.concat(
+ [headerBuf].concat(nodes.map(item => item.data))
+ )
+
+ let rootNode
+
+ try {
+ rootNode = DAGNode.create(rootData, rootLinks)
+ } catch (err) {
+ return storePinsCb(err)
+ }
+
+ return storePinsCb(null, rootNode)
+ } else {
+ // If the array of pins is > maxItems, we:
+ // - distribute the pins among `defaultFanout` bins
+ // - create a DAGNode for each bin
+ // - add each pin as a DAGLink to that bin
+ // - create a root DAGNode
+ // - add each bin as a DAGLink
+ // - send that root DAGNode via callback
+ // (using go-ipfs' "wasteful but simple" approach for consistency)
+ // https://github.com/ipfs/go-ipfs/blob/master/pin/set.go#L57
+
+ const bins = pins.reduce((bins, pin) => {
+ const n = hash(depth, pin.key) % defaultFanout
+ bins[n] = n in bins ? bins[n].concat([pin]) : [pin]
+ return bins
+ }, {})
+
+ eachOfSeries(bins, (bin, idx, eachCb) => {
+ storePins(
+ bin,
+ depth + 1,
+ (err, child) => storeChild(err, child, idx, eachCb)
+ )
+ }, err => {
+ if (err) { return storePinsCb(err) }
+
+ let rootNode
+
+ try {
+ rootNode = DAGNode.create(headerBuf, fanoutLinks)
+ } catch (err) {
+ return storePinsCb(err)
+ }
+
+ return storePinsCb(null, rootNode)
+ })
+ }
+
+ function storeChild (err, child, binIdx, cb) {
+ if (err) { return cb(err) }
+
+ const opts = {
+ version: 0,
+ format: multicodec.DAG_PB,
+ hashAlg: multicodec.SHA2_256,
+ preload: false
+ }
+
+ dag.put(child, opts, (err, cid) => {
+ if (err) { return cb(err) }
+ fanoutLinks[binIdx] = new DAGLink('', child.size, cid)
+ cb(null)
+ })
+ }
+ }
+ },
+
+ loadSet: (rootNode, name, callback) => {
+ const link = rootNode.Links.find(l => l.Name === name)
+ if (!link) {
+ return callback(new Error('No link found with name ' + name))
+ }
+
+ dag.get(link.Hash, '', { preload: false }, (err, res) => {
+ if (err) { return callback(err) }
+ const keys = []
+ const stepPin = link => keys.push(link.Hash.buffer)
+ pinSet.walkItems(res.value, { stepPin }, err => {
+ if (err) { return callback(err) }
+ return callback(null, keys)
+ })
+ })
+ },
+
+ walkItems: (node, { stepPin = () => {}, stepBin = () => {} }, callback) => {
+ let pbh
+ try {
+ pbh = readHeader(node)
+ } catch (err) {
+ return callback(err)
+ }
+
+ eachOfSeries(node.Links, (link, idx, eachCb) => {
+ if (idx < pbh.header.fanout) {
+ // the first pbh.header.fanout links are fanout bins
+ // if a fanout bin is not 'empty', dig into and walk its DAGLinks
+ const linkHash = link.Hash.buffer
+
+ if (!emptyKey.equals(linkHash)) {
+ stepBin(link, idx, pbh.data)
+
+ // walk the links of this fanout bin
+ return dag.get(linkHash, '', { preload: false }, (err, res) => {
+ if (err) { return eachCb(err) }
+ pinSet.walkItems(res.value, { stepPin, stepBin }, eachCb)
+ })
+ }
+ } else {
+ // otherwise, the link is a pin
+ stepPin(link, idx, pbh.data)
+ }
+
+ eachCb(null)
+ }, callback)
+ },
+
+ getInternalCids: (rootNode, callback) => {
+ // "Empty block" used by the pinner
+ const cids = [new CID(emptyKey)]
+
+ const stepBin = link => cids.push(link.Hash)
+ eachSeries(rootNode.Links, (topLevelLink, cb) => {
+ cids.push(topLevelLink.Hash)
+
+ dag.get(topLevelLink.Hash, '', { preload: false }, (err, res) => {
+ if (err) { return cb(err) }
+
+ pinSet.walkItems(res.value, { stepBin }, cb)
+ })
+ }, (err) => callback(err, cids))
+ }
+ }
+ return pinSet
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./pin.proto":524,"async/eachOfSeries":60,"async/eachSeries":61,"async/someSeries":99,"buffer":181,"cids":185,"fnv1a":277,"ipld-dag-pb":589,"multicodec":1151,"multihashes":1157,"protons":1274,"varint":1521}],524:[function(require,module,exports){
+'use strict'
+
+/**
+ * Protobuf interface
+ * from go-ipfs/pin/internal/pb/header.proto
+ */
+module.exports = `
+ syntax = "proto2";
+
+ package ipfs.pin;
+
+ option go_package = "pb";
+
+ message Set {
+ optional uint32 version = 1;
+ optional uint32 fanout = 2;
+ optional fixed32 seed = 3;
+ }
+`
+
+},{}],525:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR
+const PeerId = require('peer-id')
+const pull = require('pull-stream')
+const Pushable = require('pull-pushable')
+
+const log = debug('ipfs:pingPullStream')
+log.error = debug('ipfs:pingPullStream:error')
+
+module.exports = function pingPullStream (self) {
+ return (peerId, opts) => {
+ if (!self.isOnline()) {
+ return pull.error(new Error(OFFLINE_ERROR))
+ }
+
+ opts = Object.assign({ count: 10 }, opts)
+
+ const source = Pushable()
+
+ getPeer(self.libp2p, source, peerId, (err, peer) => {
+ if (err) {
+ log.error(err)
+ source.end(err)
+ return
+ }
+
+ runPing(self.libp2p, source, opts.count, peer, (err) => {
+ if (err) {
+ log.error(err)
+ source.push(getPacket({ success: false, text: err.toString() }))
+ source.end()
+ }
+ })
+ })
+
+ return source
+ }
+}
+
+function getPacket (msg) {
+ // Default msg
+ const basePacket = { success: true, time: 0, text: '' }
+ return Object.assign(basePacket, msg)
+}
+
+function getPeer (libp2pNode, statusStream, peerIdStr, cb) {
+ let peerId
+
+ try {
+ peerId = PeerId.createFromB58String(peerIdStr)
+ } catch (err) {
+ return cb(err)
+ }
+
+ let peerInfo
+
+ try {
+ peerInfo = libp2pNode.peerBook.get(peerId)
+ } catch (err) {
+ log('Peer not found in peer book, trying peer routing')
+
+ // Share lookup status just as in the go implemmentation
+ statusStream.push(getPacket({ text: `Looking up peer ${peerIdStr}` }))
+ return libp2pNode.peerRouting.findPeer(peerId, cb)
+ }
+
+ cb(null, peerInfo)
+}
+
+function runPing (libp2pNode, statusStream, count, peer, cb) {
+ libp2pNode.ping(peer, (err, p) => {
+ if (err) { return cb(err) }
+
+ let packetCount = 0
+ let totalTime = 0
+ statusStream.push(getPacket({ text: `PING ${peer.id.toB58String()}` }))
+
+ p.on('ping', (time) => {
+ statusStream.push(getPacket({ time }))
+ totalTime += time
+ packetCount++
+ if (packetCount >= count) {
+ const average = totalTime / count
+ p.stop()
+ statusStream.push(getPacket({ text: `Average latency: ${average}ms` }))
+ statusStream.end()
+ }
+ })
+
+ p.on('error', (err) => {
+ log.error(err)
+ p.stop()
+ cb(err)
+ })
+
+ p.start()
+ })
+}
+
+},{"../utils":560,"debug":456,"peer-id":1253,"pull-pushable":1306,"pull-stream":1311}],526:[function(require,module,exports){
+'use strict'
+
+const toStream = require('pull-stream-to-stream')
+
+module.exports = function pingReadableStream (self) {
+ return (peerId, opts) => toStream.source(self.pingPullStream(peerId, opts))
+}
+
+},{"pull-stream-to-stream":1310}],527:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const pull = require('pull-stream/pull')
+
+module.exports = function ping (self) {
+ return promisify((peerId, opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ pull(
+ self.pingPullStream(peerId, opts),
+ pull.collect(callback)
+ )
+ })
+}
+
+},{"promisify-es6":1263,"pull-stream/pull":1312}],528:[function(require,module,exports){
+'use strict'
+
+const peerId = require('peer-id')
+const PeerInfo = require('peer-info')
+const multiaddr = require('multiaddr')
+const waterfall = require('async/waterfall')
+const Keychain = require('libp2p-keychain')
+const mergeOptions = require('merge-options')
+const NoKeychain = require('./no-keychain')
+/*
+ * Load stuff from Repo into memory
+ */
+module.exports = function preStart (self) {
+ return (callback) => {
+ self.log('pre-start')
+
+ const pass = self._options.pass
+ waterfall([
+ (cb) => self._repo.config.get(cb),
+ (config, cb) => {
+ if (!self._options.config) {
+ return cb(null, config)
+ }
+
+ config = mergeOptions(config, self._options.config)
+
+ self.config.replace(config, (err) => {
+ if (err) {
+ return cb(err)
+ }
+
+ cb(null, config)
+ })
+ },
+ (config, cb) => {
+ // Create keychain configuration, if needed.
+ if (config.Keychain) {
+ return cb(null, config)
+ }
+ config.Keychain = Keychain.generateOptions()
+ self.config.set('Keychain', config.Keychain, (err) => {
+ self.log('using default keychain options')
+ cb(err, config)
+ })
+ },
+ (config, cb) => {
+ // Construct the keychain
+ if (self._keychain) {
+ // most likely an init or upgrade has happened
+ } else if (pass) {
+ const keychainOptions = Object.assign({ passPhrase: pass }, config.Keychain)
+ self._keychain = new Keychain(self._repo.keys, keychainOptions)
+ self.log('keychain constructed')
+ } else {
+ self._keychain = new NoKeychain()
+ self.log('no keychain, use --pass')
+ }
+ cb(null, config)
+ },
+ (config, cb) => {
+ const privKey = config.Identity.PrivKey
+
+ peerId.createFromPrivKey(privKey, (err, id) => {
+ cb(err, config, id)
+ })
+ },
+ (config, id, cb) => {
+ // Import the private key as 'self', if needed.
+ if (!pass) {
+ return cb(null, config, id)
+ }
+ self._keychain.findKeyByName('self', (err) => {
+ if (err) {
+ self.log('Creating "self" key')
+ return self._keychain.importPeer('self', id, (err) => cb(err, config, id))
+ }
+ cb(null, config, id)
+ })
+ },
+ (config, id, cb) => {
+ self.log('peer created')
+ self._peerInfo = new PeerInfo(id)
+
+ if (config.Addresses && config.Addresses.Swarm) {
+ config.Addresses.Swarm.forEach((addr) => {
+ let ma = multiaddr(addr)
+
+ if (ma.getPeerId()) {
+ ma = ma.encapsulate('/ipfs/' + self._peerInfo.id.toB58String())
+ }
+
+ self._peerInfo.multiaddrs.add(ma)
+ })
+ }
+
+ cb()
+ },
+ (cb) => self.pin._load(cb)
+ ], callback)
+ }
+}
+
+},{"./no-keychain":517,"async/waterfall":102,"libp2p-keychain":926,"merge-options":1127,"multiaddr":1140,"peer-id":1253,"peer-info":1254}],529:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const setImmediate = require('async/setImmediate')
+const errCode = require('err-code')
+
+const errPubsubDisabled = () => {
+ return errCode(new Error('pubsub experiment is not enabled'), 'ERR_PUBSUB_DISABLED')
+}
+
+module.exports = function pubsub (self) {
+ return {
+ subscribe: (topic, handler, options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ if (!self.libp2p.pubsub) {
+ return callback
+ ? setImmediate(() => callback(errPubsubDisabled()))
+ : Promise.reject(errPubsubDisabled())
+ }
+
+ if (!callback) {
+ return self.libp2p.pubsub.subscribe(topic, handler, options)
+ }
+
+ self.libp2p.pubsub.subscribe(topic, handler, options, callback)
+ },
+
+ unsubscribe: (topic, handler, callback) => {
+ if (!self.libp2p.pubsub) {
+ return callback
+ ? setImmediate(() => callback(errPubsubDisabled()))
+ : Promise.reject(errPubsubDisabled())
+ }
+
+ if (!callback) {
+ return self.libp2p.pubsub.unsubscribe(topic, handler)
+ }
+
+ self.libp2p.pubsub.unsubscribe(topic, handler, callback)
+ },
+
+ publish: promisify((topic, data, callback) => {
+ if (!self.libp2p.pubsub) {
+ return setImmediate(() => callback(errPubsubDisabled()))
+ }
+ self.libp2p.pubsub.publish(topic, data, callback)
+ }),
+
+ ls: promisify((callback) => {
+ if (!self.libp2p.pubsub) {
+ return setImmediate(() => callback(errPubsubDisabled()))
+ }
+ self.libp2p.pubsub.ls(callback)
+ }),
+
+ peers: promisify((topic, callback) => {
+ if (!self.libp2p.pubsub) {
+ return setImmediate(() => callback(errPubsubDisabled()))
+ }
+ self.libp2p.pubsub.peers(topic, callback)
+ }),
+
+ setMaxListeners (n) {
+ if (!self.libp2p.pubsub) {
+ throw errPubsubDisabled()
+ }
+ self.libp2p.pubsub.setMaxListeners(n)
+ }
+ }
+}
+
+},{"async/setImmediate":96,"err-code":268,"promisify-es6":1263}],530:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const repoVersion = require('ipfs-repo').repoVersion
+
+module.exports = function repo (self) {
+ return {
+ init: (bits, empty, callback) => {
+ // 1. check if repo already exists
+ },
+
+ /**
+ * If the repo has been initialized, report the current version.
+ * Otherwise report the version that would be initialized.
+ *
+ * @param {function(Error, Number)} [callback]
+ * @returns {undefined}
+ */
+ version: promisify((callback) => {
+ self._repo._isInitialized(err => {
+ if (err) {
+ // TODO: (dryajov) This is really hacky, there must be a better way
+ const match = [
+ /Key not found in database \[\/version\]/,
+ /ENOENT/,
+ /repo is not initialized yet/
+ ].some((m) => {
+ return m.test(err.message)
+ })
+ if (match) {
+ // this repo has not been initialized
+ return callback(null, repoVersion)
+ }
+ return callback(err)
+ }
+
+ self._repo.version.get(callback)
+ })
+ }),
+
+ gc: require('./pin/gc')(self),
+
+ stat: promisify((options, callback) => {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ self._repo.stat(options, (err, stats) => {
+ if (err) return callback(err)
+
+ callback(null, {
+ numObjects: stats.numObjects,
+ repoSize: stats.repoSize,
+ repoPath: stats.repoPath,
+ version: stats.version.toString(),
+ storageMax: stats.storageMax
+ })
+ })
+ }),
+
+ path: () => self._repo.path
+ }
+}
+
+},{"./pin/gc":521,"ipfs-repo":395,"promisify-es6":1263}],531:[function(require,module,exports){
+'use strict'
+
+const isIpfs = require('is-ipfs')
+const CID = require('cids')
+const nodeify = require('promise-nodeify')
+const { cidToString } = require('../../utils/cid')
+
+/**
+ * @typedef { import("../index") } IPFS
+ */
+
+/**
+ * @typedef {Object} ResolveOptions
+ * @prop {string} cidBase - Multibase codec name the CID in the resolved path will be encoded with
+ * @prop {boolean} [recursive=true] - Resolve until the result is an IPFS name
+ *
+ */
+
+/** @typedef {(err: Error, path: string) => void} ResolveCallback */
+
+/**
+ * @callback ResolveWrapper - This wrapper adds support for callbacks and promises
+ * @param {string} name - Path to resolve
+ * @param {ResolveOptions} opts - Options for resolve
+ * @param {ResolveCallback} [cb] - Optional callback function
+ * @returns {Promise | void} - When callback is provided nothing is returned
+ */
+
+/**
+ * IPFS Resolve factory
+ *
+ * @param {IPFS} ipfs
+ * @returns {ResolveWrapper}
+ */
+module.exports = (ipfs) => {
+ /**
+ * IPFS Resolve - Resolve the value of names to IPFS
+ *
+ * @param {String} name
+ * @param {ResolveOptions} [opts={}]
+ * @returns {Promise}
+ */
+ const resolve = async (name, opts = {}) => {
+ if (!isIpfs.path(name)) {
+ throw new Error('invalid argument ' + name)
+ }
+
+ if (isIpfs.ipnsPath(name)) {
+ name = await ipfs.name.resolve(name, opts)
+ }
+
+ const [, , hash, ...rest] = name.split('/') // ['', 'ipfs', 'hash', ...path]
+ const cid = new CID(hash)
+
+ // nothing to resolve return the input
+ if (rest.length === 0) {
+ return `/ipfs/${cidToString(cid, { base: opts.cidBase })}`
+ }
+
+ const path = rest.join('/')
+ const results = ipfs._ipld.resolve(cid, path)
+ let value = cid
+ let remainderPath = path
+
+ for await (const result of results) {
+ if (CID.isCID(result.value)) {
+ value = result.value
+ remainderPath = result.remainderPath
+ }
+ }
+
+ return `/ipfs/${cidToString(value, { base: opts.cidBase })}${remainderPath ? '/' + remainderPath : ''}`
+ }
+
+ return (name, opts = {}, cb) => {
+ if (typeof opts === 'function') {
+ cb = opts
+ opts = {}
+ }
+ return nodeify(resolve(name, opts), cb)
+ }
+}
+
+},{"../../utils/cid":561,"cids":185,"is-ipfs":614,"promise-nodeify":1259}],532:[function(require,module,exports){
+'use strict'
+
+const series = require('async/series')
+const Bitswap = require('ipfs-bitswap')
+const setImmediate = require('async/setImmediate')
+const promisify = require('promisify-es6')
+
+const IPNS = require('../ipns')
+const routingConfig = require('../ipns/routing/config')
+const createLibp2pBundle = require('./libp2p')
+
+module.exports = (self) => {
+ return promisify((callback) => {
+ const done = (err) => {
+ if (err) {
+ setImmediate(() => self.emit('error', err))
+ return callback(err)
+ }
+
+ self.state.started()
+ setImmediate(() => self.emit('start'))
+ callback()
+ }
+
+ if (self.state.state() !== 'stopped') {
+ return done(new Error(`Not able to start from state: ${self.state.state()}`))
+ }
+
+ self.log('starting')
+ self.state.start()
+
+ series([
+ (cb) => {
+ // The repo may be closed if previously stopped
+ self._repo.closed
+ ? self._repo.open(cb)
+ : cb()
+ },
+ (cb) => {
+ self._repo.config.get((err, config) => {
+ if (err) return cb(err)
+
+ const libp2p = createLibp2pBundle(self, config)
+
+ libp2p.start(err => {
+ if (err) return cb(err)
+ self.libp2p = libp2p
+ cb()
+ })
+ })
+ },
+ (cb) => {
+ const ipnsRouting = routingConfig(self)
+ self._ipns = new IPNS(ipnsRouting, self._repo.datastore, self._peerInfo, self._keychain, self._options)
+
+ self._bitswap = new Bitswap(
+ self.libp2p,
+ self._repo.blocks,
+ { statsEnabled: true }
+ )
+
+ self._bitswap.start()
+ self._blockService.setExchange(self._bitswap)
+
+ self._preload.start()
+ self._ipns.republisher.start()
+ self._mfsPreload.start(cb)
+ }
+ ], done)
+ })
+}
+
+},{"../ipns":539,"../ipns/routing/config":544,"./libp2p":514,"async/series":95,"async/setImmediate":96,"ipfs-bitswap":339,"promisify-es6":1263}],533:[function(require,module,exports){
+(function (process){
+'use strict'
+
+const promisify = require('promisify-es6')
+const Big = require('bignumber.js')
+const Pushable = require('pull-pushable')
+const human = require('human-to-milliseconds')
+const toStream = require('pull-stream-to-stream')
+const errCode = require('err-code')
+
+function bandwidthStats (self, opts) {
+ return new Promise((resolve, reject) => {
+ let stats
+
+ if (opts.peer) {
+ stats = self.libp2p.stats.forPeer(opts.peer)
+ } else if (opts.proto) {
+ stats = self.libp2p.stats.forProtocol(opts.proto)
+ } else {
+ stats = self.libp2p.stats.global
+ }
+
+ if (!stats) {
+ resolve({
+ totalIn: new Big(0),
+ totalOut: new Big(0),
+ rateIn: new Big(0),
+ rateOut: new Big(0)
+ })
+ return
+ }
+
+ resolve({
+ totalIn: stats.snapshot.dataReceived,
+ totalOut: stats.snapshot.dataSent,
+ rateIn: new Big(stats.movingAverages.dataReceived['60000'].movingAverage() / 60),
+ rateOut: new Big(stats.movingAverages.dataSent['60000'].movingAverage() / 60)
+ })
+ })
+}
+
+module.exports = function stats (self) {
+ const _bwPullStream = (opts) => {
+ opts = opts || {}
+ let interval = null
+ const stream = Pushable(true, () => {
+ if (interval) {
+ clearInterval(interval)
+ }
+ })
+
+ if (opts.poll) {
+ let value
+ try {
+ value = human(opts.interval || '1s')
+ } catch (err) {
+ // Pull stream expects async work, so we need to simulate it.
+ process.nextTick(() => {
+ stream.end(errCode(err, 'ERR_INVALID_POLL_INTERVAL'))
+ })
+ }
+
+ interval = setInterval(() => {
+ bandwidthStats(self, opts)
+ .then((stats) => stream.push(stats))
+ .catch((err) => {
+ if (interval) {
+ clearInterval(interval)
+ }
+ stream.end(err)
+ })
+ }, value)
+ } else {
+ bandwidthStats(self, opts)
+ .then((stats) => {
+ stream.push(stats)
+ stream.end()
+ })
+ .catch((err) => stream.end(err))
+ }
+
+ return stream.source
+ }
+
+ return {
+ bitswap: require('./bitswap')(self).stat,
+ repo: require('./repo')(self).stat,
+ bw: promisify((opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ opts = opts || {}
+
+ bandwidthStats(self, opts)
+ .then((stats) => callback(null, stats))
+ .catch((err) => callback(err))
+ }),
+ bwReadableStream: (opts) => toStream.source(_bwPullStream(opts)),
+ bwPullStream: _bwPullStream
+ }
+}
+
+}).call(this,require('_process'))
+},{"./bitswap":477,"./repo":530,"_process":1258,"bignumber.js":110,"err-code":268,"human-to-milliseconds":312,"promisify-es6":1263,"pull-pushable":1306,"pull-stream-to-stream":1310}],534:[function(require,module,exports){
+'use strict'
+
+const parallel = require('async/parallel')
+const promisify = require('promisify-es6')
+
+module.exports = (self) => {
+ return promisify((callback) => {
+ callback = callback || function noop () {}
+
+ self.log('stop')
+
+ if (self.state.state() === 'stopped') {
+ return callback(new Error('Already stopped'))
+ }
+
+ if (self.state.state() !== 'running') {
+ return callback(new Error('Not able to stop from state: ' + self.state.state()))
+ }
+
+ self.state.stop()
+ self._blockService.unsetExchange()
+ self._bitswap.stop()
+ self._preload.stop()
+
+ parallel([
+ cb => self._ipns.republisher.stop(cb),
+ cb => self._mfsPreload.stop(cb),
+ cb => {
+ const libp2p = self.libp2p
+ self.libp2p = null
+ libp2p.stop(cb)
+ }
+ ], err => {
+ self._repo.close(closeErr => {
+ if (err || closeErr) {
+ self.emit('error', err || closeErr)
+ return callback(err || closeErr)
+ }
+
+ self.state.stopped()
+ self.emit('stop')
+ callback()
+ })
+ })
+ })
+}
+
+},{"async/parallel":91,"promisify-es6":1263}],535:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+
+const OFFLINE_ERROR = require('../utils').OFFLINE_ERROR
+
+module.exports = function swarm (self) {
+ return {
+ peers: promisify((opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ opts = opts || {}
+
+ if (!self.isOnline()) {
+ return callback(new Error(OFFLINE_ERROR))
+ }
+
+ const verbose = opts.v || opts.verbose
+ // TODO: return latency and streams when verbose is set
+ // we currently don't have this information
+
+ const peers = []
+
+ Object.values(self._peerInfoBook.getAll()).forEach((peer) => {
+ const connectedAddr = peer.isConnected()
+
+ if (!connectedAddr) { return }
+
+ const tupple = {
+ addr: connectedAddr,
+ peer: peer.id
+ }
+ if (verbose) {
+ tupple.latency = 'n/a'
+ }
+
+ peers.push(tupple)
+ })
+
+ callback(null, peers)
+ }),
+
+ // all the addrs we know
+ addrs: promisify((callback) => {
+ if (!self.isOnline()) {
+ return callback(new Error(OFFLINE_ERROR))
+ }
+
+ const peers = Object.values(self._peerInfoBook.getAll())
+
+ callback(null, peers)
+ }),
+
+ localAddrs: promisify((callback) => {
+ if (!self.isOnline()) {
+ return callback(new Error(OFFLINE_ERROR))
+ }
+
+ callback(null, self.libp2p.peerInfo.multiaddrs.toArray())
+ }),
+
+ connect: promisify((maddr, callback) => {
+ if (!self.isOnline()) {
+ return callback(new Error(OFFLINE_ERROR))
+ }
+
+ self.libp2p.dial(maddr, callback)
+ }),
+
+ disconnect: promisify((maddr, callback) => {
+ if (!self.isOnline()) {
+ return callback(new Error(OFFLINE_ERROR))
+ }
+
+ self.libp2p.hangUp(maddr, callback)
+ }),
+
+ filters: promisify((callback) => callback(new Error('Not implemented')))
+ }
+}
+
+},{"../utils":560,"promisify-es6":1263}],536:[function(require,module,exports){
+'use strict'
+
+const pkg = require('../../../package.json')
+const promisify = require('promisify-es6')
+
+// TODO add the commit hash of the current ipfs version to the response.
+module.exports = function version (self) {
+ return promisify((opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ self.repo.version((err, repoVersion) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, {
+ version: pkg.version,
+ repo: repoVersion,
+ commit: ''
+ })
+ })
+ })
+}
+
+},{"../../../package.json":475,"promisify-es6":1263}],537:[function(require,module,exports){
+'use strict'
+
+const Multiaddr = require('multiaddr')
+const mafmt = require('mafmt')
+const { struct, superstruct } = require('superstruct')
+
+const { optional, union } = struct
+const s = superstruct({
+ types: {
+ multiaddr: v => {
+ if (v === null) {
+ return `multiaddr invalid, value must be a string, Buffer, or another Multiaddr got ${v}`
+ }
+
+ try {
+ Multiaddr(v)
+ } catch (err) {
+ return `multiaddr invalid, ${err.message}`
+ }
+
+ return true
+ },
+ 'multiaddr-ipfs': v => mafmt.IPFS.matches(v) ? true : 'multiaddr IPFS invalid'
+ }
+})
+
+const configSchema = s({
+ repo: optional(s('object|string')),
+ repoOwner: 'boolean?',
+ preload: s({
+ enabled: 'boolean?',
+ addresses: optional(s(['multiaddr'])),
+ interval: 'number?'
+ }, { enabled: true, interval: 30 * 1000 }),
+ init: optional(union(['boolean', s({
+ bits: 'number?',
+ emptyRepo: 'boolean?',
+ privateKey: optional(s('object|string')), // object should be a custom type for PeerId using 'kind-of'
+ pass: 'string?'
+ })])),
+ start: 'boolean?',
+ offline: 'boolean?',
+ pass: 'string?',
+ silent: 'boolean?',
+ relay: 'object?', // relay validates in libp2p
+ EXPERIMENTAL: optional(s({
+ pubsub: 'boolean?',
+ ipnsPubsub: 'boolean?',
+ sharding: 'boolean?',
+ dht: 'boolean?'
+ })),
+ connectionManager: 'object?',
+ config: optional(s({
+ API: 'object?',
+ Addresses: optional(s({
+ Delegates: optional(s(['multiaddr'])),
+ Swarm: optional(s(['multiaddr'])),
+ API: optional(union([s('multiaddr'), s(['multiaddr'])])),
+ Gateway: optional(union([s('multiaddr'), s(['multiaddr'])]))
+ })),
+ Discovery: optional(s({
+ MDNS: optional(s({
+ Enabled: 'boolean?',
+ Interval: 'number?'
+ })),
+ webRTCStar: optional(s({
+ Enabled: 'boolean?'
+ }))
+ })),
+ Bootstrap: optional(s(['multiaddr-ipfs'])),
+ Pubsub: optional(s({
+ Router: 'string?',
+ Enabled: 'boolean?'
+ })),
+ Swarm: optional(s({
+ ConnMgr: optional(s({
+ LowWater: 'number?',
+ HighWater: 'number?'
+ }))
+ }))
+ })),
+ ipld: 'object?',
+ libp2p: optional(union(['function', 'object'])) // libp2p validates this
+}, {
+ repoOwner: true
+})
+
+const validate = (opts) => {
+ const [err, options] = configSchema.validate(opts)
+
+ if (err) {
+ throw err
+ }
+
+ return options
+}
+
+module.exports = { validate }
+
+},{"mafmt":1125,"multiaddr":1140,"superstruct":1498}],538:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const BlockService = require('ipfs-block-service')
+const Ipld = require('ipld')
+const PeerId = require('peer-id')
+const PeerInfo = require('peer-info')
+const crypto = require('libp2p-crypto')
+const isIPFS = require('is-ipfs')
+const multiaddr = require('multiaddr')
+const multihash = require('multihashes')
+const PeerBook = require('peer-book')
+const multibase = require('multibase')
+const multicodec = require('multicodec')
+const multihashing = require('multihashing-async')
+const CID = require('cids')
+const debug = require('debug')
+const mergeOptions = require('merge-options')
+const EventEmitter = require('events')
+
+const config = require('./config')
+const boot = require('./boot')
+const components = require('./components')
+const GCLock = require('./components/pin/gc-lock')
+
+// replaced by repo-browser when running in the browser
+const defaultRepo = require('./runtime/repo-nodejs')
+const preload = require('./preload')
+const mfsPreload = require('./mfs-preload')
+const ipldOptions = require('./runtime/ipld-nodejs')
+
+/**
+ * @typedef { import("./ipns/index") } IPNS
+ */
+
+/**
+ *
+ *
+ * @class IPFS
+ * @extends {EventEmitter}
+ */
+class IPFS extends EventEmitter {
+ constructor (options) {
+ super()
+
+ const defaults = {
+ init: true,
+ start: true,
+ EXPERIMENTAL: {},
+ preload: {
+ enabled: true,
+ addresses: [
+ '/dnsaddr/node0.preload.ipfs.io/https',
+ '/dnsaddr/node1.preload.ipfs.io/https'
+ ]
+ }
+ }
+
+ options = config.validate(options || {})
+
+ this._options = mergeOptions(defaults, options)
+
+ if (options.init === false) {
+ this._options.init = false
+ }
+
+ if (!(options.start === false)) {
+ this._options.start = true
+ }
+
+ if (typeof options.repo === 'string' ||
+ options.repo === undefined) {
+ this._repo = defaultRepo(options.repo)
+ } else {
+ this._repo = options.repo
+ }
+
+ // IPFS utils
+ this.log = debug('ipfs')
+ this.log.err = debug('ipfs:err')
+
+ // IPFS Core Internals
+ // this._repo - assigned above
+ this._peerInfoBook = new PeerBook()
+ this._peerInfo = undefined
+ this._bitswap = undefined
+ this._blockService = new BlockService(this._repo)
+ this._ipld = new Ipld(ipldOptions(this._blockService, this._options.ipld, this.log))
+ this._preload = preload(this)
+ this._mfsPreload = mfsPreload(this)
+ /** @type {IPNS} */
+ this._ipns = undefined
+ // eslint-disable-next-line no-console
+ this._print = this._options.silent ? this.log : console.log
+ this._gcLock = new GCLock(this._options.repoOwner, {
+ // Make sure GCLock is specific to repo, for tests where there are
+ // multiple instances of IPFS
+ morticeId: this._repo.path
+ })
+
+ // IPFS Core exposed components
+ // - for booting up a node
+ this.init = components.init(this)
+ this.preStart = components.preStart(this)
+ this.start = components.start(this)
+ this.stop = components.stop(this)
+ this.shutdown = this.stop
+ this.isOnline = components.isOnline(this)
+ // - interface-ipfs-core defined API
+ Object.assign(this, components.filesRegular(this))
+ this.version = components.version(this)
+ this.id = components.id(this)
+ this.repo = components.repo(this)
+ this.bootstrap = components.bootstrap(this)
+ this.config = components.config(this)
+ this.block = components.block(this)
+ this.object = components.object(this)
+ this.dag = components.dag(this)
+ this.files = components.filesMFS(this)
+ this.libp2p = null // assigned on start
+ this.swarm = components.swarm(this)
+ this.name = components.name(this)
+ this.bitswap = components.bitswap(this)
+ this.pin = components.pin(this)
+ this.ping = components.ping(this)
+ this.pingPullStream = components.pingPullStream(this)
+ this.pingReadableStream = components.pingReadableStream(this)
+ this.pubsub = components.pubsub(this)
+ this.dht = components.dht(this)
+ this.dns = components.dns(this)
+ this.key = components.key(this)
+ this.stats = components.stats(this)
+ this.resolve = components.resolve(this)
+
+ if (this._options.EXPERIMENTAL.ipnsPubsub) {
+ this.log('EXPERIMENTAL IPNS pubsub is enabled')
+ }
+ if (this._options.EXPERIMENTAL.sharding) {
+ this.log('EXPERIMENTAL sharding is enabled')
+ }
+
+ this.state = require('./state')(this)
+
+ const onReady = () => {
+ this.removeListener('error', onError)
+ this._ready = true
+ }
+
+ const onError = err => {
+ this.removeListener('ready', onReady)
+ this._readyError = err
+ }
+
+ this.once('ready', onReady).once('error', onError)
+
+ boot(this)
+ }
+
+ get ready () {
+ return new Promise((resolve, reject) => {
+ if (this._ready) return resolve(this)
+ if (this._readyError) return reject(this._readyError)
+ this.once('ready', () => resolve(this))
+ this.once('error', reject)
+ })
+ }
+}
+
+module.exports = IPFS
+
+// Note: We need to do this to force browserify to load the Buffer module
+const BufferImpl = Buffer
+Object.assign(module.exports, { crypto, isIPFS, Buffer: BufferImpl, CID, multiaddr, multibase, multihash, multihashing, multicodec, PeerId, PeerInfo })
+
+module.exports.createNode = (options) => {
+ return new IPFS(options)
+}
+
+module.exports.create = (options) => {
+ return new IPFS(options).ready
+}
+
+}).call(this,require("buffer").Buffer)
+},{"./boot":476,"./components":510,"./components/pin/gc-lock":520,"./config":537,"./mfs-preload":548,"./preload":549,"./runtime/ipld-nodejs":554,"./runtime/repo-nodejs":558,"./state":559,"buffer":181,"cids":185,"debug":456,"events":272,"ipfs-block-service":352,"ipld":600,"is-ipfs":614,"libp2p-crypto":745,"merge-options":1127,"multiaddr":1140,"multibase":1148,"multicodec":1151,"multihashes":1157,"multihashing-async":1161,"peer-book":1252,"peer-id":1253,"peer-info":1254}],539:[function(require,module,exports){
+'use strict'
+
+const { createFromPrivKey } = require('peer-id')
+const series = require('async/series')
+
+const errcode = require('err-code')
+const debug = require('debug')
+const log = debug('ipfs:ipns')
+log.error = debug('ipfs:ipns:error')
+
+const IpnsPublisher = require('./publisher')
+const IpnsRepublisher = require('./republisher')
+const IpnsResolver = require('./resolver')
+const path = require('./path')
+const { normalizePath } = require('../utils')
+const TLRU = require('../../utils/tlru')
+const defaultRecordTtl = 60 * 1000
+
+class IPNS {
+ constructor (routing, datastore, peerInfo, keychain, options) {
+ this.publisher = new IpnsPublisher(routing, datastore)
+ this.republisher = new IpnsRepublisher(this.publisher, datastore, peerInfo, keychain, options)
+ this.resolver = new IpnsResolver(routing)
+ this.cache = new TLRU(1000)
+ this.routing = routing
+ }
+
+ // Publish
+ publish (privKey, value, lifetime = IpnsPublisher.defaultRecordLifetime, callback) {
+ try {
+ value = normalizePath(value)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ series([
+ (cb) => createFromPrivKey(privKey.bytes, cb),
+ (cb) => this.publisher.publishWithEOL(privKey, value, lifetime, cb)
+ ], (err, results) => {
+ if (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ log(`IPNS value ${value} was published correctly`)
+
+ // // Add to cache
+ const id = results[0].toB58String()
+ const ttEol = parseFloat(lifetime)
+ const ttl = (ttEol < defaultRecordTtl) ? ttEol : defaultRecordTtl
+
+ this.cache.set(id, value, ttl)
+
+ log(`IPNS value ${value} was cached correctly`)
+
+ callback(null, {
+ name: id,
+ value: value
+ })
+ })
+ }
+
+ // Resolve
+ resolve (name, options, callback) {
+ if (typeof name !== 'string') {
+ return callback(errcode(new Error('name received is not valid'), 'ERR_INVALID_NAME'))
+ }
+
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ options = options || {}
+
+ // If recursive, we should not try to get the cached value
+ if (!options.nocache && !options.recursive) {
+ // Try to get the record from cache
+ const id = name.split('/')[2]
+ const result = this.cache.get(id)
+
+ if (result) {
+ return callback(null, result)
+ }
+ }
+
+ this.resolver.resolve(name, options, (err, result) => {
+ if (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ log(`IPNS record from ${name} was resolved correctly`)
+
+ callback(null, result)
+ })
+ }
+
+ // Initialize keyspace
+ // sets the ipns record for the given key to point to an empty directory
+ initializeKeyspace (privKey, value, callback) {
+ this.publish(privKey, value, IpnsPublisher.defaultRecordLifetime, callback)
+ }
+}
+
+IPNS.path = path
+
+module.exports = IPNS
+
+},{"../../utils/tlru":563,"../utils":560,"./path":540,"./publisher":541,"./republisher":542,"./resolver":543,"async/series":95,"debug":456,"err-code":268,"peer-id":1253}],540:[function(require,module,exports){
+'use strict'
+
+const isIPFS = require('is-ipfs')
+
+const debug = require('debug')
+const log = debug('ipfs:ipns:path')
+log.error = debug('ipfs:ipns:path:error')
+
+// resolves the given path by parsing out protocol-specific entries
+// (e.g. /ipns/) and then going through the /ipfs/ entries and returning the final node
+const resolvePath = (ipfsNode, name, callback) => {
+ // ipns path
+ if (isIPFS.ipnsPath(name)) {
+ log(`resolve ipns path ${name}`)
+
+ return ipfsNode._ipns.resolve(name, callback)
+ }
+
+ // ipfs path
+ ipfsNode.dag.get(name.substring('/ipfs/'.length), (err, value) => {
+ if (err) {
+ return callback(err)
+ }
+
+ return callback(null, value)
+ })
+}
+
+module.exports = {
+ resolvePath
+}
+
+},{"debug":456,"is-ipfs":614}],541:[function(require,module,exports){
+'use strict'
+
+const PeerId = require('peer-id')
+const { Key } = require('interface-datastore')
+const series = require('async/series')
+const errcode = require('err-code')
+
+const debug = require('debug')
+const log = debug('ipfs:ipns:publisher')
+log.error = debug('ipfs:ipns:publisher:error')
+
+const ipns = require('ipns')
+
+const defaultRecordLifetime = 60 * 60 * 1000
+
+// IpnsPublisher is capable of publishing and resolving names to the IPFS routing system.
+class IpnsPublisher {
+ constructor (routing, datastore) {
+ this._routing = routing
+ this._datastore = datastore
+ }
+
+ // publish record with a eol
+ publishWithEOL (privKey, value, lifetime, callback) {
+ if (!privKey || !privKey.bytes) {
+ return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY'))
+ }
+
+ PeerId.createFromPrivKey(privKey.bytes, (err, peerId) => {
+ if (err) {
+ return callback(err)
+ }
+
+ this._updateOrCreateRecord(privKey, value, lifetime, peerId, (err, record) => {
+ if (err) {
+ return callback(err)
+ }
+
+ this._putRecordToRouting(record, peerId, callback)
+ })
+ })
+ }
+
+ // Accepts a keypair, as well as a value (ipfsPath), and publishes it out to the routing system
+ publish (privKey, value, callback) {
+ this.publishWithEOL(privKey, value, defaultRecordLifetime, callback)
+ }
+
+ _putRecordToRouting (record, peerId, callback) {
+ if (!(PeerId.isPeerId(peerId))) {
+ const errMsg = 'peerId received is not valid'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID'))
+ }
+ const publicKey = peerId._pubKey
+
+ ipns.embedPublicKey(publicKey, record, (err, embedPublicKeyRecord) => {
+ if (err) {
+ return callback(err)
+ }
+
+ let keys
+ try {
+ keys = ipns.getIdKeys(peerId.toBytes())
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ series([
+ (cb) => this._publishEntry(keys.routingKey, embedPublicKeyRecord || record, peerId, cb),
+ // Publish the public key to support old go-ipfs nodes that are looking for it in the routing
+ // We will be able to deprecate this part in the future, since the public keys will be only
+ // in IPNS record and the peerId.
+ (cb) => this._publishPublicKey(keys.routingPubKey, publicKey, peerId, cb)
+ ], (err) => {
+ if (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ callback(null, embedPublicKeyRecord || record)
+ })
+ })
+ }
+
+ _publishEntry (key, entry, peerId, callback) {
+ if (!(Key.isKey(key))) {
+ const errMsg = 'datastore key does not have a valid format'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY'))
+ }
+
+ let entryData
+ try {
+ // Marshal record
+ entryData = ipns.marshal(entry)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ // Add record to routing (buffer key)
+ this._routing.put(key.toBuffer(), entryData, (err, res) => {
+ if (err) {
+ const errMsg = `ipns record for ${key.toString('base64')} could not be stored in the routing`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING'))
+ }
+
+ log(`ipns record for ${key.toString('base64')} was stored in the routing`)
+ callback(null, res)
+ })
+ }
+
+ _publishPublicKey (key, publicKey, peerId, callback) {
+ if ((!Key.isKey(key))) {
+ const errMsg = 'datastore key does not have a valid format'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_INVALID_DATASTORE_KEY'))
+ }
+
+ if (!publicKey || !publicKey.bytes) {
+ const errMsg = 'one or more of the provided parameters are not defined'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_UNDEFINED_PARAMETER'))
+ }
+
+ // Add public key to routing (buffer key)
+ this._routing.put(key.toBuffer(), publicKey.bytes, (err, res) => {
+ if (err) {
+ const errMsg = `public key for ${key.toString('base64')} could not be stored in the routing`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_PUTTING_TO_ROUTING'))
+ }
+
+ log(`public key for ${key.toString('base64')} was stored in the routing`)
+ callback(null, res)
+ })
+ }
+
+ // Returns the record this node has published corresponding to the given peer ID.
+ // If `checkRouting` is true and we have no existing record, this method will check the routing system for any existing records.
+ _getPublished (peerId, options, callback) {
+ if (!(PeerId.isPeerId(peerId))) {
+ const errMsg = 'peerId received is not valid'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID'))
+ }
+
+ options = options || {}
+ const checkRouting = options.checkRouting !== false
+
+ this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => {
+ if (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ const errMsg = `unexpected error getting the ipns record ${peerId.id} from datastore`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_UNEXPECTED_DATASTORE_RESPONSE'))
+ }
+
+ if (!checkRouting) {
+ return callback((errcode(err)))
+ }
+
+ // Try to get from routing
+ let keys
+ try {
+ keys = ipns.getIdKeys(peerId.toBytes())
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ this._routing.get(keys.routingKey.toBuffer(), (err, res) => {
+ if (err) {
+ return callback(err)
+ }
+
+ // unmarshal data
+ this._unmarshalData(res, callback)
+ })
+ } else {
+ // unmarshal data
+ this._unmarshalData(dsVal, callback)
+ }
+ })
+ }
+
+ _unmarshalData (data, callback) {
+ let result
+ try {
+ result = ipns.unmarshal(data)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(err, 'ERR_INVALID_RECORD_DATA'))
+ }
+
+ callback(null, result)
+ }
+
+ _updateOrCreateRecord (privKey, value, validity, peerId, callback) {
+ if (!(PeerId.isPeerId(peerId))) {
+ const errMsg = 'peerId received is not valid'
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_INVALID_PEER_ID'))
+ }
+
+ const getPublishedOptions = {
+ checkRouting: true
+ }
+
+ this._getPublished(peerId, getPublishedOptions, (err, record) => {
+ if (err) {
+ if (err.code !== 'ERR_NOT_FOUND') {
+ const errMsg = `unexpected error when determining the last published IPNS record for ${peerId.id}`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_DETERMINING_PUBLISHED_RECORD'))
+ }
+ }
+
+ // Determinate the record sequence number
+ let seqNumber = 0
+ if (record && record.sequence !== undefined) {
+ seqNumber = record.value.toString() !== value ? record.sequence + 1 : record.sequence
+ }
+
+ // Create record
+ ipns.create(privKey, value, seqNumber, validity, (err, entryData) => {
+ if (err) {
+ const errMsg = `ipns record for ${value} could not be created`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_CREATING_IPNS_RECORD'))
+ }
+
+ // TODO IMPROVEMENT - set ttl (still experimental feature for go)
+
+ // Marshal record
+ const data = ipns.marshal(entryData)
+
+ // Store the new record
+ this._datastore.put(ipns.getLocalKey(peerId.id), data, (err, res) => {
+ if (err) {
+ const errMsg = `ipns record for ${value} could not be stored in the datastore`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_STORING_IN_DATASTORE'))
+ }
+
+ log(`ipns record for ${value} was stored in the datastore`)
+ callback(null, entryData)
+ })
+ })
+ })
+ }
+}
+
+IpnsPublisher.defaultRecordLifetime = defaultRecordLifetime
+exports = module.exports = IpnsPublisher
+
+},{"async/series":95,"debug":456,"err-code":268,"interface-datastore":322,"ipns":605,"peer-id":1253}],542:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const ipns = require('ipns')
+const crypto = require('libp2p-crypto')
+const PeerId = require('peer-id')
+const errcode = require('err-code')
+
+const debug = require('debug')
+const each = require('async/each')
+const waterfall = require('async/waterfall')
+const log = debug('ipfs:ipns:republisher')
+log.error = debug('ipfs:ipns:republisher:error')
+
+const minute = 60 * 1000
+const hour = 60 * minute
+
+const defaultBroadcastInterval = 4 * hour
+const defaultRecordLifetime = 24 * hour
+
+class IpnsRepublisher {
+ constructor (publisher, datastore, peerInfo, keychain, options) {
+ this._publisher = publisher
+ this._datastore = datastore
+ this._peerInfo = peerInfo
+ this._keychain = keychain
+ this._options = options
+ this._republishHandle = null
+ }
+
+ start () {
+ if (this._republishHandle) {
+ throw errcode(new Error('republisher is already running'), 'ERR_REPUBLISH_ALREADY_RUNNING')
+ }
+
+ // TODO: this handler should be isolated in another module
+ const republishHandle = {
+ _onCancel: null,
+ _timeoutId: null,
+ runPeriodically: (fn, period) => {
+ republishHandle._timeoutId = setTimeout(() => {
+ republishHandle._timeoutId = null
+
+ fn((nextPeriod) => {
+ // Was republish cancelled while fn was being called?
+ if (republishHandle._onCancel) {
+ return republishHandle._onCancel()
+ }
+ // Schedule next
+ republishHandle.runPeriodically(fn, nextPeriod || period)
+ })
+ }, period)
+ },
+ cancel: (cb) => {
+ // Not currently running a republish, can callback immediately
+ if (republishHandle._timeoutId) {
+ clearTimeout(republishHandle._timeoutId)
+ return cb()
+ }
+ // Wait for republish to finish then call callback
+ republishHandle._onCancel = cb
+ }
+ }
+
+ const { privKey } = this._peerInfo.id
+ const { pass } = this._options
+
+ republishHandle.runPeriodically((done) => {
+ this._republishEntries(privKey, pass, () => done(defaultBroadcastInterval))
+ }, minute)
+
+ this._republishHandle = republishHandle
+ }
+
+ stop (callback) {
+ const republishHandle = this._republishHandle
+
+ if (!republishHandle) {
+ return callback(errcode(new Error('republisher is not running'), 'ERR_REPUBLISH_NOT_RUNNING'))
+ }
+
+ this._republishHandle = null
+ republishHandle.cancel(callback)
+ }
+
+ _republishEntries (privateKey, pass, callback) {
+ // TODO: Should use list of published entries.
+ // We can't currently *do* that because go uses this method for now.
+ this._republishEntry(privateKey, (err) => {
+ if (err) {
+ const errMsg = 'cannot republish entry for the node\'s private key'
+
+ log.error(errMsg)
+ return
+ }
+
+ // keychain needs pass to get the cryptographic keys
+ if (pass) {
+ this._keychain.listKeys((err, list) => {
+ if (err) {
+ log.error(err)
+ return
+ }
+
+ each(list, (key, cb) => {
+ waterfall([
+ (cb) => this._keychain.exportKey(key.name, pass, cb),
+ (pem, cb) => crypto.keys.import(pem, pass, cb)
+ ], (err, privKey) => {
+ if (err) {
+ log.error(err)
+ return
+ }
+
+ this._republishEntry(privKey, cb)
+ })
+ }, (err) => {
+ if (err) {
+ log.error(err)
+ }
+ callback(null)
+ })
+ })
+ } else {
+ callback(null)
+ }
+ })
+ }
+
+ _republishEntry (privateKey, callback) {
+ if (!privateKey || !privateKey.bytes) {
+ return callback(errcode(new Error('invalid private key'), 'ERR_INVALID_PRIVATE_KEY'))
+ }
+
+ waterfall([
+ (cb) => PeerId.createFromPrivKey(privateKey.bytes, cb),
+ (peerId, cb) => this._getPreviousValue(peerId, cb)
+ ], (err, value) => {
+ if (err) {
+ return callback(err.code === 'ERR_NO_ENTRY_FOUND' ? null : err)
+ }
+
+ this._publisher.publishWithEOL(privateKey, value, defaultRecordLifetime, callback)
+ })
+ }
+
+ _getPreviousValue (peerId, callback) {
+ if (!(PeerId.isPeerId(peerId))) {
+ return callback(errcode(new Error('invalid peer ID'), 'ERR_INVALID_PEER_ID'))
+ }
+
+ this._datastore.get(ipns.getLocalKey(peerId.id), (err, dsVal) => {
+ // error handling
+ // no need to republish
+ if (err && err.notFound) {
+ return callback(errcode(new Error(`no previous entry for record with id: ${peerId.id}`), 'ERR_NO_ENTRY_FOUND'))
+ } else if (err) {
+ return callback(err)
+ }
+
+ if (!Buffer.isBuffer(dsVal)) {
+ return callback(errcode(new Error("found ipns record that we couldn't process"), 'ERR_INVALID_IPNS_RECORD'))
+ }
+
+ // unmarshal data
+ let record
+ try {
+ record = ipns.unmarshal(dsVal)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_IPNS_RECORD'))
+ }
+
+ callback(null, record.value)
+ })
+ }
+}
+
+exports = module.exports = IpnsRepublisher
+
+}).call(this,{"isBuffer":require("../../../../is-buffer/index.js")})
+},{"../../../../is-buffer/index.js":608,"async/each":56,"async/waterfall":102,"debug":456,"err-code":268,"ipns":605,"libp2p-crypto":745,"peer-id":1253}],543:[function(require,module,exports){
+'use strict'
+
+const ipns = require('ipns')
+const crypto = require('libp2p-crypto')
+const PeerId = require('peer-id')
+const errcode = require('err-code')
+
+const debug = require('debug')
+const log = debug('ipfs:ipns:resolver')
+log.error = debug('ipfs:ipns:resolver:error')
+
+const defaultMaximumRecursiveDepth = 32
+
+class IpnsResolver {
+ constructor (routing) {
+ this._routing = routing
+ }
+
+ resolve (name, options, callback) {
+ if (typeof options === 'function') {
+ callback = options
+ options = {}
+ }
+
+ if (typeof name !== 'string') {
+ return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME'))
+ }
+
+ options = options || {}
+ const recursive = options.recursive && options.recursive.toString() === 'true'
+
+ const nameSegments = name.split('/')
+
+ if (nameSegments.length !== 3 || nameSegments[0] !== '') {
+ return callback(errcode(new Error('invalid name'), 'ERR_INVALID_NAME'))
+ }
+
+ const key = nameSegments[2]
+
+ // Define a maximum depth if recursive option enabled
+ let depth
+
+ if (recursive) {
+ depth = defaultMaximumRecursiveDepth
+ }
+
+ this.resolver(key, depth, (err, res) => {
+ if (err) {
+ return callback(err)
+ }
+
+ log(`${name} was locally resolved correctly`)
+ callback(null, res)
+ })
+ }
+
+ // Recursive resolver according to the specified depth
+ resolver (name, depth, callback) {
+ // Exceeded recursive maximum depth
+ if (depth === 0) {
+ const errMsg = `could not resolve name (recursion limit of ${defaultMaximumRecursiveDepth} exceeded)`
+
+ log.error(errMsg)
+ return callback(errcode(new Error(errMsg), 'ERR_RESOLVE_RECURSION_LIMIT'))
+ }
+
+ this._resolveName(name, (err, res) => {
+ if (err) {
+ return callback(err)
+ }
+
+ const nameSegments = res.split('/')
+
+ // If obtained a ipfs cid or recursive option is disabled
+ if (nameSegments[1] === 'ipfs' || !depth) {
+ return callback(null, res)
+ }
+
+ // continue recursively until depth equals 0
+ this.resolver(nameSegments[2], depth - 1, callback)
+ })
+ }
+
+ // resolve ipns entries from the provided routing
+ _resolveName (name, callback) {
+ let peerId
+
+ try {
+ peerId = PeerId.createFromB58String(name)
+ } catch (err) {
+ return callback(err)
+ }
+
+ const { routingKey, routingPubKey } = ipns.getIdKeys(peerId.toBytes())
+
+ this._routing.get(routingKey.toBuffer(), (err, record) => {
+ if (err) {
+ log.error(err)
+ if (err.code !== 'ERR_NOT_FOUND') {
+ return callback(errcode(new Error(`unexpected error getting the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_RECORD'))
+ }
+ return callback(errcode(new Error(`record requested was not found for ${name} (${routingKey}) in the network`), 'ERR_NO_RECORD_FOUND'))
+ }
+
+ // IPNS entry
+ let ipnsEntry
+ try {
+ ipnsEntry = ipns.unmarshal(record)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(new Error('found ipns record that we couldn\'t convert to a value'), 'ERR_INVALID_RECORD_RECEIVED'))
+ }
+
+ // if the record has a public key validate it
+ if (ipnsEntry.pubKey) {
+ return this._validateRecord(peerId, ipnsEntry, callback)
+ }
+
+ // Otherwise, try to get the public key from routing
+ this._routing.get(routingKey.toBuffer(), (err, pubKey) => {
+ if (err) {
+ log.error(err)
+ if (err.code !== 'ERR_NOT_FOUND') {
+ return callback(errcode(new Error(`unexpected error getting the public key for the ipns record ${peerId.id}`), 'ERR_UNEXPECTED_ERROR_GETTING_PUB_KEY'))
+ }
+ return callback(errcode(new Error(`public key requested was not found for ${name} (${routingPubKey}) in the network`), 'ERR_NO_RECORD_FOUND'))
+ }
+
+ try {
+ // Insert it into the peer id, in order to be validated by IPNS validator
+ peerId.pubKey = crypto.keys.unmarshalPublicKey(pubKey)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(new Error('found public key record that we couldn\'t convert to a value'), 'ERR_INVALID_PUB_KEY_RECEIVED'))
+ }
+
+ this._validateRecord(peerId, ipnsEntry, callback)
+ })
+ })
+ }
+
+ // validate a resolved record
+ _validateRecord (peerId, ipnsEntry, callback) {
+ ipns.extractPublicKey(peerId, ipnsEntry, (err, pubKey) => {
+ if (err) {
+ return callback(err)
+ }
+
+ // IPNS entry validation
+ ipns.validate(pubKey, ipnsEntry, (err) => {
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, ipnsEntry.value.toString())
+ })
+ })
+ }
+}
+
+exports = module.exports = IpnsResolver
+
+},{"debug":456,"err-code":268,"ipns":605,"libp2p-crypto":745,"peer-id":1253}],544:[function(require,module,exports){
+'use strict'
+
+const { TieredDatastore } = require('datastore-core')
+const get = require('dlv')
+
+const PubsubDatastore = require('./pubsub-datastore')
+const OfflineDatastore = require('./offline-datastore')
+
+module.exports = (ipfs) => {
+ // Setup online routing for IPNS with a tiered routing composed by a DHT and a Pubsub router (if properly enabled)
+ const ipnsStores = []
+
+ // Add IPNS pubsub if enabled
+ let pubsubDs
+ if (get(ipfs._options, 'EXPERIMENTAL.ipnsPubsub', false)) {
+ const pubsub = ipfs.libp2p.pubsub
+ const localDatastore = ipfs._repo.datastore
+ const peerId = ipfs._peerInfo.id
+
+ pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId)
+ ipnsStores.push(pubsubDs)
+ }
+
+ // DHT should not be added as routing if we are offline or it is disabled
+ if (get(ipfs._options, 'offline') || !get(ipfs._options, 'libp2p.config.dht.enabled', false)) {
+ const offlineDatastore = new OfflineDatastore(ipfs._repo)
+ ipnsStores.push(offlineDatastore)
+ } else {
+ ipnsStores.push(ipfs.libp2p.dht)
+ }
+
+ // Create ipns routing with a set of datastores
+ return new TieredDatastore(ipnsStores)
+}
+
+},{"./offline-datastore":545,"./pubsub-datastore":546,"datastore-core":199,"dlv":233}],545:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const { Key } = require('interface-datastore')
+const { Record } = require('libp2p-record')
+const { encodeBase32 } = require('./utils')
+
+const errcode = require('err-code')
+const debug = require('debug')
+const log = debug('ipfs:ipns:offline-datastore')
+log.error = debug('ipfs:ipns:offline-datastore:error')
+
+// Offline datastore aims to mimic the same encoding as routing when storing records
+// to the local datastore
+class OfflineDatastore {
+ constructor (repo) {
+ this._repo = repo
+ }
+
+ /**
+ * Put a value to the local datastore indexed by the received key properly encoded.
+ * @param {Buffer} key identifier of the value.
+ * @param {Buffer} value value to be stored.
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ put (key, value, callback) {
+ if (!Buffer.isBuffer(key)) {
+ return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY'))
+ }
+
+ if (!Buffer.isBuffer(value)) {
+ return callback(errcode(new Error('Offline datastore value must be a buffer'), 'ERR_INVALID_VALUE'))
+ }
+
+ let routingKey
+
+ try {
+ routingKey = this._routingKey(key)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY'))
+ }
+
+ // Marshal to libp2p record as the DHT does
+ const record = new Record(key, value)
+
+ this._repo.datastore.put(routingKey, record.serialize(), callback)
+ }
+
+ /**
+ * Get a value from the local datastore indexed by the received key properly encoded.
+ * @param {Buffer} key identifier of the value to be obtained.
+ * @param {function(Error, Buffer)} callback
+ * @returns {void}
+ */
+ get (key, callback) {
+ if (!Buffer.isBuffer(key)) {
+ return callback(errcode(new Error('Offline datastore key must be a buffer'), 'ERR_INVALID_KEY'))
+ }
+
+ let routingKey
+
+ try {
+ routingKey = this._routingKey(key)
+ } catch (err) {
+ log.error(err)
+ return callback(errcode(new Error('Not possible to generate the routing key'), 'ERR_GENERATING_ROUTING_KEY'))
+ }
+
+ this._repo.datastore.get(routingKey, (err, res) => {
+ if (err) {
+ return callback(err)
+ }
+
+ // Unmarshal libp2p record as the DHT does
+ let record
+ try {
+ record = Record.deserialize(res)
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ callback(null, record.value)
+ })
+ }
+
+ // encode key properly - base32(/ipns/{cid})
+ _routingKey (key) {
+ return new Key('/' + encodeBase32(key), false)
+ }
+}
+
+exports = module.exports = OfflineDatastore
+
+}).call(this,{"isBuffer":require("../../../../../is-buffer/index.js")})
+},{"../../../../../is-buffer/index.js":608,"./utils":547,"debug":456,"err-code":268,"interface-datastore":322,"libp2p-record":945}],546:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const ipns = require('ipns')
+const { fromB58String, toB58String } = require('multihashes')
+const PubsubDatastore = require('datastore-pubsub')
+
+const withIs = require('class-is')
+
+const errcode = require('err-code')
+const debug = require('debug')
+const log = debug('ipfs:ipns:pubsub')
+log.error = debug('ipfs:ipns:pubsub:error')
+
+// Pubsub datastore aims to manage the pubsub subscriptions for IPNS
+class IpnsPubsubDatastore {
+ constructor (pubsub, localDatastore, peerId) {
+ this._pubsub = pubsub
+ this._subscriptions = {}
+
+ // Bind _handleSubscriptionKey function, which is called by PubsubDatastore.
+ this._handleSubscriptionKey = this._handleSubscriptionKey.bind(this)
+ this._pubsubDs = new PubsubDatastore(pubsub, localDatastore, peerId, ipns.validator, this._handleSubscriptionKey)
+ }
+
+ /**
+ * Put a value to the pubsub datastore indexed by the received key properly encoded.
+ * @param {Buffer} key identifier of the value.
+ * @param {Buffer} value value to be stored.
+ * @param {function(Error)} callback
+ * @returns {void}
+ */
+ put (key, value, callback) {
+ this._pubsubDs.put(key, value, callback)
+ }
+
+ /**
+ * Get a value from the pubsub datastore indexed by the received key properly encoded.
+ * Moreover, the identifier topic is subscribed and the pubsub datastore records will be
+ * updated once new publishes occur.
+ * @param {Buffer} key identifier of the value to be obtained.
+ * @param {function(Error, Buffer)} callback
+ * @returns {void}
+ */
+ get (key, callback) {
+ this._pubsubDs.get(key, (err, res) => {
+ // Add topic subscribed
+ const ns = key.slice(0, ipns.namespaceLength)
+
+ if (ns.toString() === ipns.namespace) {
+ const stringifiedTopic = key.toString()
+ const id = toB58String(key.slice(ipns.namespaceLength))
+
+ this._subscriptions[stringifiedTopic] = id
+
+ log(`subscribed pubsub ${stringifiedTopic}: ${id}`)
+ }
+
+ // If no data was obtained, after storing the subscription, return the error.
+ if (err) {
+ return callback(err)
+ }
+
+ callback(null, res)
+ })
+ }
+
+ // Modify subscription key to have a proper encoding
+ _handleSubscriptionKey (key, callback) {
+ const subscriber = this._subscriptions[key]
+
+ if (!subscriber) {
+ return callback(errcode(new Error(`key ${key} does not correspond to a subscription`), 'ERR_INVALID_KEY'))
+ }
+
+ let keys
+ try {
+ keys = ipns.getIdKeys(fromB58String(subscriber))
+ } catch (err) {
+ log.error(err)
+ return callback(err)
+ }
+
+ callback(null, keys.routingKey.toBuffer())
+ }
+
+ /**
+ * Get pubsub subscriptions related to ipns.
+ * @param {function(Error, Object)} callback
+ * @returns {void}
+ */
+ getSubscriptions (callback) {
+ const subscriptions = Object.values(this._subscriptions).filter(Boolean)
+
+ return callback(null, subscriptions.map((sub) => `${ipns.namespace}${sub}`))
+ }
+
+ /**
+ * Cancel pubsub subscriptions related to ipns.
+ * @param {String} name ipns path to cancel the pubsub subscription.
+ * @param {function(Error, Object)} callback
+ * @returns {void}
+ */
+ cancel (name, callback) {
+ if (typeof name !== 'string') {
+ return callback(errcode(new Error('invalid subscription name'), 'ERR_INVALID_SUBSCRIPTION_NAME'))
+ }
+
+ // Trim /ipns/ prefix from the name
+ if (name.startsWith(ipns.namespace)) {
+ name = name.substring(ipns.namespaceLength)
+ }
+
+ const stringifiedTopic = Object.keys(this._subscriptions).find((key) => this._subscriptions[key] === name)
+
+ // Not found topic
+ if (!stringifiedTopic) {
+ return callback(null, {
+ canceled: false
+ })
+ }
+
+ // Unsubscribe topic
+ try {
+ const bufTopic = Buffer.from(stringifiedTopic)
+
+ this._pubsubDs.unsubscribe(bufTopic)
+ } catch (err) {
+ return callback(err)
+ }
+
+ this._subscriptions[stringifiedTopic] = undefined
+ log(`unsubscribed pubsub ${stringifiedTopic}: ${name}`)
+
+ callback(null, {
+ canceled: true
+ })
+ }
+}
+
+exports = module.exports = withIs(IpnsPubsubDatastore, { className: 'IpnsPubsubDatastore', symbolName: '@js-ipfs/ipns/IpnsPubsubDatastore' })
+
+}).call(this,require("buffer").Buffer)
+},{"buffer":181,"class-is":187,"datastore-pubsub":211,"debug":456,"err-code":268,"ipns":605,"multihashes":1157}],547:[function(require,module,exports){
+'use strict'
+
+const multibase = require('multibase')
+const ipns = require('ipns')
+
+module.exports = {
+ encodeBase32: (buf) => {
+ const m = multibase.encode('base32', buf).slice(1) // slice off multibase codec
+
+ return m.toString().toUpperCase() // should be uppercase for interop with go
+ },
+ validator: {
+ func: (key, record, cb) => ipns.validator.validate(record, key, cb)
+ },
+ selector: (k, records) => ipns.validator.select(records[0], records[1])
+}
+
+},{"ipns":605,"multibase":1148}],548:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const setImmediate = require('async/setImmediate')
+const log = debug('ipfs:mfs-preload')
+log.error = debug('ipfs:mfs-preload:error')
+
+module.exports = (self) => {
+ const options = self._options.preload || {}
+ options.interval = options.interval || 30 * 1000
+
+ if (!options.enabled) {
+ log('MFS preload disabled')
+ return {
+ start: (cb) => setImmediate(cb),
+ stop: (cb) => setImmediate(cb)
+ }
+ }
+
+ let rootCid
+ let timeoutId
+
+ const preloadMfs = () => {
+ self.files.stat('/', (err, stats) => {
+ if (err) {
+ timeoutId = setTimeout(preloadMfs, options.interval)
+ return log.error('failed to stat MFS root for preload', err)
+ }
+
+ if (rootCid !== stats.hash) {
+ log(`preloading updated MFS root ${rootCid} -> ${stats.hash}`)
+
+ return self._preload(stats.hash, (err) => {
+ timeoutId = setTimeout(preloadMfs, options.interval)
+ if (err) return log.error(`failed to preload MFS root ${stats.hash}`, err)
+ rootCid = stats.hash
+ })
+ }
+
+ timeoutId = setTimeout(preloadMfs, options.interval)
+ })
+ }
+
+ return {
+ start (cb) {
+ self.files.stat('/', (err, stats) => {
+ if (err) return cb(err)
+ rootCid = stats.hash
+ log(`monitoring MFS root ${rootCid}`)
+ timeoutId = setTimeout(preloadMfs, options.interval)
+ cb()
+ })
+ },
+ stop (cb) {
+ clearTimeout(timeoutId)
+ cb()
+ }
+ }
+}
+
+},{"async/setImmediate":96,"debug":456}],549:[function(require,module,exports){
+'use strict'
+
+const setImmediate = require('async/setImmediate')
+const retry = require('async/retry')
+const toUri = require('multiaddr-to-uri')
+const debug = require('debug')
+const CID = require('cids')
+const shuffle = require('array-shuffle')
+const preload = require('./runtime/preload-nodejs')
+
+const log = debug('ipfs:preload')
+log.error = debug('ipfs:preload:error')
+
+const noop = (err) => { if (err) log.error(err) }
+
+module.exports = self => {
+ const options = self._options.preload || {}
+ options.enabled = Boolean(options.enabled)
+ options.addresses = options.addresses || []
+
+ if (!options.enabled || !options.addresses.length) {
+ log('preload disabled')
+ const api = (_, callback) => {
+ if (callback) {
+ setImmediate(() => callback())
+ }
+ }
+ api.start = () => {}
+ api.stop = () => {}
+ return api
+ }
+
+ let stopped = true
+ let requests = []
+ const apiUris = options.addresses.map(toUri)
+
+ const api = (path, callback) => {
+ callback = callback || noop
+
+ if (typeof path !== 'string') {
+ try {
+ path = new CID(path).toBaseEncodedString()
+ } catch (err) {
+ return setImmediate(() => callback(err))
+ }
+ }
+
+ const fallbackApiUris = shuffle(apiUris)
+ let request
+ const now = Date.now()
+
+ retry({ times: fallbackApiUris.length }, (cb) => {
+ if (stopped) return cb(new Error(`preload aborted for ${path}`))
+
+ // Remove failed request from a previous attempt
+ requests = requests.filter(r => r !== request)
+
+ const apiUri = fallbackApiUris.shift()
+
+ request = preload(`${apiUri}/api/v0/refs?r=true&arg=${encodeURIComponent(path)}`, cb)
+ requests = requests.concat(request)
+ }, (err) => {
+ requests = requests.filter(r => r !== request)
+
+ if (err) {
+ return callback(err)
+ }
+
+ log(`preloaded ${path} in ${Date.now() - now}ms`)
+ callback()
+ })
+ }
+
+ api.start = () => {
+ stopped = false
+ }
+
+ api.stop = () => {
+ stopped = true
+ log(`canceling ${requests.length} pending preload request(s)`)
+ requests.forEach(r => r.cancel())
+ requests = []
+ }
+
+ return api
+}
+
+},{"./runtime/preload-nodejs":557,"array-shuffle":9,"async/retry":94,"async/setImmediate":96,"cids":185,"debug":456,"multiaddr-to-uri":1137}],550:[function(require,module,exports){
+'use strict'
+
+const callbackify = require('callbackify')
+
+module.exports = () => {
+ return callbackify(() => {
+ throw new Error('not available in the browser')
+ })
+}
+
+},{"callbackify":183}],551:[function(require,module,exports){
+'use strict'
+
+module.exports = () => ({
+ Addresses: {
+ Swarm: [
+ ],
+ API: '',
+ Gateway: '',
+ Delegates: []
+ },
+ Discovery: {
+ MDNS: {
+ Enabled: false,
+ Interval: 10
+ },
+ webRTCStar: {
+ Enabled: true
+ }
+ },
+ Bootstrap: [
+ '/dns4/ams-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLer265NRgSp2LA3dPaeykiS1J6DifTC88f5uVQKNAd',
+ '/dns4/lon-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLMeWqB7YGVLJN3pNLQpmmEk35v6wYtsMGLzSr5QBU3',
+ '/dns4/sfo-3.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLPppuBtQSGwKDZT2M73ULpjvfd3aZ6ha4oFGL1KrGM',
+ '/dns4/sgp-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLSafTMBsPKadTEgaXctDQVcqN88CNLHXMkTNwMKPnu',
+ '/dns4/nyc-1.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLueR4xBeUbY9WZ9xGUUxunbKWcrNFTDAadQJmocnWm',
+ '/dns4/nyc-2.bootstrap.libp2p.io/tcp/443/wss/ipfs/QmSoLV4Bbm51jM9C4gDYZQ9Cy3U6aXMJDAbzgu2fzaDs64',
+ '/dns4/node0.preload.ipfs.io/tcp/443/wss/ipfs/QmZMxNdpMkewiVZLMRxaNxUeZpDUb34pWjZ1kZvsd16Zic',
+ '/dns4/node1.preload.ipfs.io/tcp/443/wss/ipfs/Qmbut9Ywz9YEDrz8ySBSgWyJk41Uvm2QJPhwDJzJyGFsD6'
+ ],
+ Pubsub: {
+ Enabled: true
+ },
+ Swarm: {
+ ConnMgr: {
+ LowWater: 200,
+ HighWater: 500
+ }
+ }
+})
+
+},{}],552:[function(require,module,exports){
+/* global self */
+'use strict'
+
+module.exports = (domain, opts, callback) => {
+ if (typeof opts === 'function') {
+ callback = opts
+ opts = {}
+ }
+
+ opts = opts || {}
+
+ domain = encodeURIComponent(domain)
+ let url = `https://ipfs.io/api/v0/dns?arg=${domain}`
+
+ Object.keys(opts).forEach(prop => {
+ url += `&${encodeURIComponent(prop)}=${encodeURIComponent(opts[prop])}`
+ })
+
+ self.fetch(url, { mode: 'cors' })
+ .then((response) => {
+ return response.json()
+ })
+ .then((response) => {
+ if (response.Path) {
+ return callback(null, response.Path)
+ } else {
+ return callback(new Error(response.Message))
+ }
+ })
+ .catch((error) => {
+ callback(error)
+ })
+}
+
+},{}],553:[function(require,module,exports){
+/* eslint-env browser */
+'use strict'
+module.exports = fetch
+
+},{}],554:[function(require,module,exports){
+'use strict'
+const mergeOptions = require('merge-options')
+const ipldDagCbor = require('ipld-dag-cbor')
+const ipldDagPb = require('ipld-dag-pb')
+const ipldRaw = require('ipld-raw')
+
+module.exports = (blockService, options = {}) => {
+ return mergeOptions.call(
+ // ensure we have the defaults formats even if the user overrides `formats: []`
+ { concatArrays: true },
+ {
+ blockService: blockService,
+ formats: [ipldDagCbor, ipldDagPb, ipldRaw]
+ }, options)
+}
+
+},{"ipld-dag-cbor":570,"ipld-dag-pb":589,"ipld-raw":599,"merge-options":1127}],555:[function(require,module,exports){
+'use strict'
+
+const WS = require('libp2p-websockets')
+const WebRTCStar = require('libp2p-webrtc-star')
+const WebSocketStarMulti = require('libp2p-websocket-star-multi')
+const Multiplex = require('pull-mplex')
+const SECIO = require('libp2p-secio')
+const Bootstrap = require('libp2p-bootstrap')
+const KadDHT = require('libp2p-kad-dht')
+const GossipSub = require('libp2p-gossipsub')
+const libp2p = require('libp2p')
+const mergeOptions = require('merge-options')
+const multiaddr = require('multiaddr')
+
+class Node extends libp2p {
+ constructor (_options) {
+ const wrtcstar = new WebRTCStar({ id: _options.peerInfo.id })
+
+ // this can be replaced once optional listening is supported with the below code. ref: https://github.com/libp2p/interface-transport/issues/41
+ // const wsstar = new WebSocketStar({ id: _options.peerInfo.id })
+ const wsstarServers = _options.peerInfo.multiaddrs.toArray().map(String).filter(addr => addr.includes('p2p-websocket-star'))
+ _options.peerInfo.multiaddrs.replace(wsstarServers.map(multiaddr), '/p2p-websocket-star') // the ws-star-multi module will replace this with the chosen ws-star servers
+ const wsstar = new WebSocketStarMulti({ servers: wsstarServers, id: _options.peerInfo.id, ignore_no_online: !wsstarServers.length || _options.wsStarIgnoreErrors })
+
+ const defaults = {
+ switch: {
+ denyTTL: 2 * 60 * 1e3, // 2 minute base
+ denyAttempts: 5, // back off 5 times
+ maxParallelDials: 100,
+ maxColdCalls: 25,
+ dialTimeout: 20e3
+ },
+ modules: {
+ transport: [
+ WS,
+ wrtcstar,
+ wsstar
+ ],
+ streamMuxer: [
+ Multiplex
+ ],
+ connEncryption: [
+ SECIO
+ ],
+ peerDiscovery: [
+ wrtcstar.discovery,
+ wsstar.discovery,
+ Bootstrap
+ ],
+ dht: KadDHT,
+ pubsub: GossipSub
+ },
+ config: {
+ peerDiscovery: {
+ autoDial: true,
+ bootstrap: {
+ enabled: true
+ },
+ webRTCStar: {
+ enabled: true
+ },
+ websocketStar: {
+ enabled: true
+ }
+ },
+ dht: {
+ enabled: false
+ },
+ pubsub: {
+ enabled: true,
+ emitSelf: true
+ }
+ }
+ }
+
+ super(mergeOptions(defaults, _options))
+ }
+}
+
+module.exports = Node
+
+},{"libp2p":1012,"libp2p-bootstrap":718,"libp2p-gossipsub":852,"libp2p-kad-dht":869,"libp2p-secio":969,"libp2p-webrtc-star":974,"libp2p-websocket-star-multi":978,"libp2p-websockets":987,"merge-options":1127,"multiaddr":1140,"pull-mplex":1301}],556:[function(require,module,exports){
+'use strict'
+
+module.exports = {
+ gossipsub: require('libp2p-gossipsub')
+}
+
+},{"libp2p-gossipsub":852}],557:[function(require,module,exports){
+/* eslint-env browser */
+'use strict'
+
+const debug = require('debug')
+
+const log = debug('ipfs:preload')
+log.error = debug('ipfs:preload:error')
+
+module.exports = function preload (url, callback) {
+ log(url)
+
+ const controller = new AbortController()
+ const signal = controller.signal
+
+ fetch(url, { signal })
+ .then(res => {
+ if (!res.ok) {
+ log.error('failed to preload', url, res.status, res.statusText)
+ throw new Error(`failed to preload ${url}`)
+ }
+ return res.text()
+ })
+ .then(() => callback())
+ .catch(callback)
+
+ return {
+ cancel: () => controller.abort()
+ }
+}
+
+},{"debug":456}],558:[function(require,module,exports){
+'use strict'
+
+const IPFSRepo = require('ipfs-repo')
+
+module.exports = (dir) => {
+ const repoPath = dir || 'ipfs'
+ return new IPFSRepo(repoPath)
+}
+
+},{"ipfs-repo":395}],559:[function(require,module,exports){
+'use strict'
+
+const debug = require('debug')
+const log = debug('ipfs:state')
+log.error = debug('ipfs:state:error')
+
+const fsm = require('fsm-event')
+
+module.exports = (self) => {
+ const s = fsm('uninitialized', {
+ uninitialized: {
+ init: 'initializing',
+ initialized: 'stopped'
+ },
+ initializing: {
+ initialized: 'stopped'
+ },
+ stopped: {
+ start: 'starting'
+ },
+ starting: {
+ started: 'running'
+ },
+ running: {
+ stop: 'stopping'
+ },
+ stopping: {
+ stopped: 'stopped'
+ }
+ })
+
+ // log events
+ s.on('error', (err) => log.error(err))
+ s.on('done', () => log('-> ' + s._state))
+
+ // -- Actions
+
+ s.init = () => {
+ s('init')
+ }
+
+ s.initialized = () => {
+ s('initialized')
+ }
+
+ s.stop = () => {
+ s('stop')
+ }
+
+ s.stopped = () => {
+ s('stopped')
+ }
+
+ s.start = () => {
+ s('start')
+ }
+
+ s.started = () => {
+ s('started')
+ }
+
+ s.state = () => s._state
+
+ return s
+}
+
+},{"debug":456,"fsm-event":278}],560:[function(require,module,exports){
+'use strict'
+
+const promisify = require('promisify-es6')
+const map = require('async/map')
+const isIpfs = require('is-ipfs')
+const CID = require('cids')
+
+const ERR_BAD_PATH = 'ERR_BAD_PATH'
+exports.OFFLINE_ERROR = 'This command must be run in online mode. Try running \'ipfs daemon\' first.'
+
+/**
+ * Break an ipfs-path down into it's hash and an array of links.
+ *
+ * examples:
+ * b58Hash -> { hash: 'b58Hash', links: [] }
+ * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']}
+ * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] }
+ *
+ * @param {String} ipfsPath An ipfs-path
+ * @return {Object} { hash: base58 string, links: [string], ?err: Error }
+ * @throws on an invalid @param ipfsPath
+ */
+function parseIpfsPath (ipfsPath) {
+ const invalidPathErr = new Error('invalid ipfs ref path')
+ ipfsPath = ipfsPath.replace(/^\/ipfs\//, '')
+ const matched = ipfsPath.match(/([^/]+(?:\/[^/]+)*)\/?$/)
+ if (!matched) {
+ throw invalidPathErr
+ }
+
+ const [hash, ...links] = matched[1].split('/')
+
+ // check that a CID can be constructed with the hash
+ if (isIpfs.cid(hash)) {
+ return { hash, links }
+ } else {
+ throw invalidPathErr
+ }
+}
+
+/**
+ * Returns a well-formed ipfs Path.
+ * The returned path will always be prefixed with /ipfs/ or /ipns/.
+ * If the received string is not a valid ipfs path, an error will be returned
+ * examples:
+ * b58Hash -> { hash: 'b58Hash', links: [] }
+ * b58Hash/mercury/venus -> { hash: 'b58Hash', links: ['mercury', 'venus']}
+ * /ipfs/b58Hash/links/by/name -> { hash: 'b58Hash', links: ['links', 'by', 'name'] }
+ *
+ * @param {String} pathStr An ipfs-path, or ipns-path or a cid
+ * @return {String} ipfs-path or ipns-path
+ * @throws on an invalid @param ipfsPath
+ */
+const normalizePath = (pathStr) => {
+ if (isIpfs.cid(pathStr)) {
+ return `/ipfs/${pathStr}`
+ } else if (isIpfs.path(pathStr)) {
+ return pathStr
+ } else {
+ throw Object.assign(new Error(`invalid ${pathStr} path`), { code: ERR_BAD_PATH })
+ }
+}
+
+/**
+ * Resolve various styles of an ipfs-path to the hash of the target node.
+ * Follows links in the path.
+ *
+ * Accepts formats:
+ * -
+ * - /link/to/venus
+ * - /ipfs//link/to/pluto
+ * - multihash Buffer
+ * - Arrays of the above
+ *
+ * @param {IPFS} objectAPI The IPFS object api
+ * @param {Described above} ipfsPaths A single or collection of ipfs-paths
+ * @param {Function} callback res is Array
+ * if no callback is passed, returns a Promise
+ * @return {Promise|void}
+ */
+const resolvePath = promisify(function (objectAPI, ipfsPaths, callback) {
+ if (!Array.isArray(ipfsPaths)) {
+ ipfsPaths = [ipfsPaths]
+ }
+
+ map(ipfsPaths, (path, cb) => {
+ if (typeof path !== 'string') {
+ let cid
+
+ try {
+ cid = new CID(path)
+ } catch (err) {
+ return cb(err)
+ }
+
+ return cb(null, cid.buffer)
+ }
+
+ let parsedPath
+ try {
+ parsedPath = exports.parseIpfsPath(path)
+ } catch (err) {
+ return cb(err)
+ }
+
+ const rootHash = new CID(parsedPath.hash)
+ const rootLinks = parsedPath.links
+
+ if (!rootLinks.length) {
+ return cb(null, rootHash.buffer)
+ }
+
+ objectAPI.get(rootHash, follow.bind(null, rootHash, rootLinks))
+
+ // recursively follow named links to the target node
+ function follow (cid, links, err, obj) {
+ if (err) {
+ return cb(err)
+ }
+
+ if (!links.length) {
+ // done tracing, obj is the target node
+ return cb(null, cid.buffer)
+ }
+
+ const linkName = links[0]
+ const nextObj = obj.Links.find(link => link.Name === linkName)
+
+ if (!nextObj) {
+ return cb(new Error(`no link named "${linkName}" under ${cid}`))
+ }
+
+ objectAPI.get(nextObj.Hash, follow.bind(null, nextObj.Hash, links.slice(1)))
+ }
+ }, callback)
+})
+
+exports.normalizePath = normalizePath
+exports.parseIpfsPath = parseIpfsPath
+exports.resolvePath = resolvePath
+
+},{"async/map":87,"cids":185,"is-ipfs":614,"promisify-es6":1263}],561:[function(require,module,exports){
+'use strict'
+
+const CID = require('cids')
+
+/**
+* Stringify a CID encoded in the requested base, upgrading to v1 if necessary.
+*
+* Setting upgrade to false will disable automatic CID upgrading from v0 to v1
+* which is necessary if the multibase is something other than base58btc. Note
+* that it will also not apply the encoding (since v0 CIDs can only be encoded
+* as base58btc).
+*
+* @param {CID|Buffer|String} cid The CID to encode
+* @param {Object} [options] Optional options
+* @param {String} [options.base] Name of multibase codec to encode the CID with
+* @param {Boolean} [options.upgrade] Automatically upgrade v0 CIDs to v1 when
+* necessary. Default: true.
+* @returns {String}
+*/
+exports.cidToString = (cid, options) => {
+ options = options || {}
+ options.upgrade = options.upgrade !== false
+
+ if (!CID.isCID(cid)) {
+ cid = new CID(cid)
+ }
+
+ if (cid.version === 0 && options.base && options.base !== 'base58btc') {
+ if (!options.upgrade) return cid.toString()
+ cid = cid.toV1()
+ }
+
+ return cid.toBaseEncodedString(options.base)
+}
+
+},{"cids":185}],562:[function(require,module,exports){
+'use strict'
+
+const assert = require('assert')
+const mortice = require('mortice')
+const noop = () => {}
+
+// Wrap mortice to present a callback interface
+class Mutex {
+ constructor (repoOwner, options = {}) {
+ this.mutex = mortice(options.morticeId, {
+ singleProcess: repoOwner
+ })
+
+ this.log = options.log || noop
+ this.lockId = 0
+ }
+
+ readLock (lockedFn, cb) {
+ if (lockedFn && cb) {
+ this._lock('readLock').then(release => {
+ lockedFn((err, res) => {
+ release()
+
+ cb(err, res)
+ })
+ }, cb)
+ return
+ }
+
+ return this._lock('readLock')
+ }
+
+ writeLock (lockedFn, cb) {
+ if (lockedFn && cb) {
+ this._lock('writeLock').then(release => {
+ lockedFn((err, res) => {
+ release()
+
+ cb(err, res)
+ })
+ }, cb)
+ return
+ }
+
+ return this._lock('writeLock')
+ }
+
+ /**
+ * Request a read or write lock
+ *
+ * @param {String} type The type of lock: readLock / writeLock
+ * @returns {Promise}
+ */
+ async _lock (type) {
+ assert(typeof type === 'string', `first argument to Mutex.${type}() must be a string, got ${typeof type}`)
+
+ const lockId = this.lockId++
+ this.log(`[${lockId}] ${type} requested`)
+
+ // Get a Promise for the lock, wrap it for logging
+ const release = await this.mutex[type]()
+
+ this.log(`[${lockId}] ${type} started`)
+
+ return () => {
+ this.log(`[${lockId}] ${type} released`)
+ release()
+ }
+ }
+}
+
+module.exports = Mutex
+
+},{"assert":26,"mortice":1133}],563:[function(require,module,exports){
+'use strict'
+const hashlru = require('hashlru')
+
+/**
+ * Time Aware Least Recent Used Cache
+ * @see https://arxiv.org/pdf/1801.00390
+ * @todo move this to ipfs-utils or it's own package
+ *
+ * @class TLRU
+ */
+class TLRU {
+ /**
+ * Creates an instance of TLRU.
+ *
+ * @param {number} maxSize
+ * @memberof TLRU
+ */
+ constructor (maxSize) {
+ this.lru = hashlru(maxSize)
+ }
+
+ /**
+ * Get the value from the a key
+ *
+ * @param {string} key
+ * @returns {any}
+ * @memberof TLRU
+ */
+ get (key) {
+ const value = this.lru.get(key)
+ if (value) {
+ if ((value.expire) && (value.expire < Date.now())) {
+ this.lru.remove(key)
+ return undefined
+ }
+ }
+ return value.value
+ }
+
+ /**
+ * Set a key value pair
+ *
+ * @param {string} key
+ * @param {any} value
+ * @param {number} ttl - in miliseconds
+ * @memberof TLRU
+ */
+ set (key, value, ttl) {
+ this.lru.set(key, { value, expire: Date.now() + ttl })
+ }
+
+ /**
+ * Find if the cache has the key
+ *
+ * @param {string} key
+ * @returns {boolean}
+ * @memberof TLRU
+ */
+ has (key) {
+ const value = this.get(key)
+ if (value) {
+ return true
+ }
+ return false
+ }
+
+ /**
+ * Remove key
+ *
+ * @param {string} key
+ * @memberof TLRU
+ */
+ remove (key) {
+ this.lru.remove(key)
+ }
+
+ /**
+ * Clears the cache
+ *
+ * @memberof TLRU
+ */
+ clear () {
+ this.lru.clear()
+ }
+}
+
+module.exports = TLRU
+
+},{"hashlru":306}],564:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],565:[function(require,module,exports){
+arguments[4][412][0].apply(exports,arguments)
+},{"blakejs":132,"buffer":181,"dup":412}],566:[function(require,module,exports){
+arguments[4][413][0].apply(exports,arguments)
+},{"./blake":565,"./sha":568,"./utils":569,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],567:[function(require,module,exports){
+arguments[4][414][0].apply(exports,arguments)
+},{"./crypto":566,"buffer":181,"dup":414,"err-code":564,"multihashes":1157}],568:[function(require,module,exports){
+arguments[4][415][0].apply(exports,arguments)
+},{"buffer":181,"dup":415}],569:[function(require,module,exports){
+arguments[4][416][0].apply(exports,arguments)
+},{"buffer":181,"dup":416}],570:[function(require,module,exports){
+'use strict'
+
+exports.util = require('./util.js')
+exports.resolver = require('./resolver.js')
+exports.codec = exports.util.codec
+exports.defaultHashAlg = exports.util.defaultHashAlg
+
+},{"./resolver.js":571,"./util.js":572}],571:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+
+const util = require('./util')
+
+/**
+ * Resolves a path within a CBOR block.
+ *
+ * Returns the value or a link and the partial mising path. This way the
+ * IPLD Resolver can fetch the link and continue to resolve.
+ *
+ * @param {Buffer} binaryBlob - Binary representation of a CBOR block
+ * @param {string} [path='/'] - Path that should be resolved
+ * @returns {Object} result - Result of the path it it was resolved successfully
+ * @returns {*} result.value - Value the path resolves to
+ * @returns {string} result.remainderPath - If the path resolves half-way to a
+ * link, then the `remainderPath` is the part after the link that can be used
+ * for further resolving
+ */
+exports.resolve = (binaryBlob, path) => {
+ let node = util.deserialize(binaryBlob)
+
+ const parts = path.split('/').filter(Boolean)
+ while (parts.length) {
+ const key = parts.shift()
+ if (node[key] === undefined) {
+ throw new Error(`Object has no property '${key}'`)
+ }
+
+ node = node[key]
+ if (CID.isCID(node)) {
+ return {
+ value: node,
+ remainderPath: parts.join('/')
+ }
+ }
+ }
+
+ return {
+ value: node,
+ remainderPath: ''
+ }
+}
+
+const traverse = function * (node, path) {
+ // Traverse only objects and arrays
+ if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' ||
+ node === null) {
+ return
+ }
+ for (const item of Object.keys(node)) {
+ const nextpath = path === undefined ? item : path + '/' + item
+ yield nextpath
+ yield * traverse(node[item], nextpath)
+ }
+}
+
+/**
+ * Return all available paths of a block.
+ *
+ * @generator
+ * @param {Buffer} binaryBlob - Binary representation of a CBOR block
+ * @yields {string} - A single path
+ */
+exports.tree = function * (binaryBlob) {
+ const node = util.deserialize(binaryBlob)
+
+ yield * traverse(node)
+}
+
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":608,"./util":572,"cids":185}],572:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const cbor = require('borc')
+const multicodec = require('multicodec')
+const multihashing = require('multihashing-async')
+const CID = require('cids')
+const isCircular = require('is-circular')
+
+// https://github.com/ipfs/go-ipfs/issues/3570#issuecomment-273931692
+const CID_CBOR_TAG = 42
+
+function tagCID (cid) {
+ if (typeof cid === 'string') {
+ cid = new CID(cid).buffer
+ } else if (CID.isCID(cid)) {
+ cid = cid.buffer
+ }
+
+ return new cbor.Tagged(CID_CBOR_TAG, Buffer.concat([
+ Buffer.from('00', 'hex'), // thanks jdag
+ cid
+ ]))
+}
+
+function replaceCIDbyTAG (dagNode) {
+ let circular
+ try {
+ circular = isCircular(dagNode)
+ } catch (e) {
+ circular = false
+ }
+ if (circular) {
+ throw new Error('The object passed has circular references')
+ }
+
+ function transform (obj) {
+ if (!obj || Buffer.isBuffer(obj) || typeof obj === 'string') {
+ return obj
+ }
+
+ if (Array.isArray(obj)) {
+ return obj.map(transform)
+ }
+
+ if (CID.isCID(obj)) {
+ return tagCID(obj)
+ }
+
+ const keys = Object.keys(obj)
+
+ if (keys.length > 0) {
+ // Recursive transform
+ const out = {}
+ keys.forEach((key) => {
+ if (typeof obj[key] === 'object') {
+ out[key] = transform(obj[key])
+ } else {
+ out[key] = obj[key]
+ }
+ })
+ return out
+ } else {
+ return obj
+ }
+ }
+
+ return transform(dagNode)
+}
+
+exports = module.exports
+
+exports.codec = multicodec.DAG_CBOR
+exports.defaultHashAlg = multicodec.SHA2_256
+
+const defaultTags = {
+ [CID_CBOR_TAG]: (val) => {
+ // remove that 0
+ val = val.slice(1)
+ return new CID(val)
+ }
+}
+const defaultSize = 64 * 1024 // current decoder heap size, 64 Kb
+let currentSize = defaultSize
+const defaultMaxSize = 64 * 1024 * 1024 // max heap size when auto-growing, 64 Mb
+let maxSize = defaultMaxSize
+let decoder = null
+
+/**
+ * Configure the underlying CBOR decoder.
+ *
+ * @param {Object} [options] - The options the decoder takes. The decoder will reset to the defaul values if no options are given.
+ * @param {number} [options.size=65536] - The current heap size used in CBOR parsing, this may grow automatically as larger blocks are encountered up to `maxSize`
+ * @param {number} [options.maxSize=67108864] - The maximum size the CBOR parsing heap is allowed to grow to before `dagCBOR.util.deserialize()` returns an error
+ * @param {Object} [options.tags] - An object whose keys are CBOR tag numbers and values are transform functions that accept a `value` and return a decoded representation of that `value`
+ */
+exports.configureDecoder = (options) => {
+ let tags = defaultTags
+
+ if (options) {
+ if (typeof options.size === 'number') {
+ currentSize = options.size
+ }
+ if (typeof options.maxSize === 'number') {
+ maxSize = options.maxSize
+ }
+ if (options.tags) {
+ tags = Object.assign({}, defaultTags, options && options.tags)
+ }
+ } else {
+ // no options, reset to defaults
+ currentSize = defaultSize
+ maxSize = defaultMaxSize
+ }
+
+ let decoderOptions = {
+ tags: tags,
+ size: currentSize
+ }
+
+ decoder = new cbor.Decoder(decoderOptions)
+ // borc edits opts.size in-place so we can capture _actual_ size
+ currentSize = decoderOptions.size
+}
+
+exports.configureDecoder() // Setup default cbor.Decoder
+
+/**
+ * Serialize internal representation into a binary CBOR block.
+ *
+ * @param {Object} node - Internal representation of a CBOR block
+ * @returns {Buffer} - The encoded binary representation
+ */
+exports.serialize = (node) => {
+ const nodeTagged = replaceCIDbyTAG(node)
+ const serialized = cbor.encode(nodeTagged)
+
+ return serialized
+}
+
+/**
+ * Deserialize CBOR block into the internal representation.
+ *
+ * @param {Buffer} data - Binary representation of a CBOR block
+ * @returns {Object} - An object that conforms to the IPLD Data Model
+ */
+exports.deserialize = (data) => {
+ if (data.length > currentSize && data.length <= maxSize) {
+ exports.configureDecoder({ size: data.length })
+ }
+
+ if (data.length > currentSize) {
+ throw new Error('Data is too large to deserialize with current decoder')
+ }
+
+ const deserialized = decoder.decodeFirst(data)
+
+ return deserialized
+}
+
+/**
+ * Calculate the CID of the binary blob.
+ *
+ * @param {Object} binaryBlob - Encoded IPLD Node
+ * @param {Object} [userOptions] - Options to create the CID
+ * @param {number} [userOptions.cidVersion=1] - CID version number
+ * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format
+ * @returns {Promise.}
+ */
+exports.cid = async (binaryBlob, userOptions) => {
+ const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg }
+ const options = Object.assign(defaultOptions, userOptions)
+
+ const multihash = await multihashing(binaryBlob, options.hashAlg)
+ const codecName = multicodec.print[exports.codec]
+ const cid = new CID(options.cidVersion, codecName, multihash)
+
+ return cid
+}
+
+}).call(this,require("buffer").Buffer)
+},{"borc":141,"buffer":181,"cids":185,"is-circular":609,"multicodec":1151,"multihashing-async":567}],573:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],574:[function(require,module,exports){
+arguments[4][412][0].apply(exports,arguments)
+},{"blakejs":132,"buffer":181,"dup":412}],575:[function(require,module,exports){
+arguments[4][413][0].apply(exports,arguments)
+},{"./blake":574,"./sha":577,"./utils":578,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],576:[function(require,module,exports){
+arguments[4][414][0].apply(exports,arguments)
+},{"./crypto":575,"buffer":181,"dup":414,"err-code":573,"multihashes":1157}],577:[function(require,module,exports){
+arguments[4][415][0].apply(exports,arguments)
+},{"buffer":181,"dup":415}],578:[function(require,module,exports){
+arguments[4][416][0].apply(exports,arguments)
+},{"buffer":181,"dup":416}],579:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+const assert = require('assert')
+const withIs = require('class-is')
+const visibility = require('../visibility')
+
+// Link represents an IPFS Merkle DAG Link between Nodes.
+class DAGLink {
+ constructor (name, size, cid) {
+ assert(cid, 'A link requires a cid to point to')
+ // assert(size, 'A link requires a size')
+ // note - links should include size, but this assert is disabled
+ // for now to maintain consistency with go-ipfs pinset
+
+ this._name = name || ''
+ this._nameBuf = null
+ this._size = size
+ this._cid = new CID(cid)
+
+ // Make sure we have a nice public API that can be used by an IPLD resolver
+ visibility.hidePrivateFields(this)
+ visibility.addEnumerableGetters(this, ['Hash', 'Name', 'Tsize'])
+ }
+
+ toString () {
+ return `DAGLink <${this._cid.toBaseEncodedString()} - name: "${this.Name}", size: ${this.Tsize}>`
+ }
+
+ toJSON () {
+ if (!this._json) {
+ this._json = Object.freeze({
+ name: this.Name,
+ size: this.Tsize,
+ cid: this.Hash.toBaseEncodedString()
+ })
+ }
+
+ return Object.assign({}, this._json)
+ }
+
+ get Name () {
+ return this._name
+ }
+
+ // Memoize the Buffer representation of name
+ // We need this to sort the links, otherwise
+ // we will reallocate new buffers every time
+ get nameAsBuffer () {
+ if (this._nameBuf !== null) {
+ return this._nameBuf
+ }
+
+ this._nameBuf = Buffer.from(this._name)
+ return this._nameBuf
+ }
+
+ set Name (name) {
+ throw new Error("Can't set property: 'name' is immutable")
+ }
+
+ get Tsize () {
+ return this._size
+ }
+
+ set Tsize (size) {
+ throw new Error("Can't set property: 'size' is immutable")
+ }
+
+ get Hash () {
+ return this._cid
+ }
+
+ set Hash (cid) {
+ throw new Error("Can't set property: 'cid' is immutable")
+ }
+}
+
+exports = module.exports = withIs(DAGLink, { className: 'DAGLink', symbolName: '@ipld/js-ipld-dag-pb/daglink' })
+exports.util = require('./util')
+
+}).call(this,require("buffer").Buffer)
+},{"../visibility":592,"./util":580,"assert":26,"buffer":181,"cids":185,"class-is":187}],580:[function(require,module,exports){
+'use strict'
+
+const DAGLink = require('./index')
+
+function createDagLinkFromB58EncodedHash (link) {
+ return new DAGLink(
+ link.Name || link.name || '',
+ link.Tsize || link.Size || link.size || 0,
+ link.Hash || link.hash || link.multihash || link.cid
+ )
+}
+
+exports = module.exports
+exports.createDagLinkFromB58EncodedHash = createDagLinkFromB58EncodedHash
+
+},{"./index":579}],581:[function(require,module,exports){
+'use strict'
+
+const dagNodeUtil = require('./util')
+const cloneLinks = dagNodeUtil.cloneLinks
+const cloneData = dagNodeUtil.cloneData
+const toDAGLink = dagNodeUtil.toDAGLink
+const DAGLink = require('../dag-link')
+const DAGNode = require('./index')
+const create = require('./create')
+
+const asDAGLink = async (link) => {
+ if (DAGLink.isDAGLink(link)) {
+ // It's a DAGLink instance
+ // no need to do anything
+ return link
+ }
+
+ if (DAGNode.isDAGNode(link)) {
+ // It's a DAGNode instance
+ // convert to link
+ return toDAGLink(link, {})
+ }
+
+ // It's a Object with name, multihash/hash/cid and size
+ return new DAGLink(link.Name || link.name, link.Tsize || link.size, link.Hash || link.multihash || link.hash || link.cid)
+}
+
+const addLink = async (node, link) => {
+ const links = cloneLinks(node)
+ const data = cloneData(node)
+
+ const dagLink = await asDAGLink(link)
+ links.push(dagLink)
+ return create(data, links)
+}
+
+module.exports = addLink
+
+},{"../dag-link":579,"./create":584,"./index":585,"./util":587}],582:[function(require,module,exports){
+'use strict'
+
+/**
+ * Adds a link with its name as property to an object.
+ *
+ * The link won't be added if its name is empty or matches one of the existing
+ * properties.
+ *
+ * @param {Object} object - The object that contains an array of links
+ * @param {string} name - The name of the link to add
+ * @param {numner} position - The position within the array of links
+ */
+const addNamedLink = (object, name, position) => {
+ const skipNames = ['', ...Object.keys(object)]
+ if (skipNames.includes(name)) {
+ return
+ }
+ Object.defineProperty(object, name, {
+ enumerable: true,
+ configurable: true,
+ get: () => object._links[position].Hash
+ })
+}
+
+module.exports = addNamedLink
+
+},{}],583:[function(require,module,exports){
+'use strict'
+
+const dagNodeUtil = require('./util')
+const cloneLinks = dagNodeUtil.cloneLinks
+const cloneData = dagNodeUtil.cloneData
+const create = require('./create')
+
+function clone (dagNode) {
+ const data = cloneData(dagNode)
+ const links = cloneLinks(dagNode)
+ return create(data, links)
+}
+
+module.exports = clone
+
+},{"./create":584,"./util":587}],584:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const sort = require('stable')
+const {
+ serialize
+} = require('../util.js')
+const dagNodeUtil = require('./util.js')
+const linkSort = dagNodeUtil.linkSort
+const DAGNode = require('./index.js')
+const DAGLink = require('../dag-link')
+
+const create = (data, links = []) => {
+ if (typeof data === 'string') {
+ data = Buffer.from(data)
+ }
+
+ if (!Buffer.isBuffer(data)) {
+ throw new Error('Passed \'data\' is not a buffer or a string!')
+ }
+ links = links.map((link) => {
+ return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link)
+ })
+ links = sort(links, linkSort)
+
+ const serialized = serialize({
+ Data: data,
+ Links: links
+ })
+
+ return new DAGNode(data, links, serialized.length)
+}
+
+module.exports = create
+
+}).call(this,require("buffer").Buffer)
+},{"../dag-link":579,"../util.js":591,"./index.js":585,"./util.js":587,"buffer":181,"stable":1458}],585:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const assert = require('assert')
+const withIs = require('class-is')
+const addNamedLink = require('./addNamedLink')
+const visibility = require('../visibility')
+
+class DAGNode {
+ constructor (data, links, serializedSize) {
+ if (serializedSize !== 0) {
+ assert(serializedSize, 'A DAGNode requires it\'s serialized size')
+ }
+
+ this._data = data || Buffer.alloc(0)
+ this._links = links
+ this._serializedSize = serializedSize
+
+ // Make sure we have a nice public API that can be used by an IPLD resolver
+ visibility.hidePrivateFields(this)
+ visibility.addEnumerableGetters(this, ['Data', 'Links'])
+
+ // Add getters for existing links by the name of the link
+ // This is how paths are traversed in IPFS. Links with names won't
+ // override existing fields like `data` or `links`.
+ links.forEach((link, position) => {
+ addNamedLink(this, link.Name, position)
+ })
+ }
+
+ toJSON () {
+ if (!this._json) {
+ this._json = Object.freeze({
+ data: this.Data,
+ links: this._links.map((l) => l.toJSON()),
+ size: this.size
+ })
+ }
+
+ return Object.assign({}, this._json)
+ }
+
+ toString () {
+ return `DAGNode `
+ }
+
+ get size () {
+ if (this._size === undefined) {
+ this._size = this._links.reduce((sum, l) => sum + l.Tsize, this._serializedSize)
+ }
+
+ return this._size
+ }
+
+ set size (size) {
+ throw new Error("Can't set property: 'size' is immutable")
+ }
+
+ // Getters for backwards compatible path resolving
+ get Data () {
+ return this._data
+ }
+ set Data (_) {
+ throw new Error("Can't set property: 'Data' is immutable")
+ }
+ get Links () {
+ return this._links.map((link) => {
+ return {
+ Name: link.Name,
+ Tsize: link.Tsize,
+ Hash: link.Hash
+ }
+ })
+ }
+ set Links (_) {
+ throw new Error("Can't set property: 'Links' is immutable")
+ }
+}
+
+exports = module.exports = withIs(DAGNode, { className: 'DAGNode', symbolName: '@ipld/js-ipld-dag-pb/dagnode' })
+exports.create = require('./create')
+exports.clone = require('./clone')
+exports.addLink = require('./addLink')
+exports.rmLink = require('./rmLink')
+
+}).call(this,require("buffer").Buffer)
+},{"../visibility":592,"./addLink":581,"./addNamedLink":582,"./clone":583,"./create":584,"./rmLink":586,"assert":26,"buffer":181,"class-is":187}],586:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const dagNodeUtil = require('./util')
+const cloneLinks = dagNodeUtil.cloneLinks
+const cloneData = dagNodeUtil.cloneData
+const create = require('./create')
+const CID = require('cids')
+
+const rmLink = (dagNode, nameOrCid) => {
+ const data = cloneData(dagNode)
+ let links = cloneLinks(dagNode)
+
+ if (typeof nameOrCid === 'string') {
+ links = links.filter((link) => link.Name !== nameOrCid)
+ } else if (Buffer.isBuffer(nameOrCid) || CID.isCID(nameOrCid)) {
+ links = links.filter((link) => !link.Hash.equals(nameOrCid))
+ } else {
+ throw new Error('second arg needs to be a name or CID')
+ }
+
+ return create(data, links)
+}
+
+module.exports = rmLink
+
+}).call(this,{"isBuffer":require("../../../is-buffer/index.js")})
+},{"../../../is-buffer/index.js":608,"./create":584,"./util":587,"cids":185}],587:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const DAGLink = require('./../dag-link')
+const {
+ cid,
+ serialize
+} = require('../util')
+
+exports = module.exports
+
+function cloneData (dagNode) {
+ let data
+
+ if (dagNode.Data && dagNode.Data.length > 0) {
+ data = Buffer.alloc(dagNode.Data.length)
+ dagNode.Data.copy(data)
+ } else {
+ data = Buffer.alloc(0)
+ }
+
+ return data
+}
+
+function cloneLinks (dagNode) {
+ return dagNode.Links.slice()
+}
+
+function linkSort (a, b) {
+ return Buffer.compare(a.nameAsBuffer, b.nameAsBuffer)
+}
+
+/*
+ * toDAGLink converts a DAGNode to a DAGLink
+ */
+const toDAGLink = async (node, options = {}) => {
+ const serialized = serialize(node)
+ const nodeCid = await cid(serialized)
+ return new DAGLink(options.name || '', serialized.length, nodeCid)
+}
+
+exports.cloneData = cloneData
+exports.cloneLinks = cloneLinks
+exports.linkSort = linkSort
+exports.toDAGLink = toDAGLink
+
+}).call(this,require("buffer").Buffer)
+},{"../util":591,"./../dag-link":579,"buffer":181}],588:[function(require,module,exports){
+'use strict'
+
+module.exports = `// An IPFS MerkleDAG Link
+message PBLink {
+
+ // multihash of the target object
+ optional bytes Hash = 1;
+
+ // utf string name. should be unique per object
+ optional string Name = 2;
+
+ // cumulative size of target object
+ optional uint64 Tsize = 3;
+}
+
+// An IPFS MerkleDAG Node
+message PBNode {
+
+ // refs to other objects
+ repeated PBLink Links = 2;
+
+ // opaque user data
+ optional bytes Data = 1;
+}`
+
+},{}],589:[function(require,module,exports){
+'use strict'
+
+exports.DAGNode = require('./dag-node')
+exports.DAGLink = require('./dag-link')
+
+/*
+ * Functions to fulfil IPLD Format interface
+ * https://github.com/ipld/interface-ipld-format
+ */
+exports.resolver = require('./resolver')
+exports.util = require('./util')
+exports.codec = exports.util.codec
+exports.defaultHashAlg = exports.util.defaultHashAlg
+
+},{"./dag-link":579,"./dag-node":585,"./resolver":590,"./util":591}],590:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+
+const util = require('./util')
+
+/**
+ * Resolves a path within a PB block.
+ *
+ * Returns the value or a link and the partial mising path. This way the
+ * IPLD Resolver can fetch the link and continue to resolve.
+ *
+ * @param {Buffer} binaryBlob - Binary representation of a PB block
+ * @param {string} [path='/'] - Path that should be resolved
+ * @returns {Object} result - Result of the path it it was resolved successfully
+ * @returns {*} result.value - Value the path resolves to
+ * @returns {string} result.remainderPath - If the path resolves half-way to a
+ * link, then the `remainderPath` is the part after the link that can be used
+ * for further resolving
+ */
+exports.resolve = (binaryBlob, path) => {
+ let node = util.deserialize(binaryBlob)
+
+ const parts = path.split('/').filter(Boolean)
+ while (parts.length) {
+ const key = parts.shift()
+ if (node[key] === undefined) {
+ throw new Error(`Object has no property '${key}'`)
+ }
+
+ node = node[key]
+ if (CID.isCID(node)) {
+ return {
+ value: node,
+ remainderPath: parts.join('/')
+ }
+ }
+ }
+
+ return {
+ value: node,
+ remainderPath: ''
+ }
+}
+
+const traverse = function * (node, path) {
+ // Traverse only objects and arrays
+ if (Buffer.isBuffer(node) || CID.isCID(node) || typeof node === 'string' ||
+ node === null) {
+ return
+ }
+ for (const item of Object.keys(node)) {
+ const nextpath = path === undefined ? item : path + '/' + item
+ yield nextpath
+ yield * traverse(node[item], nextpath)
+ }
+}
+
+/**
+ * Return all available paths of a block.
+ *
+ * @generator
+ * @param {Buffer} binaryBlob - Binary representation of a PB block
+ * @yields {string} - A single path
+ */
+exports.tree = function * (binaryBlob) {
+ const node = util.deserialize(binaryBlob)
+
+ yield * traverse(node)
+}
+
+}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
+},{"../../is-buffer/index.js":608,"./util":591,"cids":185}],591:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const CID = require('cids')
+const protons = require('protons')
+const proto = protons(require('./dag.proto.js'))
+const DAGLink = require('./dag-link')
+const DAGNode = require('./dag-node')
+const multicodec = require('multicodec')
+const multihashing = require('multihashing-async')
+
+exports = module.exports
+
+exports.codec = multicodec.DAG_PB
+exports.defaultHashAlg = multicodec.SHA2_256
+
+/**
+ * Calculate the CID of the binary blob.
+ *
+ * @param {Object} binaryBlob - Encoded IPLD Node
+ * @param {Object} [userOptions] - Options to create the CID
+ * @param {number} [userOptions.cidVersion=1] - CID version number
+ * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format
+ * @returns {Promise.}
+ */
+const cid = async (binaryBlob, userOptions) => {
+ const defaultOptions = { cidVersion: 1, hashAlg: exports.defaultHashAlg }
+ const options = Object.assign(defaultOptions, userOptions)
+
+ const multihash = await multihashing(binaryBlob, options.hashAlg)
+ const codecName = multicodec.print[exports.codec]
+ const cid = new CID(options.cidVersion, codecName, multihash)
+
+ return cid
+}
+
+/**
+ * Serialize internal representation into a binary PB block.
+ *
+ * @param {Object} node - Internal representation of a CBOR block
+ * @returns {Buffer} - The encoded binary representation
+ */
+const serialize = (node) => {
+ let data = node.Data
+ let links = node.Links || []
+
+ // If the node is not an instance of a DAGNode, the link.hash might be a Base58 encoded string; decode it
+ if (!DAGNode.isDAGNode(node) && links) {
+ links = links.map((link) => {
+ return DAGLink.isDAGLink(link) ? link : DAGLink.util.createDagLinkFromB58EncodedHash(link)
+ })
+ }
+
+ const serialized = proto.PBNode.encode(toProtoBuf({
+ Data: data,
+ Links: links
+ }))
+
+ return serialized
+}
+
+/**
+ * Deserialize PB block into the internal representation.
+ *
+ * @param {Buffer} buffer - Binary representation of a PB block
+ * @returns {Object} - An object that conforms to the IPLD Data Model
+ */
+const deserialize = (buffer) => {
+ const pbn = proto.PBNode.decode(buffer)
+
+ const links = pbn.Links.map((link) => {
+ return new DAGLink(link.Name, link.Tsize, link.Hash)
+ })
+
+ const data = pbn.Data == null ? Buffer.alloc(0) : pbn.Data
+
+ return new DAGNode(data, links, buffer.length)
+}
+
+function toProtoBuf (node) {
+ const pbn = {}
+
+ if (node.Data && node.Data.length > 0) {
+ pbn.Data = node.Data
+ } else {
+ // NOTE: this has to be null in order to match go-ipfs serialization `null !== new Buffer(0)`
+ pbn.Data = null
+ }
+
+ if (node.Links && node.Links.length > 0) {
+ pbn.Links = node.Links
+ .map((link) => ({
+ Hash: link.Hash.buffer,
+ Name: link.Name,
+ Tsize: link.Tsize
+ }))
+ } else {
+ pbn.Links = null
+ }
+
+ return pbn
+}
+
+exports.serialize = serialize
+exports.deserialize = deserialize
+exports.cid = cid
+
+}).call(this,require("buffer").Buffer)
+},{"./dag-link":579,"./dag-node":585,"./dag.proto.js":588,"buffer":181,"cids":185,"multicodec":1151,"multihashing-async":576,"protons":1274}],592:[function(require,module,exports){
+'use strict'
+
+/**
+ * Make certain getters enumnerable
+ *
+ * This can be used to add additional getters that are enumerable and hence
+ * show up on an `Object.keys()` call.
+ *
+ * @param {Object} object - The object it should be applied to
+ * @param {Array.} fields - The fields that should be made enumnerable
+ */
+const addEnumerableGetters = (object, fields) => {
+ for (const field of fields) {
+ let prop
+ let proto = object
+ // Walk up the proottype chain until a property with the given name is
+ // found
+ while (prop === undefined) {
+ proto = Object.getPrototypeOf(proto)
+ if (proto === null) {
+ throw new Error(`no getter named '${field}' found`)
+ }
+ prop = Object.getOwnPropertyDescriptor(proto, field)
+ }
+
+ // There is a property with the correct name, but it's not a getter
+ if (prop.get === undefined) {
+ throw new Error(`no getter named '${field}' found`)
+ }
+ Object.defineProperty(object, field, {
+ enumerable: true,
+ get: prop.get
+ })
+ }
+}
+
+/**
+ * Makes all properties with a leading underscore non-enumerable.
+ *
+ * @param {Object} object - The object it should be applied to
+ */
+const hidePrivateFields = (object) => {
+ for (const key in object) {
+ if (key[0] === '_') {
+ Object.defineProperty(object, key, { enumerable: false })
+ }
+ }
+}
+
+module.exports = {
+ addEnumerableGetters,
+ hidePrivateFields
+}
+
+},{}],593:[function(require,module,exports){
+arguments[4][210][0].apply(exports,arguments)
+},{"dup":210}],594:[function(require,module,exports){
+arguments[4][412][0].apply(exports,arguments)
+},{"blakejs":132,"buffer":181,"dup":412}],595:[function(require,module,exports){
+arguments[4][413][0].apply(exports,arguments)
+},{"./blake":594,"./sha":597,"./utils":598,"buffer":181,"dup":413,"js-sha3":666,"murmurhash3js-revisited":1177}],596:[function(require,module,exports){
+arguments[4][414][0].apply(exports,arguments)
+},{"./crypto":595,"buffer":181,"dup":414,"err-code":593,"multihashes":1157}],597:[function(require,module,exports){
+arguments[4][415][0].apply(exports,arguments)
+},{"buffer":181,"dup":415}],598:[function(require,module,exports){
+arguments[4][416][0].apply(exports,arguments)
+},{"buffer":181,"dup":416}],599:[function(require,module,exports){
+'use strict'
+const CID = require('cids')
+const multihashing = require('multihashing-async')
+const multicodec = require('multicodec')
+
+// binary resolver
+module.exports = {
+ codec: multicodec.RAW,
+ defaultHashAlg: multicodec.SHA2_256,
+ resolver: {
+ /**
+ * Resolves a path within a Raw block.
+ *
+ * Always returns the raw data as value without any remainderPath.
+ *
+ * @param {Buffer} binaryBlob - Binary representation of a PB block
+ * @param {string} [path='/'] - Path that should be resolved (that value is ignored)
+ * @returns {Object} result - Result of the path it it was resolved successfully
+ * @returns {*} result.value - The raw data
+ * @returns {string} result.remainderPath - An empty string
+ */
+ resolve: (binaryBlob, path) => {
+ return {
+ value: binaryBlob,
+ remainderPath: ''
+ }
+ },
+ /**
+ * Return all available paths of a block.
+ *
+ * @generator
+ * @param {Buffer} binaryBlob - The raw data
+ * @returns {Object} - Finished generator with `done: true`
+ */
+ tree: (binaryBlob) => {
+ return {
+ done: true
+ }
+ }
+ },
+ util: {
+ deserialize: (data) => {
+ return data
+ },
+ serialize: (data) => {
+ return data
+ },
+ /**
+ * Calculate the CID of the binary blob.
+ *
+ * @param {Object} binaryBlob - Encoded IPLD Node
+ * @param {Object} [userOptions] - Options to create the CID
+ * @param {number} [userOptions.cidVersion=1] - CID version number
+ * @param {string} [UserOptions.hashAlg] - Defaults to the defaultHashAlg of the format
+ * @returns {Promise.}
+ */
+ cid: async (binaryBlob, userOptions) => {
+ const defaultOptions = { cidVersion: 1, hashAlg: module.exports.defaultHashAlg }
+ const options = Object.assign(defaultOptions, userOptions)
+
+ const multihash = await multihashing(binaryBlob, options.hashAlg)
+ const codecName = multicodec.print[module.exports.codec]
+ const cid = new CID(options.cidVersion, codecName, multihash)
+
+ return cid
+ }
+ }
+}
+
+},{"cids":185,"multicodec":1151,"multihashing-async":596}],600:[function(require,module,exports){
+(function (Buffer){
+'use strict'
+
+const Block = require('ipfs-block')
+const CID = require('cids')
+const mergeOptions = require('merge-options')
+const ipldDagCbor = require('ipld-dag-cbor')
+const ipldDagPb = require('ipld-dag-pb')
+const ipldRaw = require('ipld-raw')
+const multicodec = require('multicodec')
+const promisify = require('promisify-es6')
+const typical = require('typical')
+const { extendIterator } = require('./util')
+
+class IPLDResolver {
+ constructor (userOptions) {
+ const options = mergeOptions(IPLDResolver.defaultOptions, userOptions)
+
+ if (!options.blockService) {
+ throw new Error('Missing blockservice')
+ }
+ this.bs = options.blockService
+
+ // Object with current list of active resolvers
+ this.resolvers = {}
+
+ if (typeof options.loadFormat !== 'function') {
+ this.loadFormat = async (codec) => {
+ const codecName = multicodec.print[codec]
+ throw new Error(`No resolver found for codec "${codecName}"`)
+ }
+ } else {
+ this.loadFormat = options.loadFormat
+ }
+
+ // Enable all supplied formats
+ for (const format of options.formats) {
+ this.addFormat(format)
+ }
+ }
+
+ /**
+ * Add support for an IPLD Format.
+ *
+ * @param {Object} format - The implementation of an IPLD Format.
+ * @returns {this}
+ */
+ addFormat (format) {
+ const codec = format.codec
+ if (this.resolvers[format.format]) {
+ const codecName = multicodec.print[codec]
+ throw new Error(`Resolver already exists for codec "${codecName}"`)
+ }
+
+ this.resolvers[codec] = format
+
+ return this
+ }
+
+ /**
+ * Remove support for an IPLD Format.
+ *
+ * @param {number} codec - The codec of the IPLD Format to remove.
+ * @returns {this}
+ */
+ removeFormat (codec) {
+ if (this.resolvers[codec]) {
+ delete this.resolvers[codec]
+ }
+
+ return this
+ }
+
+ /**
+ * Retrieves IPLD Nodes along the `path` that is rooted at `cid`.
+ *
+ * @param {CID} cid - the CID the resolving starts.
+ * @param {string} path - the path that should be resolved.
+ * @returns {Iterable.>} - Returns an async iterator of all the IPLD Nodes that were traversed during the path resolving. Every element is an object with these fields:
+ * - `remainderPath`: the part of the path that wasn’t resolved yet.
+ * - `value`: the value where the resolved path points to. If further traversing is possible, then the value is a CID object linking to another IPLD Node. If it was possible to fully resolve the path, value is the value the path points to. So if you need the CID of the IPLD Node you’re currently at, just take the value of the previously returned IPLD Node.
+ */
+ resolve (cid, path) {
+ if (!CID.isCID(cid)) {
+ throw new Error('`cid` argument must be a CID')
+ }
+ if (typeof path !== 'string') {
+ throw new Error('`path` argument must be a string')
+ }
+
+ const generator = async function * () {
+ // End iteration if there isn't a CID to follow anymore
+ while (cid !== null) {
+ const format = await this._getFormat(cid.codec)
+
+ // get block
+ // use local resolver
+ // update path value
+ const block = await promisify(this.bs.get.bind(this.bs))(cid)
+ const result = format.resolver.resolve(block.data, path)
+
+ // Prepare for the next iteration if there is a `remainderPath`
+ path = result.remainderPath
+ let value = result.value
+ // NOTE vmx 2018-11-29: Not all IPLD Formats return links as
+ // CIDs yet. Hence try to convert old style links to CIDs
+ if (Object.keys(value).length === 1 && '/' in value) {
+ try {
+ value = new CID(value['/'])
+ } catch (_error) {
+ value = null
+ }
+ }
+ cid = CID.isCID(value) ? value : null
+
+ yield {
+ remainderPath: path,
+ value
+ }
+ }
+ }.bind(this)
+
+ return extendIterator(generator())
+ }
+
+ /**
+ * Get a node by CID.
+ *
+ * @param {CID} cid - The CID of the IPLD Node that should be retrieved.
+ * @returns {Promise.]