bsv-p2p-wallet-uat
Version:
A Bitcoin SV Wallet Library
1,192 lines (1,166 loc) • 2.66 MB
JavaScript
// modules are defined as an array
// [ module function, map of requires ]
//
// map of requires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the require for previous bundles
(function (modules, entry, mainEntry, parcelRequireName, globalName) {
/* eslint-disable no-undef */
var globalObject =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {};
/* eslint-enable no-undef */
// Save the require from previous bundle to this closure if any
var previousRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
var cache = previousRequire.cache || {};
// Do not use `require` to prevent Webpack from trying to bundle this call
var nodeRequire =
typeof module !== 'undefined' &&
typeof module.require === 'function' &&
module.require.bind(module);
function newRequire(name, jumped) {
if (!cache[name]) {
if (!modules[name]) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire =
typeof globalObject[parcelRequireName] === 'function' &&
globalObject[parcelRequireName];
if (!jumped && currentRequire) {
return currentRequire(name, true);
}
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) {
return previousRequire(name, true);
}
// Try the node require function if it exists.
if (nodeRequire && typeof name === 'string') {
return nodeRequire(name);
}
var err = new Error("Cannot find module '" + name + "'");
err.code = 'MODULE_NOT_FOUND';
throw err;
}
localRequire.resolve = resolve;
localRequire.cache = {};
var module = (cache[name] = new newRequire.Module(name));
modules[name][0].call(
module.exports,
localRequire,
module,
module.exports,
this
);
}
return cache[name].exports;
function localRequire(x) {
var res = localRequire.resolve(x);
return res === false ? {} : newRequire(res);
}
function resolve(x) {
var id = modules[name][1][x];
return id != null ? id : x;
}
}
function Module(moduleName) {
this.id = moduleName;
this.bundle = newRequire;
this.exports = {};
}
newRequire.isParcelRequire = true;
newRequire.Module = Module;
newRequire.modules = modules;
newRequire.cache = cache;
newRequire.parent = previousRequire;
newRequire.register = function (id, exports) {
modules[id] = [
function (require, module) {
module.exports = exports;
},
{},
];
};
Object.defineProperty(newRequire, 'root', {
get: function () {
return globalObject[parcelRequireName];
},
});
globalObject[parcelRequireName] = newRequire;
for (var i = 0; i < entry.length; i++) {
newRequire(entry[i]);
}
if (mainEntry) {
// Expose entry point to Node, AMD or browser globals
// Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
var mainExports = newRequire(mainEntry);
// CommonJS
if (typeof exports === 'object' && typeof module !== 'undefined') {
module.exports = mainExports;
// RequireJS
} else if (typeof define === 'function' && define.amd) {
define(function () {
return mainExports;
});
// <script>
} else if (globalName) {
this[globalName] = mainExports;
}
}
})({"baxo8":[function(require,module,exports) {
var global = arguments[3];
var HMR_HOST = null;
var HMR_PORT = null;
var HMR_SECURE = false;
var HMR_ENV_HASH = "d6ea1d42532a7575";
module.bundle.HMR_BUNDLE_ID = "5ba2c13dde74a287";
"use strict";
/* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, chrome, browser, globalThis, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
import type {
HMRAsset,
HMRMessage,
} from '@parcel/reporter-dev-server/src/HMRServer.js';
interface ParcelRequire {
(string): mixed;
cache: {|[string]: ParcelModule|};
hotData: mixed;
Module: any;
parent: ?ParcelRequire;
isParcelRequire: true;
modules: {|[string]: [Function, {|[string]: string|}]|};
HMR_BUNDLE_ID: string;
root: ParcelRequire;
}
interface ParcelModule {
hot: {|
data: mixed,
accept(cb: (Function) => void): void,
dispose(cb: (mixed) => void): void,
// accept(deps: Array<string> | string, cb: (Function) => void): void,
// decline(): void,
_acceptCallbacks: Array<(Function) => void>,
_disposeCallbacks: Array<(mixed) => void>,
|};
}
interface ExtensionContext {
runtime: {|
reload(): void,
getURL(url: string): string;
getManifest(): {manifest_version: number, ...};
|};
}
declare var module: {bundle: ParcelRequire, ...};
declare var HMR_HOST: string;
declare var HMR_PORT: string;
declare var HMR_ENV_HASH: string;
declare var HMR_SECURE: boolean;
declare var chrome: ExtensionContext;
declare var browser: ExtensionContext;
declare var __parcel__import__: (string) => Promise<void>;
declare var __parcel__importScripts__: (string) => Promise<void>;
declare var globalThis: typeof self;
declare var ServiceWorkerGlobalScope: Object;
*/ var OVERLAY_ID = "__parcel__error__overlay__";
var OldModule = module.bundle.Module;
function Module(moduleName) {
OldModule.call(this, moduleName);
this.hot = {
data: module.bundle.hotData,
_acceptCallbacks: [],
_disposeCallbacks: [],
accept: function(fn) {
this._acceptCallbacks.push(fn || function() {});
},
dispose: function(fn) {
this._disposeCallbacks.push(fn);
}
};
module.bundle.hotData = undefined;
}
module.bundle.Module = Module;
var checkedAssets, acceptedAssets, assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
function getHostname() {
return HMR_HOST || (location.protocol.indexOf("http") === 0 ? location.hostname : "localhost");
}
function getPort() {
return HMR_PORT || location.port;
} // eslint-disable-next-line no-redeclare
var parent = module.bundle.parent;
if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== "undefined") {
var hostname = getHostname();
var port = getPort();
var protocol = HMR_SECURE || location.protocol == "https:" && !/localhost|127.0.0.1|0.0.0.0/.test(hostname) ? "wss" : "ws";
var ws = new WebSocket(protocol + "://" + hostname + (port ? ":" + port : "") + "/"); // Web extension context
var extCtx = typeof chrome === "undefined" ? typeof browser === "undefined" ? null : browser : chrome; // Safari doesn't support sourceURL in error stacks.
// eval may also be disabled via CSP, so do a quick check.
var supportsSourceURL = false;
try {
(0, eval)('throw new Error("test"); //# sourceURL=test.js');
} catch (err) {
supportsSourceURL = err.stack.includes("test.js");
} // $FlowFixMe
ws.onmessage = async function(event) {
checkedAssets = {} /*: {|[string]: boolean|} */ ;
acceptedAssets = {} /*: {|[string]: boolean|} */ ;
assetsToAccept = [];
var data = JSON.parse(event.data);
if (data.type === "update") {
// Remove error overlay if there is one
if (typeof document !== "undefined") removeErrorOverlay();
let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH); // Handle HMR Update
let handled = assets.every((asset)=>{
return asset.type === "css" || asset.type === "js" && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
});
if (handled) {
console.clear(); // Dispatch custom event so other runtimes (e.g React Refresh) are aware.
if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") window.dispatchEvent(new CustomEvent("parcelhmraccept"));
await hmrApplyUpdates(assets);
for(var i = 0; i < assetsToAccept.length; i++){
var id = assetsToAccept[i][1];
if (!acceptedAssets[id]) hmrAcceptRun(assetsToAccept[i][0], id);
}
} else fullReload();
}
if (data.type === "error") {
// Log parcel errors to console
for (let ansiDiagnostic of data.diagnostics.ansi){
let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + "\n" + stack + "\n\n" + ansiDiagnostic.hints.join("\n"));
}
if (typeof document !== "undefined") {
// Render the fancy html overlay
removeErrorOverlay();
var overlay = createErrorOverlay(data.diagnostics.html); // $FlowFixMe
document.body.appendChild(overlay);
}
}
};
ws.onerror = function(e) {
console.error(e.message);
};
ws.onclose = function() {
console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
};
}
function removeErrorOverlay() {
var overlay = document.getElementById(OVERLAY_ID);
if (overlay) {
overlay.remove();
console.log("[parcel] ✨ Error resolved");
}
}
function createErrorOverlay(diagnostics) {
var overlay = document.createElement("div");
overlay.id = OVERLAY_ID;
let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
for (let diagnostic of diagnostics){
let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
return `${p}
<a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
${frame.code}`;
}, "") : diagnostic.stack;
errorHTML += `
<div>
<div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
🚨 ${diagnostic.message}
</div>
<pre>${stack}</pre>
<div>
${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + "</div>").join("")}
</div>
${diagnostic.documentation ? `<div>📝 <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ""}
</div>
`;
}
errorHTML += "</div>";
overlay.innerHTML = errorHTML;
return overlay;
}
function fullReload() {
if ("reload" in location) location.reload();
else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
}
function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
var modules = bundle.modules;
if (!modules) return [];
var parents = [];
var k, d, dep;
for(k in modules)for(d in modules[k][1]){
dep = modules[k][1][d];
if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
bundle,
k
]);
}
if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
return parents;
}
function updateLink(link) {
var newLink = link.cloneNode();
newLink.onload = function() {
if (link.parentNode !== null) // $FlowFixMe
link.parentNode.removeChild(link);
};
newLink.setAttribute("href", link.getAttribute("href").split("?")[0] + "?" + Date.now()); // $FlowFixMe
link.parentNode.insertBefore(newLink, link.nextSibling);
}
var cssTimeout = null;
function reloadCSS() {
if (cssTimeout) return;
cssTimeout = setTimeout(function() {
var links = document.querySelectorAll('link[rel="stylesheet"]');
for(var i = 0; i < links.length; i++){
// $FlowFixMe[incompatible-type]
var href = links[i].getAttribute("href");
var hostname = getHostname();
var servedFromHMRServer = hostname === "localhost" ? new RegExp("^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):" + getPort()).test(href) : href.indexOf(hostname + ":" + getPort());
var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
if (!absolute) updateLink(links[i]);
}
cssTimeout = null;
}, 50);
}
function hmrDownload(asset) {
if (asset.type === "js") {
if (typeof document !== "undefined") {
let script = document.createElement("script");
script.src = asset.url + "?t=" + Date.now();
if (asset.outputFormat === "esmodule") script.type = "module";
return new Promise((resolve, reject)=>{
var _document$head;
script.onload = ()=>resolve(script);
script.onerror = reject;
(_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
});
} else if (typeof importScripts === "function") {
// Worker scripts
if (asset.outputFormat === "esmodule") return import(asset.url + "?t=" + Date.now());
else return new Promise((resolve, reject)=>{
try {
importScripts(asset.url + "?t=" + Date.now());
resolve();
} catch (err) {
reject(err);
}
});
}
}
}
async function hmrApplyUpdates(assets) {
global.parcelHotUpdate = Object.create(null);
let scriptsToRemove;
try {
// If sourceURL comments aren't supported in eval, we need to load
// the update from the dev server over HTTP so that stack traces
// are correct in errors/logs. This is much slower than eval, so
// we only do it if needed (currently just Safari).
// https://bugs.webkit.org/show_bug.cgi?id=137297
// This path is also taken if a CSP disallows eval.
if (!supportsSourceURL) {
let promises = assets.map((asset)=>{
var _hmrDownload;
return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
// Web extension bugfix for Chromium
// https://bugs.chromium.org/p/chromium/issues/detail?id=1255412#c12
if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3) {
if (typeof ServiceWorkerGlobalScope != "undefined" && global instanceof ServiceWorkerGlobalScope) {
extCtx.runtime.reload();
return;
}
asset.url = extCtx.runtime.getURL("/__parcel_hmr_proxy__?url=" + encodeURIComponent(asset.url + "?t=" + Date.now()));
return hmrDownload(asset);
}
throw err;
});
});
scriptsToRemove = await Promise.all(promises);
}
assets.forEach(function(asset) {
hmrApply(module.bundle.root, asset);
});
} finally{
delete global.parcelHotUpdate;
if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
if (script) {
var _document$head2;
(_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
}
});
}
}
function hmrApply(bundle, asset) {
var modules = bundle.modules;
if (!modules) return;
if (asset.type === "css") reloadCSS();
else if (asset.type === "js") {
let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
if (deps) {
if (modules[asset.id]) {
// Remove dependencies that are removed and will become orphaned.
// This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
let oldDeps = modules[asset.id][1];
for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
let id = oldDeps[dep];
let parents = getParents(module.bundle.root, id);
if (parents.length === 1) hmrDelete(module.bundle.root, id);
}
}
if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
// support for source maps is better with eval.
(0, eval)(asset.output);
// $FlowFixMe
let fn = global.parcelHotUpdate[asset.id];
modules[asset.id] = [
fn,
deps
];
} else if (bundle.parent) hmrApply(bundle.parent, asset);
}
}
function hmrDelete(bundle, id) {
let modules = bundle.modules;
if (!modules) return;
if (modules[id]) {
// Collect dependencies that will become orphaned when this module is deleted.
let deps = modules[id][1];
let orphans = [];
for(let dep in deps){
let parents = getParents(module.bundle.root, deps[dep]);
if (parents.length === 1) orphans.push(deps[dep]);
} // Delete the module. This must be done before deleting dependencies in case of circular dependencies.
delete modules[id];
delete bundle.cache[id]; // Now delete the orphans.
orphans.forEach((id)=>{
hmrDelete(module.bundle.root, id);
});
} else if (bundle.parent) hmrDelete(bundle.parent, id);
}
function hmrAcceptCheck(bundle, id, depsByBundle) {
if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
// Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
let parents = getParents(module.bundle.root, id);
let accepted = false;
while(parents.length > 0){
let v = parents.shift();
let a = hmrAcceptCheckOne(v[0], v[1], null);
if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
accepted = true;
else {
// Otherwise, queue the parents in the next level upward.
let p = getParents(module.bundle.root, v[1]);
if (p.length === 0) {
// If there are no parents, then we've reached an entry without accepting. Reload.
accepted = false;
break;
}
parents.push(...p);
}
}
return accepted;
}
function hmrAcceptCheckOne(bundle, id, depsByBundle) {
var modules = bundle.modules;
if (!modules) return;
if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
// If we reached the root bundle without finding where the asset should go,
// there's nothing to do. Mark as "accepted" so we don't reload the page.
if (!bundle.parent) return true;
return hmrAcceptCheck(bundle.parent, id, depsByBundle);
}
if (checkedAssets[id]) return true;
checkedAssets[id] = true;
var cached = bundle.cache[id];
assetsToAccept.push([
bundle,
id
]);
if (!cached || cached.hot && cached.hot._acceptCallbacks.length) return true;
}
function hmrAcceptRun(bundle, id) {
var cached = bundle.cache[id];
bundle.hotData = {};
if (cached && cached.hot) cached.hot.data = bundle.hotData;
if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
cb(bundle.hotData);
});
delete bundle.cache[id];
bundle(id);
cached = bundle.cache[id];
if (cached && cached.hot && cached.hot._acceptCallbacks.length) cached.hot._acceptCallbacks.forEach(function(cb) {
var assetsToAlsoAccept = cb(function() {
return getParents(module.bundle.root, id);
});
if (assetsToAlsoAccept && assetsToAccept.length) // $FlowFixMe[method-unbinding]
assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
});
acceptedAssets[id] = true;
}
},{}],"kShel":[function(require,module,exports) {
"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
enumerable: true,
get: function() {
return m[k];
}
};
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
default: mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.BlockchainCache = exports.TxCache = exports.Tx = exports.Encoders = exports.Crypto = exports.Blockchain = exports.HDPrivateKey = exports.OfflineWallet = exports.Wallet = exports.PeerToPeerWallet = void 0;
const Wallet_1 = __importDefault(require("ae267767fa79c691"));
exports.Wallet = Wallet_1.default;
const HDPrivateKey_1 = __importDefault(require("f2d157406224d0a1"));
exports.HDPrivateKey = HDPrivateKey_1.default;
const Blockchain_1 = __importDefault(require("8f17c2a8b58e5374"));
exports.Blockchain = Blockchain_1.default;
const BlockchainCache_1 = __importDefault(require("7722d55eaed38cb7"));
exports.BlockchainCache = BlockchainCache_1.default;
const TxCache_1 = __importDefault(require("76cf2a6b584d1065"));
exports.TxCache = TxCache_1.default;
const Tx = __importStar(require("723fb96563b6a72a"));
exports.Tx = Tx;
const Crypto = __importStar(require("3076403eed67b4f9"));
exports.Crypto = Crypto;
const Encoders = __importStar(require("e10d252adde0338d"));
exports.Encoders = Encoders;
const OfflineWallet_1 = __importDefault(require("a382199d767ad248"));
exports.OfflineWallet = OfflineWallet_1.default;
const PeerToPeerWallet_1 = __importDefault(require("47eeb7f1727ae3d8"));
exports.PeerToPeerWallet = PeerToPeerWallet_1.default;
},{"ae267767fa79c691":"hwH6R","f2d157406224d0a1":"8Imyt","8f17c2a8b58e5374":"agY3L","7722d55eaed38cb7":"kpnpI","76cf2a6b584d1065":"cjddo","723fb96563b6a72a":"82oGo","3076403eed67b4f9":"cZ5Du","e10d252adde0338d":"jqr8S","a382199d767ad248":"abHPb","47eeb7f1727ae3d8":"jGeP7"}],"hwH6R":[function(require,module,exports) {
"use strict";
var __awaiter = this && this.__awaiter || function(thisArg, _arguments, P, generator) {
function adopt(value) {
return value instanceof P ? value : new P(function(resolve) {
resolve(value);
});
}
return new (P || (P = Promise))(function(resolve, reject) {
function fulfilled(value) {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
}
function rejected(value) {
try {
step(generator["throw"](value));
} catch (e) {
reject(e);
}
}
function step(result) {
result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
}
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = this && this.__rest || function(s, e) {
var t = {};
for(var p in s)if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function") {
for(var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++)if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
const HDPrivateKey_1 = __importDefault(require("91d334ccd3958bbd"));
const bsv_1 = __importDefault(require("d93cd58e81e8b0ac"));
const address_1 = __importDefault(require("68c290e84bda38ec"));
const Blockchain_1 = __importDefault(require("48f8df22de1bfa51"));
// * little helper function (a move dans un autre fichier)
const computeTotalInChunk = (data)=>{
return data.reduce((total, { balance: { confirmed , unconfirmed } , address: adr })=>{
const localTotal = confirmed + unconfirmed;
return localTotal + total;
}, 0);
};
class BSVWallet extends HDPrivateKey_1.default {
constructor(_a){
var { key ="" , keyFormat ="mnemonic" , language ="ENGLISH" , network ="livenet" } = _a, options = __rest(_a, [
"key",
"keyFormat",
"language",
"network"
]);
super(Object.assign({
key,
keyFormat,
language,
network
}, options));
this.lastUnusedAddressIndex = 10;
this.blockchain = new Blockchain_1.default(network);
}
// * adresse ou on va recevoir
getUnusedAddress() {
return __awaiter(this, void 0, void 0, function*() {
// * TODO : FAIRE EN SORTE QUE LE PREMIER APPEL SOIT MOINS LONG
do {
var adr = this.getDerivatedAddress(++this.lastUnusedAddressIndex);
var history = yield this.blockchain.getHistory(adr);
}while (history.length > 0);
return adr;
});
}
// * will return an unused address
getAddress() {
return __awaiter(this, void 0, void 0, function*() {
return yield this.getUnusedAddress();
});
}
/**
* @param debitedAddressIndex index of the key to use in the wallet
* @param amount amount of BTC to send
* @returns tx encoded in hexadicimal format
*/ signTxv1(debitedAddressIndex, recipientAdr, amount, changeAdr) {
return __awaiter(this, void 0, void 0, function*() {
changeAdr = !changeAdr ? yield this.getUnusedAddress() : changeAdr;
const myAddress = this.getDerivatedAddress(debitedAddressIndex);
const privKey = this.getDerivatedPrivateKey(debitedAddressIndex);
const unspendTransactions = yield this.blockchain.getUnspendTxOuput(myAddress);
const myInputs = [];
for (let transaction of unspendTransactions){
// * récupérer son script en hexa depuis la blockchain
const rawTxScript = yield this.blockchain.getRawTx(transaction["tx_hash"]);
// * l'interpèter avec la lib
const tx = new bsv_1.default.Transaction(rawTxScript);
console.log({
tx
});
// * et extrait les utxo
const data = tx.toObject();
const { satoshis , script } = data.outputs[transaction.tx_pos]; // très exactement ça // pas sur pour le tx_pos
myInputs.push({
txid: transaction.tx_hash,
satoshis: satoshis,
vout: transaction.tx_pos,
scriptPubKey: script
});
}
// * all the stuff above is garbage to understand juste focus on this
const finalTx = new bsv_1.default.Transaction();
finalTx.from(myInputs);
finalTx.to(new address_1.default(recipientAdr), amount);
finalTx.change(new address_1.default(changeAdr || myAddress));
finalTx.sign(this._getPrivateKey(debitedAddressIndex));
return finalTx.toString();
});
}
/**
* @param maxIndex this function with download the history of each derivated address from 0 to this
* @returns
*/ getUtxo(maxIndex) {
return __awaiter(this, void 0, void 0, function*() {
// au cas ou cette fonction n'est jamais été appelée
maxIndex || (yield this.getUnusedAddress());
const numberOfAddressToCheck = maxIndex || this.lastUnusedAddressIndex + 3;
const addresses = this.getAddresses(0, Math.max(numberOfAddressToCheck, 100));
// * we will for all of the address of this wallet
// * load it's utxo into an array
const utxo = yield this.blockchain.getBulkUTXO(addresses);
const allUTXO = utxo.map((utxo)=>{
const ownerAddress = this.getDerivatedAddress(utxo.privateKeyIndex);
const improvedData = {
privKeyIndex: utxo.privateKeyIndex,
txId: utxo.tx_hash,
satoshis: utxo.value,
outputIndex: utxo.tx_pos,
script: bsv_1.default.Script(new address_1.default(ownerAddress)),
fromAddress: ownerAddress,
ownerAddress: utxo.ownerAddress
};
return improvedData;
});
return allUTXO;
});
}
signTx(output) {
return __awaiter(this, void 0, void 0, function*() {
// TODO : checker si le montant en utxo est disponible
const tx = new bsv_1.default.Transaction();
// * on charge les inputs
const utxo = yield this.getUtxo();
tx.from(utxo);
// * on charge les ouputs
if (Array.isArray(output)) output.forEach(({ to: address , amount })=>tx.to(address, amount));
else tx.to(output.to, output.amount);
// * ou oublie pas l'addresse de change
const unusedAdr = yield this.getUnusedAddress();
tx.change(unusedAdr);
// * on récupères la clef privée qui correspond à chaque utxo
const privateKeys = utxo.map((utxo)=>this.getDerivatedPrivateKey(utxo.privKeyIndex));
// TODO: prendre en compte les clefs privées en double dans cette liste
// * et enfin on signe la transaction
const txHex = tx.sign(privateKeys);
return txHex.toString();
});
}
/**
* broadcast the transaction
* equivalent of
* ```js
* wallet.blockchain.boardcast(txHex)
* ```
* @param txHex
* @returns
*/ broadcast(txHex) {
return this.blockchain.broadcast(txHex);
}
getBalance() {
return __awaiter(this, void 0, void 0, function*() {
const utxo = yield this.getUtxo();
console.log({
utxo
});
const totalSat = utxo.reduce((total, utxo)=>total + utxo.satoshis, 0);
// TODO: return confirmed et unconfirmed seperatly
return totalSat;
});
}
}
exports.default = BSVWallet;
},{"91d334ccd3958bbd":"8Imyt","d93cd58e81e8b0ac":"hOFCS","68c290e84bda38ec":"lDqbu","48f8df22de1bfa51":"agY3L"}],"8Imyt":[function(require,module,exports) {
"use strict";
var __createBinding = this && this.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) desc = {
enumerable: true,
get: function() {
return m[k];
}
};
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = this && this.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", {
enumerable: true,
value: v
});
} : function(o, v) {
o["default"] = v;
});
var __importStar = this && this.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for(var k in mod)if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = this && this.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : {
"default": mod
};
};
Object.defineProperty(exports, "__esModule", {
value: true
});
const address_1 = __importDefault(require("51d30b99fbfc61b2"));
const hdprivatekey_1 = __importDefault(require("45447b2163a66dc3"));
const words_1 = __importDefault(require("aa316d3b0073ce32"));
const mnemonic_1 = __importDefault(require("ebc411ef58ea6d4f"));
const Words = __importStar(require("b437d896be089b40"));
const HDPrivateKeyFromMnemonic = (key, language, network)=>{
const mnemonicObj = (0, mnemonic_1.default)(key, Words[language]);
return hdprivatekey_1.default.fromSeed(mnemonicObj.toSeed(), network);
};
class HDPrivateKeyManager {
constructor({ key , keyFormat , language , network }){
// * si il n'y a pas de clef on crée un nouveau wallet
if (!key) {
const mnemonic = mnemonic_1.default.fromRandom(Words[language]);
this.masterHDPrivateKey = hdprivatekey_1.default.fromSeed(mnemonic.toSeed(), network);
this.mnemonic = mnemonic.toString();
return;
}
if (keyFormat == "seed") // * c'est de la merde on peut pas recup le mnemonic avec ça
this.masterHDPrivateKey = hdprivatekey_1.default.fromString(key);
if (keyFormat == "mnemonic") {
const mnemonic1 = key;
const privKey = HDPrivateKeyFromMnemonic(mnemonic1, language, network);
this.masterHDPrivateKey = privKey;
this.mnemonic = mnemonic1;
}
this.network = network;
}
/**
* ------ Wrapper BSV.JS ----
*/ _getPrivateKey(index) {
return this.masterHDPrivateKey.deriveChild(`m/44'/${this.network == "testnet" ? 1 : 0}'/0'/0/${index}`, false).privateKey;
}
_getPublicKey(index) {
return this._getPrivateKey(index).publicKey;
}
_getAddress(index) {
return address_1.default.fromPublicKey(this._getPublicKey(index), this.network);
}
// * clean interface
getDerivatedPublicKey(index) {
return this._getPublicKey(index).toString();
}
getDerivatedPrivateKey(index) {
return this._getPrivateKey(index).toString();
}
getDerivatedAddress(index) {
return this._getAddress(index).toString();
}
getMnemonic(language = "ENGLISH") {
if (!this.mnemonic) throw new Error('you should create the private key instance from the "mnemonic" KeyFormat if you would like to use this feature');
if (language != "ENGLISH") throw new Error("sorry mnemonic language other than english are not yet implemented");
// todo: changement de langage
const wordList = words_1.default[language];
return this.mnemonic;
}
/**
* give out a range of adresses
*/ getAddresses(start, end) {
// * in case of wreid input
if (end < start) {
const tmp = start;
start = end;
end = tmp;
}
// console.log({ start, end });
const addresses = [];
for(let n = start; n <= end; ++n)addresses.push(this.getDerivatedAddress(n));
return addresses;
}
toString() {
return this.getMnemonic();
}
}
exports.default = HDPrivateKeyManager;
},{"51d30b99fbfc61b2":"lDqbu","45447b2163a66dc3":"eAQrC","aa316d3b0073ce32":"jWuWU","ebc411ef58ea6d4f":"9fYHn","b437d896be089b40":"jWuWU"}],"lDqbu":[function(require,module,exports) {
var Buffer = require("23be59c6d1d59b25").Buffer;
"use strict";
var _ = require("330674f78d2a614d");
var $ = require("de670a636c449d22");
var errors = require("b25e2d0a02674c7f");
var Base58Check = require("98485e841ec3d349");
var Networks = require("96cce7a86ab1ef80");
var Hash = require("4bd984558535959b");
var JSUtil = require("db0e1b8e0fe210be");
var PublicKey = require("669eb1185ad40ece");
/**
* Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
* or an instance of {@link PublicKey} or {@link Script}.
*
* This is an immutable class, and if the first parameter provided to this constructor is an
* `Address` instance, the same argument will be returned.
*
* An address has two key properties: `network` and `type`. The type is either
* `Address.PayToPublicKeyHash` (value is the `'pubkeyhash'` string)
* or `Address.PayToScriptHash` (the string `'scripthash'`). The network is an instance of {@link Network}.
* You can quickly check whether an address is of a given kind by using the methods
* `isPayToPublicKeyHash` and `isPayToScriptHash`
*
* @example
* ```javascript
* // validate that an input field is valid
* var error = Address.getValidationError(input, 'testnet');
* if (!error) {
* var address = Address(input, 'testnet');
* } else {
* // invalid network or checksum (typo?)
* var message = error.messsage;
* }
*
* // get an address from a public key
* var address = Address(publicKey, 'testnet').toString();
* ```
*
* @param {*} data - The encoded data in various formats
* @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type of address: 'script' or 'pubkey'
* @returns {Address} A new valid and frozen instance of an Address
* @constructor
*/ function Address(data, network, type) {
if (!(this instanceof Address)) return new Address(data, network, type);
if (_.isArray(data) && _.isNumber(network)) return Address.createMultisig(data, network, type);
if (data instanceof Address) // Immutable instance
return data;
$.checkArgument(data, "First argument is required, please include address data.", "guide/address.html");
if (network && !Networks.get(network)) throw new TypeError('Second argument must be "livenet", "testnet", or "regtest".');
if (type && type !== Address.PayToPublicKeyHash && type !== Address.PayToScriptHash) throw new TypeError('Third argument must be "pubkeyhash" or "scripthash".');
var info = this._classifyArguments(data, network, type);
// set defaults if not set
info.network = info.network || Networks.get(network) || Networks.defaultNetwork;
info.type = info.type || type || Address.PayToPublicKeyHash;
JSUtil.defineImmutable(this, {
hashBuffer: info.hashBuffer,
network: info.network,
type: info.type
});
return this;
}
/**
* Internal function used to split different kinds of arguments of the constructor
* @param {*} data - The encoded data in various formats
* @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type of address: 'script' or 'pubkey'
* @returns {Object} An "info" object with "type", "network", and "hashBuffer"
*/ Address.prototype._classifyArguments = function(data, network, type) {
// transform and validate input data
if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 20) return Address._transformHash(data);
else if ((data instanceof Buffer || data instanceof Uint8Array) && data.length === 21) return Address._transformBuffer(data, network, type);
else if (data instanceof PublicKey) return Address._transformPublicKey(data);
else if (data instanceof Script) return Address._transformScript(data, network);
else if (typeof data === "string") return Address._transformString(data, network, type);
else if (_.isObject(data)) return Address._transformObject(data);
else throw new TypeError("First argument is an unrecognized data format.");
};
/** @static */ Address.PayToPublicKeyHash = "pubkeyhash";
/** @static */ Address.PayToScriptHash = "scripthash";
/**
* @param {Buffer} hash - An instance of a hash Buffer
* @returns {Object} An object with keys: hashBuffer
* @private
*/ Address._transformHash = function(hash) {
var info = {};
if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) throw new TypeError("Address supplied is not a buffer.");
if (hash.length !== 20) throw new TypeError("Address hashbuffers must be exactly 20 bytes.");
info.hashBuffer = hash;
return info;
};
/**
* Deserializes an address serialized through `Address#toObject()`
* @param {Object} data
* @param {string} data.hash - the hash that this address encodes
* @param {string} data.type - either 'pubkeyhash' or 'scripthash'
* @param {Network=} data.network - the name of the network associated
* @return {Address}
*/ Address._transformObject = function(data) {
$.checkArgument(data.hash || data.hashBuffer, "Must provide a `hash` or `hashBuffer` property");
$.checkArgument(data.type, "Must provide a `type` property");
return {
hashBuffer: data.hash ? Buffer.from(data.hash, "hex") : data.hashBuffer,
network: Networks.get(data.network) || Networks.defaultNetwork,
type: data.type
};
};
/**
* Internal function to discover the network and type based on the first data byte
*
* @param {Buffer} buffer - An instance of a hex encoded address Buffer
* @returns {Object} An object with keys: network and type
* @private
*/ Address._classifyFromVersion = function(buffer) {
var version = {};
var pubkeyhashNetwork = Networks.get(buffer[0], "pubkeyhash");
var scripthashNetwork = Networks.get(buffer[0], "scripthash");
if (pubkeyhashNetwork) {
version.network = pubkeyhashNetwork;
version.type = Address.PayToPublicKeyHash;
} else if (scripthashNetwork) {
version.network = scripthashNetwork;
version.type = Address.PayToScriptHash;
}
return version;
};
/**
* Internal function to transform a bitcoin address buffer
*
* @param {Buffer} buffer - An instance of a hex encoded address Buffer
* @param {string=} network - The network: 'livenet' or 'testnet'
* @param {string=} type - The type: 'pubkeyhash' or 'scripthash'
* @returns {Object} An object with keys: hashBuffer, network and type
* @private
*/ Address._transformBuffer = function(buffer, network, type) {
var info = {};
if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) throw new TypeError("Address supplied is not a buffer.");
if (buffer.length !== 21) throw new TypeError("Address buffers must be exactly 21 bytes.");
var networkObj = Networks.get(network);
var bufferVersion = Address._classifyFromVersion(buffer);
if (network && !networkObj) throw new TypeError("Unknown network");
if (!bufferVersion.network || networkObj && networkObj !== bufferVersion.network) // console.log(bufferVersion)
throw new TypeError("Address has mismatched network type.");
if (!bufferVersion.type || type && type !== bufferVersion.type) throw new TypeError("Address has mismatched type.");
info.hashBuffer = buffer.slice(1);
info.network = bufferVersion.network;
info.type = bufferVersion.type;
return info;
};
/**
* Internal function to transform a {@link PublicKey}
*
* @param {PublicKey} pubkey - An instance of PublicKey
* @returns {Object} An object with keys: hashBuffer, type
* @private
*/ Address._transformPublicKey = function(pubkey) {
var info = {};
if (!(pubkey instanceof PublicKey)) throw new TypeError("Address must be an instance of PublicKey.");
info.hashBuffer = Hash.sha256ripemd160(pubkey.toBuffer());
info.type = Address.PayToPublicKeyHash;
return info;
};
/**
* Internal function to transform a {@link Script} into a `info` object.
*
* @param {Script} script - An instance of Script
* @returns {Object} An object with keys: hashBuffer, type
* @private
*/ Address._transformScript = function(script, network) {
$.checkArgument(script instanceof Script, "script must be a Script instance");
var info = script.getAddressInfo(network);
if (!info) throw new errors.Script.CantDeriveAddress(script);
return info;
};
/**
* Creates a P2SH address from a set of public keys and a threshold.
*
* The addresses will be sorted lexicographically, as that is the trend in bitcoin.
* To create an address from unsorted public keys, use the {@link Script#buildMultisigOut}
* interface.
*
* @param {Array} publicKeys - a set of public keys to create an address
* @param {number} threshold - the number of signatures needed to release the funds
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @return {Address}
*/ Address.createMultisig = function(publicKeys, threshold, network) {
network = network || publicKeys[0].network || Networks.defaultNetwork;
return Address.payingTo(Script.buildMultisigOut(publicKeys, threshold), network);
};
/**
* Internal function to transform a bitcoin cash address string
*
* @param {string} data
* @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
* @param {string=} type - The type: 'pubkeyhash' or 'scripthash'
* @returns {Object} An object with keys: hashBuffer, network and type
* @private
*/ Address._transformString = function(data, network, type) {
if (typeof data !== "string") throw new TypeError("data parameter supplied is not a string.");
if (data.length < 27) throw new Error("Invalid Address string provided");
data = data.trim();
var networkObj = Networks.get(network);
if (network && !networkObj) throw new TypeError("Unknown network");
var addressBuffer = Base58Check.decode(data);
return Address._transformBuffer(addressBuffer, network, type);
};
/**
* Instantiate an address from a PublicKey instance
*
* @param {PublicKey} data
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.fromPublicKey = function(data, network) {
var info = Address._transformPublicKey(data);
network = network || Networks.defaultNetwork;
return new Address(info.hashBuffer, network, info.type);
};
/**
* Instantiate an address from a PrivateKey instance
*
* @param {PrivateKey} privateKey
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.fromPrivateKey = function(privateKey, network) {
let publicKey = PublicKey.fromPrivateKey(privateKey);
network = network || privateKey.network || Networks.defaultNetwork;
return Address.fromPublicKey(publicKey, network);
};
/**
* Instantiate an address from a ripemd160 public key hash
*
* @param {Buffer} hash - An instance of buffer of the hash
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.fromPublicKeyHash = function(hash, network) {
var info = Address._transformHash(hash);
return new Address(info.hashBuffer, network, Address.PayToPublicKeyHash);
};
/**
* Instantiate an address from a ripemd160 script hash
*
* @param {Buffer} hash - An instance of buffer of the hash
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.fromScriptHash = function(hash, network) {
$.checkArgument(hash, "hash parameter is required");
var info = Address._transformHash(hash);
return new Address(info.hashBuffer, network, Address.PayToScriptHash);
};
/**
* Builds a p2sh address paying to script. This will hash the script and
* use that to create the address.
* If you want to extract an address associated with a script instead,
* see {{Address#fromScript}}
*
* @param {Script} script - An instance of Script
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.payingTo = function(script, network) {
$.checkArgument(script, "script is required");
$.checkArgument(script instanceof Script, "script must be instance of Script");
return Address.fromScriptHash(Hash.sha256ripemd160(script.toBuffer()), network);
};
/**
* Extract address from a Script. The script must be of one
* of the following types: p2pkh input, p2pkh output, p2sh input
* or p2sh output.
* This will analyze the script and extract address information from it.
* If you want to transform any script to a p2sh Address paying
* to that script's hash instead, use {{Address#payingTo}}
*
* @param {Script} script - An instance of Script
* @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
* @returns {Address} A new valid and frozen instance of an Address
*/ Address.fromScript = function(script, network) {
$.checkArgu