From b454558fc428905fdd9ed05c4b0f5ad58fb4010e Mon Sep 17 00:00:00 2001 From: loutskiy Date: Tue, 12 Feb 2019 14:43:30 +0300 Subject: [PATCH 01/65] new protocol --- .../project.pbxproj | 8 +- .../Base.lproj/Main.storyboard | 10 +- .../macOS/KeyChain Installer/ProgressVC.swift | 10 +- keychain_cmd_app/cmd_parser.cpp | 3 +- keychain_mac/DialogWC.h | 5 +- keychain_mac/DialogWC.mm | 184 ++- keychain_mac/InfoButton.swift | 103 +- keychain_mac/SelectKeyVC.h | 23 + keychain_mac/SelectKeyVC.mm | 131 ++ keychain_mac/gui_mod_mac.hpp | 27 + keychain_mac/gui_mod_mac.mm | 35 + keychain_mac/sec_mod_mac.hpp | 32 +- keychain_mac/sec_mod_mac.mm | 184 ++- .../KeyManager.xcodeproj/project.pbxproj | 441 +++++++ .../contents.xcworkspacedata | 7 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + .../xcschemes/KeyManager.xcscheme | 92 ++ .../contents.xcworkspacedata | 10 + .../xcshareddata/IDEWorkspaceChecks.plist | 8 + keymanager_mac/KeyManager/AppDelegate.swift | 26 + .../KeyManager/AppleScriptManager.swift | 43 + .../AppIcon.appiconset/Contents.json | 58 + .../KeyManager/Assets.xcassets/Contents.json | 6 + .../logo.imageset/Contents.json | 23 + .../Assets.xcassets/logo.imageset/logo.png | Bin 0 -> 7612 bytes .../Assets.xcassets/logo.imageset/logo@2x.png | Bin 0 -> 15982 bytes .../Assets.xcassets/logo.imageset/logo@3x.png | Bin 0 -> 25618 bytes .../KeyManager/Base.lproj/Main.storyboard | 1156 +++++++++++++++++ keymanager_mac/KeyManager/HexToRgbColor.h | 18 + keymanager_mac/KeyManager/HexToRgbColor.m | 35 + keymanager_mac/KeyManager/Info.plist | 32 + keymanager_mac/KeyManager/KeyFileModel.swift | 69 + .../KeyManager/KeyManager-Bridging-Header.h | 5 + .../KeyManager/KeyManager.entitlements | 10 + keymanager_mac/KeyManager/KeyManager.swift | 60 + .../KeyManager/String+extension.swift | 19 + keymanager_mac/KeyManager/TableRowView.swift | 29 + .../KeyManager/ViewController.swift | 119 ++ .../KeyManager/WebsocketChecker.swift | 26 + keymanager_mac/Podfile | 10 + keymanager_mac/Podfile.lock | 16 + 41 files changed, 2763 insertions(+), 318 deletions(-) create mode 100644 keychain_mac/SelectKeyVC.h create mode 100644 keychain_mac/SelectKeyVC.mm create mode 100644 keychain_mac/gui_mod_mac.hpp create mode 100644 keychain_mac/gui_mod_mac.mm create mode 100644 keymanager_mac/KeyManager.xcodeproj/project.pbxproj create mode 100644 keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata create mode 100644 keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme create mode 100644 keymanager_mac/KeyManager.xcworkspace/contents.xcworkspacedata create mode 100644 keymanager_mac/KeyManager.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist create mode 100644 keymanager_mac/KeyManager/AppDelegate.swift create mode 100644 keymanager_mac/KeyManager/AppleScriptManager.swift create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/AppIcon.appiconset/Contents.json create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/Contents.json create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/Contents.json create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo.png create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@2x.png create mode 100644 keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@3x.png create mode 100644 keymanager_mac/KeyManager/Base.lproj/Main.storyboard create mode 100644 keymanager_mac/KeyManager/HexToRgbColor.h create mode 100644 keymanager_mac/KeyManager/HexToRgbColor.m create mode 100644 keymanager_mac/KeyManager/Info.plist create mode 100644 keymanager_mac/KeyManager/KeyFileModel.swift create mode 100644 keymanager_mac/KeyManager/KeyManager-Bridging-Header.h create mode 100644 keymanager_mac/KeyManager/KeyManager.entitlements create mode 100644 keymanager_mac/KeyManager/KeyManager.swift create mode 100644 keymanager_mac/KeyManager/String+extension.swift create mode 100644 keymanager_mac/KeyManager/TableRowView.swift create mode 100644 keymanager_mac/KeyManager/ViewController.swift create mode 100644 keymanager_mac/KeyManager/WebsocketChecker.swift create mode 100644 keymanager_mac/Podfile create mode 100644 keymanager_mac/Podfile.lock diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index fb1217e..fa1b5db 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -8,10 +8,10 @@ /* Begin PBXBuildFile section */ 065E4561476CAD7D2A088F20 /* Pods_Keychain_Installer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D45CE400EF06130F590AA706 /* Pods_Keychain_Installer.framework */; }; - A774C73A21E60919000F7648 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A774C73921E60919000F7648 /* bin.tar.gz */; }; A776F48D21D0C696006736C9 /* Print.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75B21A6B4A60021ED5E /* Print.swift */; }; A776F48F21D0C92E006736C9 /* UninstallVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F48E21D0C92E006736C9 /* UninstallVC.swift */; }; A776F49021D0D147006736C9 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75721A6B4620021ED5E /* Alerts.swift */; }; + A78BBE432209D4E7007A5BB4 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A78BBE422209D4E7007A5BB4 /* bin.tar.gz */; }; A793A32921C2672B0061249D /* LicenseVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A793A32821C2672B0061249D /* LicenseVC.swift */; }; A799115F21C41AD500CB13B7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A799115E21C41AD500CB13B7 /* AppDelegate.swift */; }; A799116321C41AD500CB13B7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A799116221C41AD500CB13B7 /* Assets.xcassets */; }; @@ -43,8 +43,8 @@ 6FF41F077014844269A8A241 /* Pods-Keychain Uninstaller.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Uninstaller.release.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Uninstaller/Pods-Keychain Uninstaller.release.xcconfig"; sourceTree = ""; }; A0679F4132141184C33311C6 /* Pods-Keychain Installer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Installer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Installer/Pods-Keychain Installer.debug.xcconfig"; sourceTree = ""; }; A1FECE3906833024E5D5394D /* Pods_Keychain_Uninstaller.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Keychain_Uninstaller.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - A774C73921E60919000F7648 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A776F48E21D0C92E006736C9 /* UninstallVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallVC.swift; sourceTree = ""; }; + A78BBE422209D4E7007A5BB4 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A793A32821C2672B0061249D /* LicenseVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseVC.swift; sourceTree = ""; }; A799115C21C41AD500CB13B7 /* Keychain Uninstaller.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Keychain Uninstaller.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A799115E21C41AD500CB13B7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -168,7 +168,7 @@ A7E7F74321A6B0D10021ED5E /* Main.storyboard */, A7E7F74621A6B0D10021ED5E /* Info.plist */, A7E7F74721A6B0D10021ED5E /* Keychain_Installer.entitlements */, - A774C73921E60919000F7648 /* bin.tar.gz */, + A78BBE422209D4E7007A5BB4 /* bin.tar.gz */, ); path = "KeyChain Installer"; sourceTree = ""; @@ -265,7 +265,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - A774C73A21E60919000F7648 /* bin.tar.gz in Resources */, + A78BBE432209D4E7007A5BB4 /* bin.tar.gz in Resources */, A7E7F74221A6B0D10021ED5E /* Assets.xcassets in Resources */, A7E7F74521A6B0D10021ED5E /* Main.storyboard in Resources */, ); diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index 1dd3741..1563b49 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -685,7 +685,7 @@ - + @@ -798,7 +798,7 @@ - + @@ -850,7 +850,7 @@ - + @@ -913,7 +913,7 @@ - + @@ -987,7 +987,7 @@ - + diff --git a/installer/macOS/KeyChain Installer/ProgressVC.swift b/installer/macOS/KeyChain Installer/ProgressVC.swift index f80c090..be338c3 100644 --- a/installer/macOS/KeyChain Installer/ProgressVC.swift +++ b/installer/macOS/KeyChain Installer/ProgressVC.swift @@ -84,8 +84,14 @@ class ProgressVC: NSViewController { print("OK untar") print(dataPath) self.jobWorker(dataPath: dataPath) - self.infoTextField.stringValue = "Installation complete!" - self.installText("Installation complete!") + AppleScriptManager.runScriptWithBody("cp -a '" + dataPath + "/keys/.' /var/keychain/key_data", isAdminRequired: true, success: { + self.infoTextField.stringValue = "Installation complete!" + self.installText("Installation complete!") + }, failure: { (error) in + print("ERROR: \(error)") + self.installText(error.description) + }) + }) { (error) in print("ERROR: \(error)") self.installText(error.description) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 4347d87..7ca6124 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -26,6 +26,7 @@ #ifdef APPLE #include "../keychain_mac/sec_mod_mac.hpp" +#include "../keychain_mac/gui_mod_mac.hpp" #endif #ifdef _WIN32 @@ -85,7 +86,7 @@ int cmd_parser::run(int argc, const char* const argv[]) BOOST_LOG_SEV(log.lg, info) << "secure_module: "; sec_mod = module_singleton::instance(); //TODO: need to implement gui module - gui_mod = module_singleton::instance(); + gui_mod = module_singleton::instance(); # else # ifdef _WIN32 BOOST_LOG_SEV(log.lg, info) << "secure_module: "; diff --git a/keychain_mac/DialogWC.h b/keychain_mac/DialogWC.h index 096b924..bf3b976 100644 --- a/keychain_mac/DialogWC.h +++ b/keychain_mac/DialogWC.h @@ -6,7 +6,7 @@ // #import -//#import "ResponseModel.h" +#include NS_ASSUME_NONNULL_BEGIN @@ -17,6 +17,9 @@ NS_ASSUME_NONNULL_BEGIN @property (nonatomic, strong) NSString *blockhainType; @property (readwrite) BOOL isSignTransaction; @property (readwrite) BOOL isJson; +@property (readwrite) BOOL isRawhash; + @property (readwrite) keychain_app::secmod_commands::events_te etype; + @property keychain_app::secmod_commands::secmod_parser_f parser; @property (readwrite) int unlockTime; @property (nonatomic, strong) NSString *keyname; @property (readwrite) BOOL unlockOnly; diff --git a/keychain_mac/DialogWC.mm b/keychain_mac/DialogWC.mm index 17aacc0..a97eb15 100644 --- a/keychain_mac/DialogWC.mm +++ b/keychain_mac/DialogWC.mm @@ -13,10 +13,11 @@ #include #include #import "FileManager.h" -#include #import "keychain-Swift.h" #import "MiddleAlignedTextFieldCell.h" +using namespace keychain_app; + using keychain_app::secmod_commands::secmod_parser_f; @interface DialogWC () { @@ -95,109 +96,94 @@ - (void)runModal { [self setupLogoBlockhain:self.blockhainType]; [self setupExpertModeButton]; [self setupTitleLabel:[NSString stringWithFormat:@"You are trying to sign a transaction with the key \"%@\". %@", self.keyname, (self.unlockTime > 0) ? @"" : @""]]; - secmod_parser_f cmd_parse; - auto cmd_type = cmd_parse([self.jsonString UTF8String]); - - switch (cmd_type) - { - case keychain_app::secmod_commands::blockchain_secmod_te::unknown: - { - [self.window setTitle:@"Sign hex"]; - [self setupBottomLabel:@"Data"]; - [self setupTextBottomLabel:[NSString stringWithUTF8String:cmd_parse.to_raw_trx_string().c_str()]]; - - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::ethereum: - { - [self.window setTitle:@"Sign transaction"]; - auto eth_trx = cmd_parse.to_ethereum(); - auto eth_data = eth_trx.trx_info; - [self setupBottomLabel:@"To"]; - [self setupFrom]; - [self setupTopLabel:@"Amount"]; - [self setupTextBottomLabel:[NSString stringWithUTF8String:eth_data.to.c_str()]]; - [self setupTextFrom:[NSString stringWithUTF8String:eth_trx.from.c_str()]]; - [self setupTextTopLabel:[NSString stringWithUTF8String:eth_data.value.c_str()]]; - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::bitcoin: - { - [self.window setTitle:@"Sign transaction"]; - if (cmd_parse.is_json()) { - dataForBitcoin = [NSMutableArray new]; - auto btc_trx = cmd_parse.to_bitcoin(); - for (int i = 0; i < btc_trx.trx_info.num_vouts; i++) { - auto vout = btc_trx.trx_info.vouts[i]; - NSDictionary *dict = @{@"key1": [NSString stringWithUTF8String:vout.address.c_str()], @"key2": [NSString stringWithFormat:@"%llu", vout.amount]}; - [dataForBitcoin addObject:dict]; + if (self.etype == secmod_commands::events_te::sign_hash) { + [self.window setTitle:@"Sign hash"]; + isHash = true; + auto cmd = self.parser.params(); + [self setupBottomLabel:@"Hash"]; + [self setupTextBottomLabel:[NSString stringWithUTF8String:cmd.hash.c_str()]]; + [self setupFrom]; + [self setupTextFrom:[NSString stringWithUTF8String:cmd.from.c_str()]]; + } else if (self.etype == secmod_commands::events_te::sign_hex) { + auto cmd = self.parser.params(); + switch (cmd.blockchain) { + case secmod_commands::blockchain_secmod_te::unknown: { + NSLog(@"unknown"); + [self.window setTitle:@"Sign hex"]; + [self setupBottomLabel:@"Data"]; + + [self setupTextBottomLabel:[NSString stringWithUTF8String:cmd.get_trx_view().c_str()]]; + break; + } + case secmod_commands::blockchain_secmod_te::ethereum: { + NSLog(@"ethereum"); + [self.window setTitle:@"Sign transaction"]; + auto eth_trx = cmd.get_trx_view(); + auto eth_data = eth_trx.trx_info; + [self setupBottomLabel:@"To"]; + [self setupFrom]; + [self setupTopLabel:@"Amount"]; + [self setupTextBottomLabel:[NSString stringWithUTF8String:eth_data.to.c_str()]]; + [self setupTextFrom:[NSString stringWithUTF8String:eth_trx.from.c_str()]]; + [self setupTextTopLabel:[NSString stringWithUTF8String:eth_data.value.c_str()]]; + break; + } + case secmod_commands::blockchain_secmod_te::ethereum_swap: { + NSLog(@"ethereum_swap"); + [self.window setTitle:@"Sign transaction"]; + [self setupBottomLabel:@"To"]; + [self setupFrom]; + [self setupTopLabel:@"Amount"]; + + auto swap_trx = cmd.get_trx_view(); + auto swap_info = swap_trx.swap_info; + switch (swap_info.action) + { + case keychain_app::secmod_commands::transaction_view::secmod_command_swap::action_te::create_swap: + [self setupSwapAdditional:@"Hash"]; + [self setupTextSwapAdditional:[NSString stringWithUTF8String:swap_info.hash.c_str()]]; + [self setupTextSwapAction:@"Create Swap"]; + break; + case keychain_app::secmod_commands::transaction_view::secmod_command_swap::action_te::refund: + [self setupSwapAdditional:@""]; + [self setupTextSwapAdditional:@""]; + [self setupTextSwapAction:@"Refund"]; + break; + case keychain_app::secmod_commands::transaction_view::secmod_command_swap::action_te::withdraw: + [self setupSwapAdditional:@"Secret"]; + [self setupTextSwapAdditional:[NSString stringWithUTF8String:swap_info.secret.c_str()]]; + [self setupTextSwapAction:@"Withdraw"]; + break; } - [self setupSwapAddress:@"From"]; - [self setupTextSwapAddress:[NSString stringWithUTF8String:btc_trx.from.c_str()]]; - [self createTableView]; + auto eth_data = swap_trx.trx_info; + [self setupTextBottomLabel:[NSString stringWithUTF8String:eth_data.to.c_str()]]; + [self setupTextFrom:[NSString stringWithUTF8String:swap_trx.from.c_str()]]; + [self setupTextTopLabel:[NSString stringWithUTF8String:eth_data.value.c_str()]]; + [self setupSwapAddress:@"Address"]; + [self setupSwapAction]; + [self setupLogoSwap]; + [self setupTextSwapAddress:[NSString stringWithUTF8String:swap_info.address.c_str()]]; + break; } - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::rawhash: - { - [self.window setTitle:@"Sign hash"]; - isHash = true; - auto raw_cmd = cmd_parse.to_rawhash(); - [self setupBottomLabel:@"Hash"]; - [self setupTextBottomLabel:[NSString stringWithUTF8String:raw_cmd.hash.c_str()]]; - [self setupFrom]; - [self setupTextFrom:[NSString stringWithUTF8String:raw_cmd.from.c_str()]]; - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap: - { - [self.window setTitle:@"Sign transaction"]; - [self setupBottomLabel:@"To"]; - [self setupFrom]; - [self setupTopLabel:@"Amount"]; - - auto swap_trx = cmd_parse.to_ethereum_swap(); - auto swap_info = swap_trx.swap_info; - switch (swap_info.action) - { - case keychain_app::secmod_commands::secmod_command::secmod_command_swap::action_te::create_swap: - [self setupSwapAdditional:@"Hash"]; - [self setupTextSwapAdditional:[NSString stringWithUTF8String:swap_info.hash.c_str()]]; - [self setupTextSwapAction:@"Create Swap"]; - break; - case keychain_app::secmod_commands::secmod_command::secmod_command_swap::action_te::refund: - [self setupSwapAdditional:@""]; - [self setupTextSwapAdditional:@""]; - [self setupTextSwapAction:@"Refund"]; - break; - case keychain_app::secmod_commands::secmod_command::secmod_command_swap::action_te::withdraw: - [self setupSwapAdditional:@"Secret"]; - [self setupTextSwapAdditional:[NSString stringWithUTF8String:swap_info.secret.c_str()]]; - [self setupTextSwapAction:@"Withdraw"]; - break; + case secmod_commands::blockchain_secmod_te::bitcoin: { + NSLog(@"bitcoin"); + [self.window setTitle:@"Sign transaction"]; + if (cmd.is_parsed) { + dataForBitcoin = [NSMutableArray new]; + auto btc_trx = cmd.get_trx_view(); + for (int i = 0; i < btc_trx.trx_info.num_vouts; i++) { + auto vout = btc_trx.trx_info.vouts[i]; + NSDictionary *dict = @{@"key1": [NSString stringWithUTF8String:vout.address.c_str()], @"key2": [NSString stringWithFormat:@"%llu", vout.amount]}; + [dataForBitcoin addObject:dict]; + } + [self setupSwapAddress:@"From"]; + [self setupTextSwapAddress:[NSString stringWithUTF8String:btc_trx.from.c_str()]]; + [self createTableView]; + } + break; } - auto eth_data = swap_trx.trx_info; - [self setupTextBottomLabel:[NSString stringWithUTF8String:eth_data.to.c_str()]]; - [self setupTextFrom:[NSString stringWithUTF8String:swap_trx.from.c_str()]]; - [self setupTextTopLabel:[NSString stringWithUTF8String:eth_data.value.c_str()]]; - [self setupSwapAddress:@"Address"]; - [self setupSwapAction]; - [self setupLogoSwap]; - [self setupTextSwapAddress:[NSString stringWithUTF8String:swap_info.address.c_str()]]; - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::parse_error: - { - - } - break; - default: - { - } - break; } -// [self checkForRedLock]; } else { [self.window setTitle:@"Create password"]; [self setupTitleLabel:@"Enter the password for the new key"]; diff --git a/keychain_mac/InfoButton.swift b/keychain_mac/InfoButton.swift index ec1bf47..8a35226 100755 --- a/keychain_mac/InfoButton.swift +++ b/keychain_mac/InfoButton.swift @@ -9,106 +9,6 @@ import Foundation import Cocoa -/* -@IBDesignable -open class InfoButton : NSControl, NSPopoverDelegate { - var mainSize: CGFloat! - - @IBInspectable var showOnHover: Bool = false - @IBInspectable var fillMode: Bool = true - @IBInspectable var animatePopover: Bool = false - @IBInspectable var content: String = "" - @IBInspectable var primaryColor: NSColor = NSColor.scrollBarColor - var secondaryColor: NSColor = NSColor.white - - var mouseInside = false { - didSet { - self.needsDisplay = true - if showOnHover { - if popover == nil { - popover = NSPopover(content: self.content, doesAnimate: self.animatePopover) - } - if mouseInside { - popover.show(relativeTo: self.frame, of: self.superview!, preferredEdge: NSRectEdge.maxX) - } else { - popover.close() - } - - } - } - } - - var trackingArea: NSTrackingArea! - override open func updateTrackingAreas() { - super.updateTrackingAreas() - if trackingArea != nil { - self.removeTrackingArea(trackingArea) - } - trackingArea = NSTrackingArea(rect: self.bounds, options: [NSTrackingArea.Options.mouseEnteredAndExited, NSTrackingArea.Options.activeAlways], owner: self, userInfo: nil) - self.addTrackingArea(trackingArea) - } - - fileprivate var stringAttributeDict = [String: AnyObject]() - fileprivate var circlePath: NSBezierPath! - - var popover: NSPopover! - - - required public init?(coder: NSCoder) { - super.init(coder: coder) - let frameSize = self.frame.size - if frameSize.width != frameSize.height { - self.frame.size.height = self.frame.size.width - } - self.mainSize = self.frame.size.height - stringAttributeDict[NSFontAttributeName] = NSFont.systemFont(ofSize: mainSize * 0.6) - - let inSet: CGFloat = 2 - let rect = NSMakeRect(inSet, inSet, mainSize - inSet * 2, mainSize - inSet * 2) - circlePath = NSBezierPath(ovalIn: rect) - } - - - override open func draw(_ dirtyRect: NSRect) { - var activeColor: NSColor! - if mouseInside || (popover != nil && popover!.isShown){ - activeColor = primaryColor - } else { - activeColor = primaryColor.withAlphaComponent(0.35) - } - - if fillMode { - activeColor.setFill() - circlePath.fill() - stringAttributeDict[NSForegroundColorAttributeName] = secondaryColor - } else { - activeColor.setStroke() - circlePath.stroke() - stringAttributeDict[NSForegroundColorAttributeName] = (mouseInside ? primaryColor : primaryColor.withAlphaComponent(0.35)) - } - - let attributedString = NSAttributedString(string: "?", attributes: stringAttributeDict) - let stringLocation = NSMakePoint(mainSize / 2 - attributedString.size().width / 2, mainSize / 2 - attributedString.size().height / 2) - attributedString.draw(at: stringLocation) - } - - override open func mouseDown(with theEvent: NSEvent) { - if popover == nil { - popover = NSPopover(content: self.content, doesAnimate: self.animatePopover) - } - if popover.isShown { - popover.close() - } else { - popover.show(relativeTo: self.frame, of: self.superview!, preferredEdge: NSRectEdge.maxX) - } - } - - override open func mouseEntered(with theEvent: NSEvent) { mouseInside = true } - override open func mouseExited(with theEvent: NSEvent) { mouseInside = false } - -} -*/ - //MARK: Extension for making a popover from string @objc extension NSPopover { @@ -135,7 +35,8 @@ open class InfoButton : NSControl, NSPopoverDelegate { }(content) self.contentViewController!.view.addSubview(textField) - var viewSize = textField.frame.size; viewSize.width += (popoverMargin * 2); viewSize.height += (popoverMargin * 2) + var viewSize = textField.frame.size; + viewSize.width += (popoverMargin * 2); viewSize.height += (popoverMargin * 2) self.contentSize = viewSize } diff --git a/keychain_mac/SelectKeyVC.h b/keychain_mac/SelectKeyVC.h new file mode 100644 index 0000000..635e77a --- /dev/null +++ b/keychain_mac/SelectKeyVC.h @@ -0,0 +1,23 @@ +// +// SelectKeyVC.h +// keychain +// +// Created by Mikhail Lutskiy on 05/02/2019. +// + +#import +#include + +NS_ASSUME_NONNULL_BEGIN + +@interface SelectKeyVC : NSWindowController + +//@property keychain_app::keyfile_singleton keyfiles; + +- (instancetype)initWithFrame:(NSRect)frame; +- (void)runModal; + + +@end + +NS_ASSUME_NONNULL_END diff --git a/keychain_mac/SelectKeyVC.mm b/keychain_mac/SelectKeyVC.mm new file mode 100644 index 0000000..98ef18e --- /dev/null +++ b/keychain_mac/SelectKeyVC.mm @@ -0,0 +1,131 @@ +// +// SelectKeyVC.m +// keychain +// +// Created by Mikhail Lutskiy on 05/02/2019. +// + +#import "SelectKeyVC.h" +#import "MiddleAlignedTextFieldCell.h" + +@interface SelectKeyVC () + +@end + +@implementation SelectKeyVC + +- (instancetype)initWithFrame:(NSRect)frame { + NSWindowStyleMask windowMask = NSWindowStyleMaskTitled | NSWindowStyleMaskFullSizeContentView | NSWindowStyleMaskClosable; + NSWindow *window = [[NSWindow alloc] initWithContentRect:frame + styleMask:windowMask + backing:NSBackingStoreBuffered + defer:NO]; + [window setTitle:@"KeyChain"]; + [window makeKeyAndOrderFront:self]; + [window orderFront:self]; + + [NSNotificationCenter.defaultCenter addObserver:self + selector:@selector(windowWillClose:) + name:NSWindowWillCloseNotification + object:nil]; + window.titlebarAppearsTransparent = YES; + //window.titleVisibility = NSWindowTitleHidden; + window.backgroundColor = [NSColor whiteColor]; + [window center]; + return [super initWithWindow:window]; +} + +- (void)windowDidLoad { + [super windowDidLoad]; + + // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. +} + +- (void)windowWillClose:(NSNotification *)notification { + [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; + dispatch_async(dispatch_get_main_queue(), ^{ + [NSApp stopModal]; + }); +} + +- (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex + { + // NSString *aString = [NSString stringWithFormat:@"%@, Row %ld",[aTableColumn identifier],(long)rowIndex]; + NSString *aString; +// aString = [[dataForBitcoin objectAtIndex:rowIndex] objectForKey:[aTableColumn identifier]]; + return aString; + } + + // TableView Datasource method implementation +- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView + { + //we have only one table in the screen and thus we are not checking the row count based on the target table view + // long recordCount = [self.dataArray count]; + return keyfile_singleton::instance(); + } + +- (void)runModal { + NSVisualEffectView *cover = [[NSVisualEffectView alloc] initWithFrame:NSMakeRect(0, 0, self.window.frame.size.width, self.window.frame.size.height - 91)]; + cover.blendingMode = NSVisualEffectBlendingModeBehindWindow; + cover.material = NSVisualEffectMaterialAppearanceBased; + cover.state = NSVisualEffectStateFollowsWindowActiveState; + [cover setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantLight]]; + [self.window.contentView addSubview:cover]; + + + [[NSApplication sharedApplication] runModalForWindow:self.window]; + + [self.window setFrame:NSMakeRect(0, 0, 575, 500) display:true]; +} + +- (void) createTableView { + NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(22, 110, self.window.frame.size.width - 44, 150)]; + scrollView.backgroundColor = [NSColor clearColor]; + [scrollView setBorderType:NSBezelBorder]; + + NSTableView *tableView = [[NSTableView alloc] initWithFrame:scrollView.bounds]; + tableView.rowSizeStyle = NSTableViewRowSizeStyleLarge; + tableView.backgroundColor = [NSColor clearColor]; + tableView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; + + NSTableColumn *tCol; + + tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key1"]]; + id cell = [tCol dataCell]; + [cell setFont: [NSFont systemFontOfSize:18]]; + [[tCol headerCell] setStringValue:@"To"]; + [tCol setWidth:self.window.frame.size.width - 149]; + tCol.editable = false; + [[tCol dataCell] setVerticalCentering:YES]; + [tableView addTableColumn:tCol]; + + tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key2"]]; + cell = [tCol dataCell]; + [cell setFont: [NSFont systemFontOfSize:18]]; + [[tCol headerCell] setStringValue:@"Amount"]; + [tCol setWidth:100]; + tCol.editable = false; + [[tCol dataCell] setVerticalCentering:YES]; + [tableView addTableColumn:tCol]; + + [tableView setUsesAlternatingRowBackgroundColors:YES]; + [tableView setGridStyleMask:NSTableViewSolidVerticalGridLineMask]; + [tableView setRowHeight:23.0]; + [tableView setDelegate:self]; + [tableView setDataSource:self]; + [tableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone]; + [tableView setAutoresizesSubviews:YES]; + + scrollView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; + [scrollView setHasVerticalScroller:YES]; + [scrollView setHasHorizontalScroller:NO]; + scrollView.horizontalScrollElasticity = NSScrollElasticityNone; + [scrollView setAutoresizesSubviews:YES]; + [scrollView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable]; + [scrollView setAutohidesScrollers:false]; + [scrollView setScrollerStyle:NSScrollerStyleLegacy]; + [scrollView setDocumentView:tableView]; + [self.window.contentView addSubview:scrollView]; +} + +@end diff --git a/keychain_mac/gui_mod_mac.hpp b/keychain_mac/gui_mod_mac.hpp new file mode 100644 index 0000000..942c43d --- /dev/null +++ b/keychain_mac/gui_mod_mac.hpp @@ -0,0 +1,27 @@ +// +// gui_mod_mac.hpp +// keychain +// +// Created by Mikhail Lutskiy on 28/01/2019. +// + +#ifndef gui_mod_mac_h +#define gui_mod_mac_h + +#include + +namespace keychain_app +{ + + class gui_mod_mac: public gui_mod_base + { + public: + gui_mod_mac(); + virtual ~gui_mod_mac(); + virtual dev::Public select_key() const override; + }; + +} + + +#endif /* gui_mod_mac_h */ diff --git a/keychain_mac/gui_mod_mac.mm b/keychain_mac/gui_mod_mac.mm new file mode 100644 index 0000000..0828245 --- /dev/null +++ b/keychain_mac/gui_mod_mac.mm @@ -0,0 +1,35 @@ +// +// gui_mod_mac.m +// keychain +// +// Created by Mikhail Lutskiy on 28/01/2019. +// + +#import "gui_mod_mac.hpp" +#import "SelectKeyVC.h" +#import +#import "ApplicationShared.h" + +using namespace keychain_app; + +gui_mod_mac::gui_mod_mac() +{} + +gui_mod_mac::~gui_mod_mac() +{} + +dev::Public gui_mod_mac::select_key() const +{ + [ApplicationShared sharedInstance]; + NSRect frame = NSMakeRect(0, 0, 500, 521); + + auto& keyfiles = keyfile_singleton::instance(); + auto it = keyfiles.begin(); + if ( it==keyfiles.end() ) + return dev::Public(); + + SelectKeyVC *dialog = [[SelectKeyVC alloc] initWithFrame:frame]; + [dialog runModal]; + + return it->keyinfo.public_key; +} diff --git a/keychain_mac/sec_mod_mac.hpp b/keychain_mac/sec_mod_mac.hpp index 425758c..9710a20 100644 --- a/keychain_mac/sec_mod_mac.hpp +++ b/keychain_mac/sec_mod_mac.hpp @@ -8,7 +8,7 @@ //#ifndef sec_mod_mac_hpp //#define sec_mod_mac_hpp -#include +#include namespace keychain_app { @@ -18,19 +18,33 @@ namespace keychain_app public: sec_mod_mac(); virtual ~sec_mod_mac(); - virtual keychain_app::byte_seq_t get_passwd_trx(const std::string& raw_trx) const override; - virtual keychain_app::byte_seq_t get_passwd_unlock(const std::string& keyname, int unlock_time) const override; - virtual keychain_app::byte_seq_t get_passwd_on_create() const override; - virtual void print_mnemonic(const string_list& mnemonic) const override; - -// virtual keychain_app::byte_seq_t get_passwd_trx_raw(const std::string& raw_trx) const override; -// virtual keychain_app::byte_seq_t get_passwd_on_create() const override; -// virtual void print_mnemonic(const string_list& mnemonic) const override; + virtual std::string exec_cmd(const std::string& json_cmd) const override; private: static constexpr const char* pass_str = "blank_password"; }; } +//#include +// +//namespace keychain_app +//{ +// +// class sec_mod_mac: public secure_dlg_mod_base +// { +// public: +// sec_mod_mac(); +// virtual ~sec_mod_mac(); +// +// virtual keychain_app::byte_seq_t get_passwd_trx(const std::string& raw_trx) const override; +// virtual keychain_app::byte_seq_t get_passwd_unlock(const std::string& keyname, int unlock_time) const override; +// virtual keychain_app::byte_seq_t get_passwd_on_create(const std::string& keyname = std::string("") ) const override; +// virtual void print_mnemonic(const string_list& mnemonic) const override; +// private: +// static constexpr const char* pass_str = "blank_password"; +// }; +// +//} + //#endif //KEYCHAINAPP_SEC_MOD_LINUX_HPP //#endif diff --git a/keychain_mac/sec_mod_mac.mm b/keychain_mac/sec_mod_mac.mm index dfca2de..7dda50a 100644 --- a/keychain_mac/sec_mod_mac.mm +++ b/keychain_mac/sec_mod_mac.mm @@ -18,7 +18,6 @@ #include using namespace keychain_app; -using secmod_commands::secmod_parser_f; sec_mod_mac::sec_mod_mac() {} @@ -28,121 +27,114 @@ bfs::path get_path(); - -void sec_mod_mac::print_mnemonic(const string_list& mnemonic) const -{ -} - -keychain_app::byte_seq_t keychain_app::sec_mod_mac::get_passwd_unlock(const std::string& keyname, int unlock_time) const -{ - NSLog(@"get_passwd_unlock"); - [ApplicationShared sharedInstance]; - NSRect frame = NSMakeRect(0, 0, 575, 210); - - DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; - dialog.isSignTransaction = false; - dialog.unlockTime = unlock_time; - dialog.keyname = [NSString stringWithUTF8String:keyname.c_str()]; - dialog.unlockOnly = true; - [dialog runModal]; - - std::string str = std::string([[[PassSyncStore sharedInstance] pass] UTF8String]); - [[PassSyncStore sharedInstance] setPass:@""]; - keychain_app::byte_seq_t pass(str.begin(), str.end()); - return pass; -} - - -byte_seq_t sec_mod_mac::get_passwd_trx(const std::string& raw_trx) const +std::string keychain_app::sec_mod_mac::exec_cmd(const std::string& json_cmd) const { auto& log = logger_singleton::instance(); - NSLog(@"get_passwd_trx"); [ApplicationShared sharedInstance]; NSRect frame; - - secmod_parser_f cmd_parse; - auto cmd_type = cmd_parse(raw_trx); - - auto unlock_time = cmd_parse.unlock_time(); //check unlock time. If unlock time > 0 print red lock icon with text warning. - auto is_json = cmd_parse.is_json();//need to check parse success. If json is false > 0 print red lock icon with text warning. + BOOST_LOG_SEV(log.lg, info) << "Send to secmod mac:" + json_cmd; + secmod_commands::secmod_parser_f parser; + auto etype = parser(json_cmd); + int unlock_time = 0; + bool is_json = true; std::string blockhain_type; - NSLog(@"cmd_type %d", cmd_type); - switch (cmd_type) + switch (etype) { - case keychain_app::secmod_commands::blockchain_secmod_te::unknown: - { - frame = NSMakeRect(0, 0, 575, 245); - blockhain_type = "unknow"; - } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::ethereum: - { - frame = NSMakeRect(0, 0, 575, 361); - blockhain_type = "ethereum"; - } + case secmod_commands::events_te::sign_hex: { + NSLog(@"sign_hex"); + auto cmd = parser.params(); + is_json = cmd.is_parsed; + switch (cmd.blockchain) { + case secmod_commands::blockchain_secmod_te::unknown: { + NSLog(@"unknown"); + frame = NSMakeRect(0, 0, 575, 245); + blockhain_type = "unknow"; + break; + } + case secmod_commands::blockchain_secmod_te::ethereum: { + NSLog(@"ethereum"); + frame = NSMakeRect(0, 0, 575, 361); + blockhain_type = "ethereum"; + break; + } + case secmod_commands::blockchain_secmod_te::ethereum_swap: { + NSLog(@"ethereum_swap"); + blockhain_type = "ethereum"; + frame = NSMakeRect(0, 0, 825, 521); + break; + } + case secmod_commands::blockchain_secmod_te::bitcoin: { + NSLog(@"bitcoin_sec"); + frame = NSMakeRect(0, 0, 575, is_json ? 440 : 240); + blockhain_type = "bitcoin"; + break; + } + } + + DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; + dialog.jsonString = [NSString stringWithUTF8String:json_cmd.c_str()]; + dialog.isJson = is_json; + dialog.unlockTime = unlock_time; + dialog.unlockOnly = false; + dialog.isSignTransaction = true; + dialog.isRawhash = false; + dialog.etype = etype; + dialog.keyname = [NSString stringWithUTF8String:cmd.keyname.c_str()]; + dialog.parser = parser; + dialog.expertModeString = [NSString stringWithUTF8String:keychain_app::secmod_commands::to_expert_mode_string(cmd).c_str()]; + dialog.blockhainType = [NSString stringWithUTF8String:blockhain_type.c_str()]; + [dialog runModal]; break; - case keychain_app::secmod_commands::blockchain_secmod_te::bitcoin: - { - frame = NSMakeRect(0, 0, 575, is_json ? 440 : 240); - blockhain_type = "bitcoin"; } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::rawhash: - { + case secmod_commands::events_te::sign_hash: { + auto cmd = parser.params(); frame = NSMakeRect(0, 0, 1024, 285); blockhain_type = "hash"; - } + DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; + dialog.jsonString = [NSString stringWithUTF8String:json_cmd.c_str()]; + dialog.isJson = false; + dialog.unlockTime = unlock_time; + dialog.unlockOnly = false; + dialog.isSignTransaction = true; + dialog.keyname = [NSString stringWithUTF8String:cmd.keyname.c_str()]; + dialog.isRawhash = true; + dialog.etype = etype; + dialog.parser = parser; + dialog.expertModeString = [NSString stringWithUTF8String:cmd.hash.c_str()]; + dialog.blockhainType = [NSString stringWithUTF8String:blockhain_type.c_str()]; + [dialog runModal]; break; - case keychain_app::secmod_commands::blockchain_secmod_te::ethereum_swap: - { - blockhain_type = "ethereum"; - frame = NSMakeRect(0, 0, 825, 521); } - break; - case keychain_app::secmod_commands::blockchain_secmod_te::parse_error: + case secmod_commands::events_te::unlock: { - NSLog(@"PARSE_ERROR. Code -1."); - BOOST_LOG_SEV(log.lg, info) << "PARSE_ERROR. Code -1."; - std::string str = std::string([[NSString new] UTF8String]); - keychain_app::byte_seq_t pass(str.begin(), str.end()); - return pass; - } + NSLog(@"unlock"); + auto cmd = parser.params(); + unlock_time = cmd.unlock_time; + frame = NSMakeRect(0, 0, 575, 210); + + DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; + dialog.isSignTransaction = true; + dialog.unlockTime = unlock_time; + dialog.keyname = [NSString stringWithUTF8String:cmd.keyname.c_str()]; + dialog.unlockOnly = true; + dialog.isRawhash = false; + dialog.parser = parser; + dialog.etype = etype; + [dialog runModal]; break; + } default: { - frame = NSMakeRect(0, 0, 575, 361); - blockhain_type = ""; + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Secmod command is not implemented, etype = %{ETYPE}", ("ETYPE", etype)); } - break; } - DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; - dialog.jsonString = [NSString stringWithUTF8String:raw_trx.c_str()]; - dialog.isJson = is_json; - dialog.unlockTime = unlock_time; - dialog.unlockOnly = false; - dialog.isSignTransaction = true; - dialog.keyname = [NSString stringWithUTF8String:cmd_parse.keyname().c_str()]; - dialog.expertModeString = [NSString stringWithUTF8String:cmd_parse.to_expert_mode_string().c_str()]; - dialog.blockhainType = [NSString stringWithUTF8String:blockhain_type.c_str()]; - [dialog runModal]; - std::string str = std::string([[[PassSyncStore sharedInstance] pass] UTF8String]); - [[PassSyncStore sharedInstance] setPass:@""]; keychain_app::byte_seq_t pass(str.begin(), str.end()); - return pass; -} - -byte_seq_t sec_mod_mac::get_passwd_on_create() const -{ - [ApplicationShared sharedInstance]; - NSRect frame = NSMakeRect(0, 0, 575, 300); - DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; - dialog.isSignTransaction = false; - [dialog runModal]; - - std::string str = std::string([[[PassSyncStore sharedInstance] pass] UTF8String]); [[PassSyncStore sharedInstance] setPass:@""]; - keychain_app::byte_seq_t pass(str.begin(), str.end()); - return pass; + + secmod_commands::secmod_resonse_common response; + response.etype = secmod_commands::response_te::password; + response.params = pass; + return fc_light::json::to_pretty_string(fc_light::variant(response)); } diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj new file mode 100644 index 0000000..48d1404 --- /dev/null +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -0,0 +1,441 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F49F21D0DD95006736C9 /* AppDelegate.swift */; }; + A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4A121D0DD95006736C9 /* ViewController.swift */; }; + A776F4A421D0DD97006736C9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A776F4A321D0DD97006736C9 /* Assets.xcassets */; }; + A776F4A721D0DD97006736C9 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A776F4A521D0DD97006736C9 /* Main.storyboard */; }; + A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */; }; + A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B121D0E66B006736C9 /* KeyManager.swift */; }; + A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B721D39AB7006736C9 /* String+extension.swift */; }; + A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */; }; + A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */; }; + A79F78BA21F89D0400E2C184 /* HexToRgbColor.m in Sources */ = {isa = PBXBuildFile; fileRef = A79F78B921F89D0400E2C184 /* HexToRgbColor.m */; }; + A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79F78BB21F8A17900E2C184 /* TableRowView.swift */; }; + AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 130888C1592515A58F013398 /* Pods_KeyManager.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXFileReference section */ + 130888C1592515A58F013398 /* Pods_KeyManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_KeyManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 188A215C60F625DB886DF7B7 /* Pods-KeyManager.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KeyManager.release.xcconfig"; path = "Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager.release.xcconfig"; sourceTree = ""; }; + 9E7F5FE43CEBFF8FE8BEDA2F /* Pods-KeyManager.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KeyManager.debug.xcconfig"; path = "Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager.debug.xcconfig"; sourceTree = ""; }; + A776F49C21D0DD95006736C9 /* KeyManager.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KeyManager.app; sourceTree = BUILT_PRODUCTS_DIR; }; + A776F49F21D0DD95006736C9 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + A776F4A121D0DD95006736C9 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; + A776F4A321D0DD97006736C9 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + A776F4A621D0DD97006736C9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + A776F4A821D0DD97006736C9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + A776F4A921D0DD97006736C9 /* KeyManager.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = KeyManager.entitlements; sourceTree = ""; }; + A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyFileModel.swift; sourceTree = ""; }; + A776F4B121D0E66B006736C9 /* KeyManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyManager.swift; sourceTree = ""; }; + A776F4B721D39AB7006736C9 /* String+extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+extension.swift"; sourceTree = ""; }; + A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppleScriptManager.swift; sourceTree = ""; }; + A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebsocketChecker.swift; sourceTree = ""; }; + A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "KeyManager-Bridging-Header.h"; sourceTree = ""; }; + A79F78B821F89D0400E2C184 /* HexToRgbColor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HexToRgbColor.h; sourceTree = ""; }; + A79F78B921F89D0400E2C184 /* HexToRgbColor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HexToRgbColor.m; sourceTree = ""; }; + A79F78BB21F8A17900E2C184 /* TableRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRowView.swift; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + A776F49921D0DD95006736C9 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 368A9D57B9DB04311291C1BB /* Pods */ = { + isa = PBXGroup; + children = ( + 9E7F5FE43CEBFF8FE8BEDA2F /* Pods-KeyManager.debug.xcconfig */, + 188A215C60F625DB886DF7B7 /* Pods-KeyManager.release.xcconfig */, + ); + name = Pods; + sourceTree = ""; + }; + A776F49321D0DD95006736C9 = { + isa = PBXGroup; + children = ( + A776F49E21D0DD95006736C9 /* KeyManager */, + A776F49D21D0DD95006736C9 /* Products */, + 368A9D57B9DB04311291C1BB /* Pods */, + F73689D206923AF1FA7A3A0E /* Frameworks */, + ); + sourceTree = ""; + }; + A776F49D21D0DD95006736C9 /* Products */ = { + isa = PBXGroup; + children = ( + A776F49C21D0DD95006736C9 /* KeyManager.app */, + ); + name = Products; + sourceTree = ""; + }; + A776F49E21D0DD95006736C9 /* KeyManager */ = { + isa = PBXGroup; + children = ( + A776F49F21D0DD95006736C9 /* AppDelegate.swift */, + A776F4A121D0DD95006736C9 /* ViewController.swift */, + A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */, + A79F78BB21F8A17900E2C184 /* TableRowView.swift */, + A776F4A321D0DD97006736C9 /* Assets.xcassets */, + A776F4A521D0DD97006736C9 /* Main.storyboard */, + A776F4A821D0DD97006736C9 /* Info.plist */, + A776F4A921D0DD97006736C9 /* KeyManager.entitlements */, + A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */, + A776F4B121D0E66B006736C9 /* KeyManager.swift */, + A776F4B721D39AB7006736C9 /* String+extension.swift */, + A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */, + A79F78B821F89D0400E2C184 /* HexToRgbColor.h */, + A79F78B921F89D0400E2C184 /* HexToRgbColor.m */, + A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */, + ); + path = KeyManager; + sourceTree = ""; + }; + F73689D206923AF1FA7A3A0E /* Frameworks */ = { + isa = PBXGroup; + children = ( + 130888C1592515A58F013398 /* Pods_KeyManager.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + A776F49B21D0DD95006736C9 /* KeyManager */ = { + isa = PBXNativeTarget; + buildConfigurationList = A776F4AC21D0DD97006736C9 /* Build configuration list for PBXNativeTarget "KeyManager" */; + buildPhases = ( + 4DAB4937D96294647D1C4E6F /* [CP] Check Pods Manifest.lock */, + A776F49821D0DD95006736C9 /* Sources */, + A776F49921D0DD95006736C9 /* Frameworks */, + A776F49A21D0DD95006736C9 /* Resources */, + 4E78683ECFE60E4C180EB408 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = KeyManager; + productName = KeyManager; + productReference = A776F49C21D0DD95006736C9 /* KeyManager.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + A776F49421D0DD95006736C9 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 1010; + LastUpgradeCheck = 1010; + ORGANIZATIONNAME = "Mikhail Lutskii"; + TargetAttributes = { + A776F49B21D0DD95006736C9 = { + CreatedOnToolsVersion = 10.1; + LastSwiftMigration = 1010; + }; + }; + }; + buildConfigurationList = A776F49721D0DD95006736C9 /* Build configuration list for PBXProject "KeyManager" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = A776F49321D0DD95006736C9; + productRefGroup = A776F49D21D0DD95006736C9 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + A776F49B21D0DD95006736C9 /* KeyManager */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + A776F49A21D0DD95006736C9 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A776F4A421D0DD97006736C9 /* Assets.xcassets in Resources */, + A776F4A721D0DD97006736C9 /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 4DAB4937D96294647D1C4E6F /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-KeyManager-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 4E78683ECFE60E4C180EB408 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + "${SRCROOT}/Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager-frameworks.sh", + "${BUILT_PRODUCTS_DIR}/ObjectMapper/ObjectMapper.framework", + ); + name = "[CP] Embed Pods Frameworks"; + outputPaths = ( + "${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}/ObjectMapper.framework", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + A776F49821D0DD95006736C9 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */, + A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */, + A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */, + A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */, + A79F78BA21F89D0400E2C184 /* HexToRgbColor.m in Sources */, + A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */, + A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */, + A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */, + A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + A776F4A521D0DD97006736C9 /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + A776F4A621D0DD97006736C9 /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + A776F4AA21D0DD97006736C9 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "Mac Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; + MTL_FAST_MATH = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + A776F4AB21D0DD97006736C9 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_ENABLE_OBJC_WEAK = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + CODE_SIGN_IDENTITY = "Mac Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.14; + MTL_ENABLE_DEBUG_INFO = NO; + MTL_FAST_MATH = YES; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + A776F4AD21D0DD97006736C9 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9E7F5FE43CEBFF8FE8BEDA2F /* Pods-KeyManager.debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = KeyManager/KeyManager.entitlements; + CODE_SIGN_IDENTITY = "Mac Developer"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + DEVELOPMENT_TEAM = 8YBKQD6YZD; + INFOPLIST_FILE = KeyManager/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OBJC_BRIDGING_HEADER = "KeyManager/KeyManager-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 4.2; + }; + name = Debug; + }; + A776F4AE21D0DD97006736C9 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 188A215C60F625DB886DF7B7 /* Pods-KeyManager.release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = KeyManager/KeyManager.entitlements; + CODE_SIGN_IDENTITY = "Mac Developer"; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + DEVELOPMENT_TEAM = 8YBKQD6YZD; + INFOPLIST_FILE = KeyManager/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; + PRODUCT_NAME = "$(TARGET_NAME)"; + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OBJC_BRIDGING_HEADER = "KeyManager/KeyManager-Bridging-Header.h"; + SWIFT_VERSION = 4.2; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + A776F49721D0DD95006736C9 /* Build configuration list for PBXProject "KeyManager" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A776F4AA21D0DD97006736C9 /* Debug */, + A776F4AB21D0DD97006736C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + A776F4AC21D0DD97006736C9 /* Build configuration list for PBXNativeTarget "KeyManager" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + A776F4AD21D0DD97006736C9 /* Debug */, + A776F4AE21D0DD97006736C9 /* Release */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = A776F49421D0DD95006736C9 /* Project object */; +} diff --git a/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..c47c419 --- /dev/null +++ b/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/keymanager_mac/KeyManager.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme b/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme new file mode 100644 index 0000000..04aaa28 --- /dev/null +++ b/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme @@ -0,0 +1,92 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/keymanager_mac/KeyManager.xcworkspace/contents.xcworkspacedata b/keymanager_mac/KeyManager.xcworkspace/contents.xcworkspacedata new file mode 100644 index 0000000..0b8f9d6 --- /dev/null +++ b/keymanager_mac/KeyManager.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/keymanager_mac/KeyManager.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/keymanager_mac/KeyManager.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 0000000..18d9810 --- /dev/null +++ b/keymanager_mac/KeyManager.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/keymanager_mac/KeyManager/AppDelegate.swift b/keymanager_mac/KeyManager/AppDelegate.swift new file mode 100644 index 0000000..e67b3b7 --- /dev/null +++ b/keymanager_mac/KeyManager/AppDelegate.swift @@ -0,0 +1,26 @@ +// +// AppDelegate.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 24/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Cocoa + +@NSApplicationMain +class AppDelegate: NSObject, NSApplicationDelegate { + + + + func applicationDidFinishLaunching(_ aNotification: Notification) { + // Insert code here to initialize your application + } + + func applicationWillTerminate(_ aNotification: Notification) { + // Insert code here to tear down your application + } + + +} + diff --git a/keymanager_mac/KeyManager/AppleScriptManager.swift b/keymanager_mac/KeyManager/AppleScriptManager.swift new file mode 100644 index 0000000..0ea2cee --- /dev/null +++ b/keymanager_mac/KeyManager/AppleScriptManager.swift @@ -0,0 +1,43 @@ +// +// AppleScriptManager.swift +// Keychain Installer +// +// Created by Mikhail Lutskiy on 22/11/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Foundation + +class AppleScriptManager { + + /// Function for call apple script (execute shell commands) + /// + /// - Returns: return success or failure block + static func runScriptWithBody(_ body: String, isAdminRequired: Bool = false, success: @escaping() -> Void = {}, failure: @escaping(_ error: NSDictionary) -> Void = {error in }) { +// let script = NSAppleScript(source: "do shell script \"" + body + "\"") +// var errorInfo: NSDictionary? +// script?.executeAndReturnError(&errorInfo) +// if let error = errorInfo { +// failure(error) +// } else { +// success() +// } + runScriptWithBodyWithReturnString(body, isAdminRequired: isAdminRequired, success: { _ in + success() + }) { (error) in + failure(error) + } + } + + static func runScriptWithBodyWithReturnString(_ body: String, isAdminRequired: Bool = false, success: @escaping(_ result: String) -> Void = {_ in }, failure: @escaping(_ error: NSDictionary) -> Void = {error in }) { + let script = NSAppleScript(source: "do shell script \"" + body + "\"" + (isAdminRequired ? " with administrator privileges" : "")) + var errorInfo: NSDictionary? + let result = script?.executeAndReturnError(&errorInfo) + if let error = errorInfo { + failure(error) + } else { + success(result?.stringValue ?? "") + } + } + +} diff --git a/keymanager_mac/KeyManager/Assets.xcassets/AppIcon.appiconset/Contents.json b/keymanager_mac/KeyManager/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100644 index 0000000..2db2b1c --- /dev/null +++ b/keymanager_mac/KeyManager/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,58 @@ +{ + "images" : [ + { + "idiom" : "mac", + "size" : "16x16", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "16x16", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "32x32", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "32x32", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "128x128", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "128x128", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "256x256", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "256x256", + "scale" : "2x" + }, + { + "idiom" : "mac", + "size" : "512x512", + "scale" : "1x" + }, + { + "idiom" : "mac", + "size" : "512x512", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/keymanager_mac/KeyManager/Assets.xcassets/Contents.json b/keymanager_mac/KeyManager/Assets.xcassets/Contents.json new file mode 100644 index 0000000..da4a164 --- /dev/null +++ b/keymanager_mac/KeyManager/Assets.xcassets/Contents.json @@ -0,0 +1,6 @@ +{ + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/Contents.json b/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/Contents.json new file mode 100644 index 0000000..ffbc6e0 --- /dev/null +++ b/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "logo.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "logo@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "logo@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} \ No newline at end of file diff --git a/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo.png b/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo.png new file mode 100644 index 0000000000000000000000000000000000000000..8f365006070a4ed71bb6f1c18e588a72db1b27c7 GIT binary patch literal 7612 zcmV;t9Yf-YP)Py7c1c7*RCodHJqdUeMb@w9zLLx&lSx8C5(sAk36~d#fO6=1Eou}2HHzT1DByjd ztgI{EuB<5HDk`WX;*Y{2C@d1x|OX``{FwHg1RVc3c&CHOW=#bS{(EL5e@YE|A_ zi-@G;R9%tTY`%E$;supLAIodvg(Cj5mRq#wO?gz5X#eO@1JXnyVeD&aGCN97*Bz^_ zHh!bgD7H+VJnH9(6DKxt@#w&T1Ja$__g~Ozcg$3&q?4l!VHZUjvHQ;*yc8YZUw>%Opy=qXSm1Eb^wB>~mp3#tuS-l!S~-9I zb(|gE6&{+V#Vb~oXNwtkb2>T)qkMcALOZcb#D_1`BcTeTIoA>(5tEWj7 ziVaCg(FRYrjE!cC*=(D1#~rhO69r8Ou3t{gdY|M;V?+&3aQemGAy;q+0~++_XAHH+7Ha4mSQ-;=i>diI+sPHjYrQ>qw%fBius z4r_ZZVnks9hrLqdu$8L7T>9j2`}+y;ks7Y&E-$Zd`Fi_-$gHf_1GY}j)vgfO8?UeZ ze(2EHOS#ITWY85Ab+_Dk=e&;T>7UjJjLUdua7%dq2klz@R9lEHPO{FZaoqTTAdNS@ zaxWyr8@YH0Hk*SkE3aM97dxL2oHlCE4W*^kC-f1T5Z4DlDW_<=b2-901mI7j0hTXc zE_%B>>1K;Q_Rdy)+(oVZ25La$+p_H66$ju#akVS|nENlQHI@yH za_3aH0=)!?k2ic)QQ5%xFiM3~e(F@!LPFX(B>+)>`)Gjr#lvN_mt1|XJv4%Me(o#J zV?`}6P}Im-eXlbbs)2umu|~vbj3XxQ(mws&o16%G7>IAT9T$W$`I@z~TCXN~=Zpa8 z7kz$BUFyuEEdxi!@I6#_;Uh$Ks4qFE(Qw$V>k>UJl~WC)rv6R$*p8RGEZhSHh7OH; z!DO;HxSCQZWFrauoDhKUMVoJ|A2(yOO=s}iSkJ|jVG{1Cp99&n-x0-C#T`Zi3c-|z z!k2u-s95&`JqMXFV@4SUqf~LV7^YQ6?%usy+vf!!YSCvG8^=!F=um|Oj8;Wu2}FJU zAq=d{=i(Kdbc8?yEnN19U0_VT^zEp7KJvI+%h{Npfflnhj|-(#A`(|t*4`d4rgAmv zHEemNtYPTIJ00rKfY3>y*ED+DIvDWQ!w{Xl1ENE@JGmma0L11NugG_3!bE0W+*+?H z1)#7*D&5V8*3@hn8W6_vHRvro%&Py?5|yC#ww}=P5kG7O-Ot;Y;^->}^2e1-RaKz> z;s3a@Ji^d7aaH7fZ*jVlJy!H%rXf0XFE2Wpj_R`l5cTj!>gK^?{>n?dA2KvYvOBP# zQPgqmdSPy{fY{`{)6X6fE~X@rvt04@R{x}c$?Aam3uknc_2$AZQ;+hdyuZsj9F7Ky)y6p!0E!9^D1*E6FiwT)vhLIu zQnz~g9B3Ljo+&Dqa=R6b`1b#PK{}ZG4HSaXt&CHyIxA&vxq%17#lP;X!xeszrH3P8&t*9_7trEx=MZxy)3&CXYolT0e z6Wo&J=V#$VCo3){Yu%hLI!#d)-=B=HML)sq3U$DYKUWeh`hM`c{s#EnHNy}0n!-bV zz~VcKV-yvmP)IrZ8C@18PRa1SIsesERF`q8E&sI;cudmTGLY3(@>`dICjnPAVJOBl zx-AH`HSKKavjU(#arm4UfY>iq6F&1WzXy6Bn>bxrKZ36%r<1Piy8`gXp*~9+A4A!2 zMfpikp8A6g>XmDY#W9huVU_U+rZhqsz-v0O!QmCzg>q0R2I8h{WjYBfQ>tT(vm@3XMDPhSL8X<-L_xM8HU zsMbM*Qzg|BYRrd5#e{&KF)M^`%(_U~@ zPLq%=kDbqY$QZlb`bm0vx*&t7uFkj;r~jRJ*p92dzWFHb7Cu7m`-BG2Fa2Ujt6|_* zb%WA|;JOtj(S%s50lmXE3o|6N#v}rUU=eVSC#K{7yB0!!`vE9!H#^cq(;^XlJ0Edo zbHgeO-{#$V##Ilsz@+?qYB}aD_7y8pyCa6Ep<}Jal{;$I$ruDL+4xa}J)8a`SAb z)A^}yyrrBdSkqCnaM~8++#Csh3xxaN6#j~Zr2Uf#wl@fQuvwzOeGR=P$l`%EU2a%xi?`zvpm zlOBt8I^68NY6Cb!!(Q}T=Mx^F2gPdWkN$%eh}^XibiZuJ-H-@JTZjmQQ-V`sa*c9N zVOelEP;*#;BEMuSSO+WH80y3SWr+3?uFfa8u=8K=N9PkB@ zj>pVTdh*d(Ad<;;g=iEicAM;L+|vHzo%82TV#COFz%)SE;~RAKV`u!swZTB$%W?4~ zdh35c)x!%giHQb?j}OmUvu4H3*!i4~H+Jm27<9dUh?(34IBRtcM6r`3CPZzb#o{ne zoo{S3H4KglyOs-Mzyv^QRr=(<!7SEY<_0{#R zw2}LO34qfs(sMQFKUmMJd-8^-r1Xchv;i<8B_8DR4)#&W!{csPy?Wg-JlOM!`|rQC zV|($&jd@StGhgPv=LXQ}G?0Gdco;T}*Vt#8bKrR~6&1$i_uhNk*L>~!RVA?-(Jk40 zP5t=m+|Hz7m+|$wht)lX&OwV@uE@D(;q+1Q33`w7OgsSEQBqR#b)-`<`=t-Jr8%9B z?}@7R^;y~VhyYHSlnj$EO=g6Eo#%RuZPHa0^=mTb&%M_*kA2^L!q9iGKOk3u)vlo^ zi5eFm)ON5c9TL?g?1ubt-9zf0%==n!xGqMEew))NS)HH%NijpebJ|p+(X@fPeLGs5a+GRPK-C3_AXI@8&m3Fx?6vu6FskP!Kg zI;}di1L$&rQ!ZGuW(O1=D|gA^znwPiLU``EyFsgMTN*IoT5!(cBe4JHLl74i0V=gH zw>KUYN7qy~yg2{v+sM$B=1#Q?O}S(b>=Qx^s<1W`~*a8LF=Bi#_kCPc09hh zqNTaH8^7>Wt~+^~)^CbyaoP_?>O(jUyB**B20L~Lj|RTujw|5WYsTXNR5q|$tw1`z zrKN?;^}Qmqx~2)f{Bl1WJ$mZ;+}td(%GhP{NdUy_jCS0xDQH!yOA2@jw5j{gK=k>g3_cypSqfM(kc*Bp++Ci-(xq- zz9#D4udZF&oLVqPR6rSI=FRRy2>qP$07_#*}8j}mz&n4vg#EA+>9^T~#NIFpA zf({(WJ^}mo9R>UvNe7(k0?B$}TQ2VljD|3Gc6&szf+0%+Pn=;IUsirQdy(6X+-L?!G|Je5LqpG~ZLuhcy{ zbKrr#r0!jxkOXPw<^ox05gOd-ilWoK3Z0Do`styhq!Nb(TcUuuK0T#G(n3}--NqD&zcm0JiNd_~Le)L7?vb!1=YqQTiSu4oYCpKjsZfI@qMzRc zfR7Af19)^5@>O(&i|`mV!>&(3dtj$v-#x1PmqSD8fA$4uj_dRE);)27S52RbL*^f# z!tHQ@P8cfd6z)~vq=shV<|B#kUa&KV+J;`L2lMjIEp^ZN_&xv~7`ti3bBV|y5+ov- zok9wJ#SNyvvO%4$tvUlZaYqyhTlYtjgdP5|#G%yaXbhRAB`6PK8S{(h-Jba+a4Ev^ zm;9lVqWxD|TY*QdejwDqLwczq95d0n-}t3Jh(8x`;P;E*E_=!rvp&b*}%u`zzj($R9SBpcgAGz|17U7cXhG^b7m;W%j!7KETiF5xr?Z z3e)+d5ZUl*#~skpW?_b2QwmPy(OXDTWAerR5da2T0RO``ejASU4`6`C@c=e+&Y)J| zRx`1w5trFQ@eHA(AQ9O4|0_}$)c2>u=%?ph} zDg{CS&U!|G?Lio>}qq51t(<+WrPe|vN&UqA?hmB+QH^#49;nvYI zw7a;HL#2V@+n0eQW&p_X`v(c{Edy8KHnR z@e2sw-_1XQM~9#h7y=?Z?S!2~c*cRMr~s$hG6>Dv3lV#_x;fRHnCDa|v2JJk zKweV@BD6Os#Hs(^CNvnc*{E?BlX&In(>a|R#1ecR+o>{HNKh#3iq=-M+-4Ig(03%q zovw_~;8Lw{G3|u)&v7$i#Ox{LNH?KRV==@*$!$*qo`#NR5gdlt&t4TYRulZhwkW^u zZaf4-jvm)t5cAc$LYsxqP+8di{TmuxD+n3_FwB}PB9K49M`XA*6ufWaK+WVEn9e76 zElH_Rf58mU|Jb!(j2MWOf4KuYU%?=17&i^VQA3b7zdOmVMqqacIbZ4$HO)@w5@+A? zUNfrNWfK-fcYh%_C;+@H4@?I6P?fB@ltHd6F2G3Woo)>|(0(9s0j??ftF?@g$c*#5 zvw&|(=vvRyy`Uk$6M|r#I|s-+Z5%xX$f6H9U`ot7KvGs;1xc%xf&*1K8&0s`K@U*& z*L$Hcbs}?2Zfw@SKy&Q(js`;We#V8OUzq77Wp`i0YZ*9#8CF7b(P30x)KSmVMNk8H z;*O7bb(5}z@>%ym)s-1&wB5sr#kKQEp~mEkn8UG&tCt*oS9Zf9w_}Sa+3IZ!_RIHu%gv3G}*PC&(y&EmpJ9)J@%&)T5?_@ zIT?*4VknYnrjQgA03lrRvP}5CZ6HNePmZh8f0rq^c1Zp&K;kIdlje_X5aWsILXzra z9)$k>17jmFvx8b;ThrYw4I!-s%XDzSTR#A)NYph6{UQz{R}Y>wBAQw8BOXMI)#&8# zAr2&C>Lhd%t3i8ck6_^-ZFb8KKoA6ze>l(@od87(pT{5@8M7=r5Dh~1k#@wg*YDvD z^r*hdRbq2`Zx@D`!O&l z30;!6CpSdwk1mz%PwAVFa%U$87R}YN5#-H@KtoNu37VAtW@}(PvP5=`65m4a~j* z;#Cxqf&w6fOJ0_dmlt8Yf7>oB5(FwVNtmFHvx`Ic*;%1g(dW>7c8%e5q1%1~K14x3 z03T-r!uk9FWZmD6djJ@tParN*jJ)-ANp{EHqgqRbPq2k&F zg6nxI7!&|c+zCKlryvg8xZml%i}u*xC8Y3e_eTm&1O358FL01``sgid+lGLgAHDj< za0G^qk)TkrN~qucxfiYS7YzykKW_q-Lyo^Ce_W{r)qCCet5GnjnA1|((Z3=*PBv=C zdai0d!-4|fGwb|ck@)sY=RS(od|M0v3H*rq#=jlzN_Ef%aOFrZ-s3j?j?O1!knLW9 zPC)?(G>5&wPnLzrr|w7+<2BhB66h2h0=mgz{4P)Tm*iM9L~nhcG4Mnf2_!nRYRJm= z`Lem$%1LKX1Nh9+wu%yoq_mqT+^Q2z;Lpy-2=hAJ!F4v)jMZXL09efM<#O0CTQSz_ zyxivtqQKVK&xbxJ0DPPg2tV^dh9?9T?~P&(kx245U&F%I4EbsY;S2|AYVr?7My532 zuIkGX(3f~xi^ucafFGIO%hy%G)j&SZ_yEUGx<^{A)HL+)4)CG6->Tq#Lnn^=IY`I% ed}DumWB(6~0ehZLbRrA@0000i literal 0 HcmV?d00001 diff --git a/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@2x.png b/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@2x.png new file mode 100644 index 0000000000000000000000000000000000000000..f7a45de7c4e66c0ff60986405b5bcd95e43e9d0f GIT binary patch literal 15982 zcmV-!K9RwRP)PyeC`m*?RCodHT?d#HMfQI^IqlAD&dUNzT#^DRhzkDojGPh{%vroU#ek=0I>p2( zhl;0|5VM3`G9KW8m=F{};*xXP$i~^7JpF$)xa-dDgzld13A#o{2S%Wu$UEwj&)0E~X*v^Cieqsp)> zKRcE>6pbT++N2i`|Lh zpwtcQqMV$xCs7z!B`q*S=2QTL2p}a74+4dSQ&suhbk8Rx8*k6cOHJ47)lvWMn$1>6 zW25zeQZD=F&9~jKI6O%4D<$edM&+`K;6`g9F#-=hIK4+=qWYt5UDJlAq{Pc4E-q~B z>*|`!cDrL<-+~_Z4;eDV5w?Q;6hsApA7E&7WDt00($w69%!H5fx}=UwOEZRVHZRQ0 zZ7^HSHk)hqt+y6V33Jh2#Zdv^1qZ!}6ar)kk9Eb($<0f@IWr?6^fkLkHH1gGI22%O zYRqR`Zg$cww@g^VgH*JvQ~-zuC1oTOfybu&Yg~F};(NV%WhKky9Y)*d3pT6s*x2N-HZ|E^y6v_J zFAGDIKUJp(oj+uhLJS1{@#rg8W#y*K?a?E{BnH2Z!UN5ZS)3@`*0Wc)5jaWMBz3!} z0FWAC%D)`~Pdq;T{oZ}E?@3EFbv}K+9U8tP%#F5smUZ7cVZylOzH^8ZO9g;9I8rVg z5P0K_k4Lj4`=sS0eBZZEc8Ub-y;#=PHnEkJwN(xEmOa>sHfi;mwU=Es^hcp8 zHOsQhC!fskQc+rSiPPo!6AFVNXnvfVo{^wYNIYpt_8QdHH?6(##_?B>RRgbvif}^( zfCwN`7J(6X&Aq9q0Px0x-ieIBlTW^S zYqzeMb8yp+=)I${(FR8jm)GH1`Vu$DpMT|*M~;eIeNOC%hVYNSProJ3r2Sh~X41JC z83`&*ggi6h-hztsjFjFNU35_mPg1|xsQ~Z`4NV9YfoGq6=qF`0#2m z>P-cJ7${O6?GSiu%Cx`s8_@Nw)Ku}zd8?`#*yBelHp!HVzdrfoU!&Ry$L7tOl`EF5 ze<3M3?r+_@r^kya2v8F^lbn*!8;ypl+5yiqf(ihhfYI#15%|YHUcaeV&$Q1_6&B^o zk9+K4&)$>A%TCtZ{noqxTpPRw(USu;0@cp#C;y$3n|yChPO@loAh^x=OlDSk&rmf1 zDgdJAUFi@tdG^_vSLEg-t;os}XUxC->J2G z_8uMc`R6l4o%s&6ZlTaW|NL9yOeWojJw>vB#5sZACQKYRSZJN701%2CrSn2y(xj=n z{O)N-`uFdW>Xjhi=GgH{+wtSok4~HR$SeWmQBU&zjQ5kPERN*`{cD1>RzOya=&T#+!`*V9+ni{`D ze+X%zv==7@OUD(C$w4j5#gz};jl~ryny(!KlPCX2othH=NhqBkUs@Kw{I7P_&QCzS z@4lP%$`!J6ca@wt(GFxD5qg6rqo`={G9DyA1pptkXkIS_k`moTef#Dlc}4QL!L@Am z*DZ(MeE#`|p5#H+A+t`NeD`USDQ@WAeW#Cx(m*`^?5dSZSB&S%g9-qyNYQ*=2t51r z>!Z8pXIv}P!VT4a`1zOpAH4eNV~=<-?!-6u-g{GdR#yD5g9pnF357w46AD&`^WAU1 z{g%^yYbpSQBHfAUaJF6+XVT9}PKp!s{y6an&TZR|E}b#siNADW7=1QOG|nN@2{7-w)RRcD=6pyeL=!1EaJv4CbF z_(@<~E~ngXX<}^F2ARWFD|6b<;IBMe)>NCB9UK=Gt%0L<>C8`+7SB z^x%XMigJukXqOf&qO7#mwsq^Vi-YB(>An#dGiLOrIdkUDcDvjU$>jWwMbB@1e zY~sy`62Rx5&c6>m55I#h$$7sIX0vTW;e;_4wuO-jfVPN4@IL#`QwKEl82W~}=Q)?y z6Eh<6rT5kRZZb2xtl0!6hTkSV3n<|JrV&uedV9iB)>c%>8*1ONUflB~7{WMwl}Y2; zBS5?lfAGO)zvkwo@OA)#y9F(2=_yI*Ld?>dGjB=Knwb6%9Rc!CGjE!8cl@*KkDQ+P z__pc`uD&#yIzMUQ5P2o<&QIumcBHoJ{3PCCN=>%r^n6ynv$jU}+McQKElcO32rxkc zIT$28#q>;dO(SoisnIC4RaI5bwk?7RfVPN)@jm_5_wP5nvc2~7n7@8l-~Ylqw@Mpz z8kq)M9s$4?77O<2FCBhYpFHeb29v%ixA$|3BQ-U;*LObyEE_di58w8NEB|$4uUqYK zIDZyWp55-gsVyB90BsQo!+rWq?-Uwd*i>FN`kuEN^9RO%uDNC@o)>t)e-7U%xP&OHuD5t?y^j7j(05y6DweF@C*8mBubfkA{~?f=K|b1 zouhP^QYhT?s@-KUsrx+Wi4;%tWha5fBf;s7U@g{fP`;D z%HN8fuDtZdpBwWBB}-V0WURYm=U1ZzAfM0(N?7FR&WFTrUY9OjQ9E$t7YR>)^KZYI zI%&dXmt9tlLrC8C6bhAG*-+OoxfwPp0Gg2y@k*BV5*}auRpljPUyQY{erp(d$!c5Q za{7P36%RHMO_N!ff~gre@=?m?{H-BKVC*>l=db?n6*~5BU3lC7jEt#0chr=G$N%?A+oaBX zk4F!$Y_ixY`C@<)Be$7`3V>!LM7Wa9U)OEy!G>N#yNbXrqAao*Gjzc@06xJ9a#-nT zdAInG2G8pe0wW(!et7ZC!83P`92Z=Dbv?tvUcRkWs+6WRYu0$qA)o?)FM59RXHI%w zSJ!>)!N%_WGyG(Uspxb$@kYgOl9{agSF&o!+R4h5OkKf8Oz>-EPEC2x}0=#v;5=DxD7#L_ko#7_ZNE^w6w|6X>L_2)pn=D z#e25a>12Bnkf;C%@l{EBc*)~+gGOE%BAbYj%WW3OTJ$#Lz5gV{?ZH(g^bbaS{U;_E zc-Lw7j-$M3gc3CLJ^xui*JncMI||*XQKPIlsaMLoJr;UM(z)S#5-r@)D0Xt z4cB91a<*U5SdSh5DTv?ht?nl!#Y18uKLOyt!#(Tg&Vht2-~0iPg#YZRIhv%4ucb?a zh_PJG9OMhN3>e&lLNx%sxOwGw-OtsV z&$_TrTlFc(txfHCN)chn>~@P3d}EDgoL0S$Z=DrNnFdb}GEfbGFLJ-{*&uY*I5nJlHC)UvIBbp@>{Tg1iL9sBGW?wm5C6E$?dLiyIFo3 z0M-@lS4>m@2zY4Lw7j7L$fAm*cF1LbF1dWx35`p9#s`W-*VBNz_n>s#{eiNHp61r- z`A=AgUW>>wv}m<c^f>=hz zYZZVz068Oz5#Lmzy)L0Ma%l`5%1xC$Ar+3^^8)CO?S+I*UxWV8PO!F`(DQ{DjyIvI z&I{h~(i_N+eEXT&15kdV4ANW;kR-DMgKiCMZaLT(1yrg`utnDc_NkJ<9R=TA&FLdC zj(q6VU%!5RT zi9}@__4P)yM(5p^ap+LRTWyF$1EZ--Wesl!EYVc`4p$fb;ZCmm;}f;XWJa8~5wdhs zNd*AUE`eVh-m|Sdi=f##BEY!apsK0hn7iX=OHiiR44y6i|tY+6jUNq=ZND9pSa;lxxM zxmMO@vv=W|w>h7~;c6T)VnhQK0L_SSzA{YGMpQj%h$sRX%ioV^`O#H4lg+n2IDO*r z`9=i*U*s^q{=ilNRFp(41d@JO0?HcC`zsd9nC0`$H{WC_6|yA04ZtHSP7@j`0Qe$@ z`HAOT!|q=MP*Rdm5s+ETkn(L&sBAh6z1?oVT&Gj>-kYLTtIz=?6##-?gp8FR3#O%n z!V&2D{u999&O;i`B7lAvt|xBk`Qo8aDb^7hssZpt?)UtP`f7;Zxn3YOB@==`&fHf) zRZZ9ZTVsa@e4Nwzp38r`-D$-YfL}>o-sXc`3g|3(G8exC=C1w0ZSb73)LEJxk#;71 zTMUN1Tf$a0*}Y)vCAr z`#1AL8Jo` zMuPj*?$pP_u{)lHqj$dmZr#}vbgWtVpgD;eAq^oTz@W$CZf`#d#;xB4<%PcRb_UH9 zAj9CnHzwO`?yoV+kO0{@Cb2hKEVc6s3kxMT7q2s0|D{qY_?P2m58`oR&gKU3mUhjA zo$;FZ(6Y-<8Iu$0`w#cod@Fjx)to#CR&=#RgD?ctrAMI4M^k~ES;!^ep7!}%^7+a` zzSd1mwJT7?=;paly5 zf8y?6oCIl^%c^@09v;jcIO+UkIABfBL#JyLUjL}JPsv#R0hl%u?KFVS?@i`TNzr}o z9mV|)JO3Ok>jLf+TywJb78Fd}T~e}OCRYkR`RZ!wr)za8&)I%_=xjDeqajZJdTScq z1_Z5%JH!8kfBf&&hMt3`IO7v}^=3tV6)+A5IKu2DHx{3Xy7VyQel`urVWoTms{cRl z-d#M54^4Ak?4b9!-R{}V_hMhMZg#mGhVR^2Eb7`NasO3zy5fZ1py9ptY;Le_ESxyj zOMT__Qi}~zH1kV*WW}E>xxK!u$?hS@H#%gGjTwk6-V6wizqg8-av!0rzbUz6rN8X_+FK^t0$^HFg5jmQfzh_U;jbbn*WB;nk zniD7h&dxmZV2U;aCkrQx%V|qOHGo!#2vzr6vGDoVnULm*Clg$5+_&LKO!t|uqesf{ z*zoj~AE62LPodiLvnWr;2*InOqUjB!3sdJOHDqtV;l?*OAMl}&`nIMyQ&qE2NarU! z@HF5ht$8*7ry2kvkvwJDsK%T=MHYeTelwU{uVl>Y*66|UyI|l-7pwV{wdIhpY&Pf) z?*fMZ0XDvxy?D=_;&Hwb0>u>+Oc;k}8Y~QyN1`+f!zhOC-aSvS2h+8ySC4A6*uGY& z`TPFEa~{m5L}OQ6{%f~~nhF4X;@X)9DlJ+0g2wuxyfCV=W7r{FU`xxxIf9O5l0m-q z$v-RtRM3?_Z16v1IJn>&E)Z(CLQ&NslZ!?@U(r zBwyf29cNGP;wgf$HiEkH6gZ7ZfX7`+U94pM$=-;>4PSxjw{^H{uUzo>-d_dL>d&cE z%7^jo{KU)`E&b+2s`HcfVA%z=wakC;@4f!o=P!QY!X;nC={4CxWT>Ud)}W8m{ly>e zPA>o)##mBc78!G0-oZw?20R{@Vik-5L2#|kNSMLlSDD+j19lM%4n=BW4C~+>a=GC z!G-3>4kM0IBDkDLzVNyuB@nmg7trH)UWq>W$?Asm0Us12dwloqq8WV4Li_y7kmhTY zOi?n%V(R5`=G>$Dql(;OeXWE<<)|0g(9E zsz<8NyVA=tD%eAbXgYQ_MQw%0C7Hr%1|>QrAt&+@t3y_$5v^*B(}`d7U7pUaIei$E zXUaStcx5geb_>x%L#r7Mf!U|`?p^pVzH9~zxHT1b>TO5$JKC0AHsh4fg(W4$c7JWc z&aXgo-(6_&*UMj?VDUDq^Ns7r{&`BEe4Tm-U`@_?AP_iFmxgbR6SaW&J-qZim8`|f(GW*&X+%C2 zkUOjx=fveX+$VxPCQ5=EZT%ldmH9Qk^+BP5$A(Y*EDAe6Y040{n|TGVemiGvZNr*S zI)7uM_2fXk=E-2Vby^J|amu`$nxSKlu?khpU_h49(*HZhGhrC)!FGUjG^JHsyKC3H zHA32gW9`R~Zn_ZKaM9ptKDcpc!B=g|TUfMczE-c9AVcZbHjT?Y+WfmTD#gSrueoMX zu>74?190oo{}n5ppZFh4{rWR7?%WXUd3K0&{AyRC9sLmO{Kthf2;F&|hYG;Us09ci z4;zik<^E*gz`}vsw-=vkE_D9f;#n$Cw$Q5*Q)EsTo<(Sle~f?3?YnYC@PZ2 z9q9Ipn`KluDW+s)c$F&@I8CfX^;Q8gh1`u-R)((;idk|+^_aoK(8zzhDi~I!#wG}p zuwiSvXIbsPkb>*!Uh00>DiHR9$Yl3|-Mbgugdaaay%%lowo0qIOQFCqo4`=tU_EUz>3ibLeC78ft= zqS7dC;d{tuYoKg4r`>4O-OaW06WW**04_!zcB{SCKuh^wQGW*2{m(m%x}TP2f>9&; zL2hocyRP2W`0&H?1jCD_zW1W3??k~2B0z{89&W#F)YEFMl0iF%kTi0K)4llmE3aJ5 zrx`IR0OSnQ@dN--_kUiAv-=A>g}R@ZV1SXM`oVzyT_8SQN8VYJPG|XX=FE?$KK$^V zXq?3_;JCjpeoZBDz`?I3+;ijC8t%ROa>&d|6s+<$mxjCjN(LFUcQoH~y~d;fz}4_X zt__TZeELH>Anm^&bqaOgpx40Vmk)%3f?P;UG|K6^1uUkT*-AF z;OrLPCbX_&J(9$WX_Vgd>5~oP#}9`DlRo4c);CznGUBwOdR%?AjW4s96aXM=>#v<} zv!f$FQTNkO-H-1Cv-?EVA3m%%^zEAsNl9^j9{}3=Gx^=q{`BF8Uml+|>*JyK-+yPB z-^{-!;1*x}^0WPd<%@=NRP$l%m|<|vIb8vTUC32xXt0=5QWCDb_|i)&g)oar0l>-> z5!ult1Yn;uMBU#=)O|GOvGW$%K3PU%B+h2T`RDb3K7DhbOKuA2^MpOW-!N;|%3pBS|IyZI(ehu7U;NS64)F|q#F*r3-7Ylqby{t% zH*UCL?BlKDh5nDc27uNd$^Texu-F=P3Yl6j1G%1ITzFMzU2f1ZGPw>nvuIg2qX8MC zWr5K;bjG1V8yrr$4l=t>Eb@r=oht0`2k=Y3Q6`gphBoYb0%3{nr_7r-Zyt1D|B-EI znI@VLKzG=()7y`Xz|KD+Q2An{b?cUeD;DQNj~-;jA|CK4Za8+V41W7@n_d#fyOH6W! zIWF#AL;1s?j@QA0N8MlbDa4ojEJ@37dCY+w@pUvC`3-;l@qaJ;3U@&;Gw>RR_hhzB ziT`oyUm)WWl)fl!F+XkrWbBx;4m(yk#vQ|xaSvig$H^u3Yy7%b3vCDr0p0%nM}EUE zA=WYUaPnj|y!oFMfOhnuGxNiNboeKpxE+QK>+dHA*=yefAAYzDii*~tAyWZ#&(DC= zlz1Q$pHc+Wd~7Zj9-TOG>?|?)hpqGJW|W+0>Vj)P9XT}H?thQQJkrhXuTdxz5ANJK zZ!Z@p$vO9!Ph~R2;cj0W{_LJ-9v4^8_}zC?vExf0P^ie~&0F|CH2xWd{{_Euc(5gQ z{;!~-qE50(UwiEcc7q@LZ!uk%TK_x{euofK)_?@lMYbyZKhi$!dGU{*xS zz#RWKcW&{2jPbhrabizUmsz~zXURMN^yv?J8iNOi;8)%Z^>ua7h*zu41{SLoEKN;d zx7&#gzbBv6o&V^uN?5#TgR-=&x*{;j!cqlGW4^^{{&Tq6n$b0ZFI}|f_o(};KZE#P z8zreKQTMU)zaf{aU)ZtZb51+FB&mor~>kCA^$)LMU+~Zq=1g-N%Q%7I(=_=Bn<87XV?U6&8;B5LXC(uB@#2 zD$bz6d5hqotgHse*I%lDa~&{d%y4LIj1Ku)U)Ka1HtdD}t^LEk2Q`i~T>L{1M=WO( zX)bt$O#q;Ks<4&CrQxCEk$QH&S=~n`n4G=GhSHvJ)8Y!jE-W)|!GcAf>b0s{a1KOcOLAFqU!E4RS@1Es#m{)FcmlI6cweI*Ks3)>Jt z@nNMM{n^E|7N9`4*J(uEmw0wxsZ_t%5!8JyFXW09EC1xM+2(3>YM%!pkT3uG^#NBL zxfByH&ofWoh|7GMfO(`&tgUT?ZQBmR>aVv26n6M=KuIMZv3vLYU&N?W*aU$5lR785 zww7j%L<}SX@j!Jy>F2K?`8)K?Bhl=BM^yI%LE1VE)mp{EqQxI*H0oOvO7!aVd)T)1 zFnspK_szGGU0;7~67nXd4&e`EtiN~fN$mJr;q+;)tF6pYosJ!}WlM3$%OPP?%UPvT z(9Cc6ABlH~;ZXN+4gOJ7_lvws?mTxW{D}U2*P1nJrdFS+n;Rde9bQpc&n#Rl-MGIs zx(YddR>?X=n8S$^XW%Cs>u=h$pJ&Nzp2fnDJrEOk61K}8HVpt4pr}KCeC=uwr4dx! zkKBV$s=$lNo-Y0S`;L3;id4 zER>$mg+~LJT11?8#zyB4le&*COdr^>qj+B^53i%rKKbP5Ik*fTmd;Nww4s5K)N52k z)jxcs9LM=bVDqmBP~#B8lF>cmoO24l+Pbw^kS_qzcHaVEC94K27@_RAL1k^ys~Lv@ z$G!%)-L1#dY;|bNrAG^1yn+@dB|KNpe;K2}gC{h&Xo**1jw(~5sjrHa%M4AVv?vcA zb)PumJmYf)Hssoq*?s&yQc_a1Fl1&Ol)>54d~C1aw0ziFc)l>03AmEh&oWq*wQW zSmM2|P-tH2EVKJUA2*)m_bGP%+l0~!q07(Dgohry790-Y>UisNEmk`mJz5C|50=92 z-6x^E9FIqrFrcl-s9n3}e$m`v6E;OO@2cS8( z=!Kh8&2Zz=OE~s_np0+xGi7Ba!IMu-1UsIS7%bqb1?Y4-Fc=JAh>P=FzxiehOq=#u zFjA?~S(QrGTgcJrjO_D9i(8|MtQCY*u=wEXQTNGK-QA+tQM4-o-wmqnw?id(#Nfe` zlom_v31adZJhwDC1`p0hAN`l&J^&}~22|n1pc0h$Q{#{PCvj@E8sg&PalgL_cebC^ z7}l=c1P?#_I*<)SkqRi3{)0=&5AiLZVdmLgELvaiC5*ZJVN&-|5g1lk@&d(UHERnB zAekI77ARlaG(05F_yV?=EoU@5q$O4de1L4H4*yv&qtNt;Q7j*I)z3&I}bur zla(LSFyuxJieSi305Gg0aswBsKq2b>h82+fJ=*R|IJ=M5%~ahN;Tc|d;azdn)eVD0 zU?n<>ii&FZ<{K}6r=pi37DJR<7bCAX`0!IOPSgN8PzZ;*kK-+3%){yY^$rBBWKC&k zXvF=vAbbr@vYN#lWB*PJ{WOKl0dxof5Ds-8F??OCHNCiH%LlPw*y!hxM_;td#im4G ztzxl8tj{ggfm))7sNbVNHRGBV9(DhJsP0duv-?~h3cq|fkAkN?htKqvU+rQiHx2=e zQ>RXq;g9pMULnJMP_ffQ@0#ilZu1OcRl^SXXjRZ$hI%rCdK>UvNz(jD(-xr3z$1%mlCFI~iu8sw8_TR~hV*nkXR$?c4 z)csYTK>QwQCTE(Bd8oQC_LK9?4+X8B%)CcqaOn(i%)qOaQUm{fZ>FmCk&n?z@S+lzNY=SkjD?o=30B(0w4*|lX?lZ5U zy8jZL-S_#fcj`#xnR4`BOjaqqgQ}*&J0eE!6f)Ksof<$G)P4Nof2~w957OEF7=3%g zQ0?UPOQF91a9~w`?3Ytw=QnOy7lzWMFG7Jwp+ubk&>z6r{goeqbhGKG-E zcd+Zb|9~?WT@QA$3UK;}$HG)@k3LgiA&8?PkUMHxqNuHeG_qA!(%F5g?hAQQIx`LN z8Iig4-3|!>P6E0jt^qJE2PCdX+x;J;o82esKDwWuyl2nc10C{7(nbYEps{NKSaN!T zys-}A_H6-$Ib^r`LCbW+CxW@xU~p;lpgXn)bjPF153B+rtO0~W-N&=v9@({P!Q!A# zi)QGM2oMW{(}fS>SbjuH`zo5ukUf6}=#TDhi4*%zL(g;J^n{1Nt%D8OuLt zxsUW8MNaYSE8MJXG&%)=)<3u0`<|7ftiTh#-Q-Hr&_hb|)s2U_w5G*#05P8m<1nwH z`Fb{whcD90aPBdAU6Iu4{tTSmf0@qiNBT93Z27fAFZb&Fq&99e@HstxGUU&k42%S( zFfNS_PLF-StMij`YlmD0#QU^V$IFp2_ymRA;bc8#jU8lCgEXG1`+Q!3j-QvP;J$)0 zJ_)R;xu89L*jI8$ab&1Lgp99X?r~1^2moIdjMX?a;XO{({aAf^($$;A7bDz(WdeBF zi$Hz+wLd^D{gFgpJh9!!ul_WxHlYt4>qp=7iFAz&`?vb6f}*|}G!@dg^wOT#4>FtY zUE_xRzxk|BBqC#80AS}|&9cgV=n?g4I@XWGD-``@CT#i|3~iQ{W!6T>T=*YJ#{UEn zg~jZd>|@&4*_pPijT-geQ_tvse796AgQJqH82-Ur>05=mDbgfu1=oq^i0YC1KLW z|8maXIwM(0Ad`tCXwiN^&f(CK*7RKd$CLp0UEP1Mq=XvtaCx{LEsweT04N>vH*lhH z4GA)96Qr!22Z^ZSOBHNM8J@L#Yeu)0A`JUBL&oBFJZgSRq{x42&m9HjSKraHjL0}_ zkg@bVFz)+Wmm{3Ii*RC|n>nzDQNr4y16 z?E-+P`!5@ffV2B_tS{sNcNCiH;n#SK%6zq_`oe2{MTZ>M)V)90Q*(UsY3Or45HnvX zLd~$N(U`?o*JPk(*j1ty8MQ+IqVD5wGWz2?C~Au-vzSD{h6X$Sf+eH7zod}jiTWQX z*ikD{;!>j6!IJsMaHB16he_PSyQ5A35Op8D#6FD6dQ00jp5Av}1jq&+e?cM9Y`&)a zxW6Jj@hXWA>Tfgzo017mr-G-g-->7z@&m&fiSG7#WYRDDuF^<7F7XLFE z^pTHOAU{k$d&SO+>7eqeEXNzF?sEi+X7eDB{KHZ(Zv7rCI1}#D$9oKGh_eo^fvl^O z^?W&6=>=2on|Z3xNlo5|&v?qTC#HMs0Eqno*WCqVN310)ADp`Qvo-`(r<+;(y%NJE zvSrxx>l(0h>E$^yh3p_ybD;Ih)K3D}cK9Jb8;t^j88zxoHJYgyOnB% z!hwQ9jsn7sKNB`GB}NYoO=?t`)9~p^tNPf?UhPZ&W;^la<)_w zWfBmz2;y^rxE6~V_hM2#RLVE@5GeigeNaD;oSgkfuqS82@!S6iIiF7h1Abk_4wmeE zIC0ApUTgWJjE24!z$x^-k@Ll?VizfhUsTKi2&y?Hq6lz6z>?9mUFUBh!?ADWWjD0k ziutGPn!DO{{$~DW+#5gyL^K2{0HWb3&^kzlfF&oe<(!p_&v8CM%;3f^yfrJZZ33AW zh=xD~Kr}oBS_kP6z^{C;!0^~m6pR;1XWTAe96@~Ta;O)VvO>)h9Gy^0p!5`h2qK_6 z9C(tCY}XZgmmOI?B)j(l1-&09C4p$9NTUKk3REf2s6jweaRP`F4xa&S3R3^~h0ml= zBhy!X0>s_DuVDP`Ti~;N>5GS0aZ~_^g(T$@wFsntH3yRL%n7EI<6C7-Iplu+GU(B$ zhf8q8B|uYdFVE>fT=Em20eK%h{ktV0StP^l%jk+c`P*V#2M{^54Z!7v`cdl&%#)Lv4<(m1yKRej0C+#JpyEZJ~8O2 z8+b9e)jH6g+z)B1Kf|lHsjk0<$gtxF>$I(D$#&mklU@R+A)$3N*fR3q=-n?s*AJfJ z!&!7oZf`h#+cTWia=z`Txa_8Ooxhm}IW4&C+IyOBMZFTO>?7rljhb*KQ~jup)rK?H26*09m$!=#HG&K<8Vb%2$fhZ; zuOv=E>dv|3tdMI{x()X+kV8ep3{(J!i6-SG83K-0_VjHFA&xo34sNa9{*na8%Pox{vj^XqE|=hh;XrNGoIE7B zO}+@J0Puwhjf*-2i1Us3o$K4xi*(Y&pI5ev7b7Bmd;9WQ^HrnAASu@Ki7xeDHw@-$S+_ZUU-OiTzhf`PKL>GEAKAIDw>J= z>`w)x6Plt3Ji$ z&%n!wa=HAC^75VaT-z+}lp@zsX+DZTD+HwW2hgf0-has&K3NSQ6LUoPkf1xf)6*Hb zIu#)_d~Fv9jgSx#e*i)%N@*wp;Y7e0XM!`su7#$qeeuvvE1u7{0Zd!J3wkynS-;Qt z>O)9h`4P_eC*gX2Bj+`JB0Q=_6+-PfBhhX_3)*9QA@!U2pu=ml1Vyw|gw}&1AQb{0 zgPyye$D_T{T8e1u)(@@w20+&Q*Ev}P5(_@!9*k=s$BCVsI0c%pjOJj$Wy9mQKLfd+ zz7#b=fKCE7KOK7Qun1KC-wj@!zqz5rJ5NKw1-e|;{`*ONWOiHY z>=FA<1wh20rv--#fwa}1g51aPVTS!%Aa2hlNvfecvESo^pe=KGL#@Z>f7|#--ABhj zBvP%X<#q}LRMq9s^}Q$H%*A6oPCbY*O$h1QSIQ2`JNdXzS15Fi$N#50hP(1^!`S6^@y5UV@|nk1XHeUF;Mubfzs zGY6zNcYssj95PV>zyTzhC3+Ab{`6~xT;}n)uRpZi(;11!AF0Bbi~bB1m$zEB%jgDX zT;faEv>FAp8>|%{$wHI%3O}F#l;L% z0Emeu1bbzQ{zPj(=tt@;G_5dX3F zpK;hEu^*t5fMPv0%13ep3J6VVL z4A7oB2-WAK9e^g}MP3fh*1kS`->4JQq+(yM?yp2fL>NAQ(b4y+a^S ze%0+B!fqpyKe;~#8Ux~v;C61@YBf-ZBOLm}jEZb9^F z1Y}4j0RzHA6FUL|9#dYls`CoC9k=YtJHRf1Uw=}L8@C{rUUy$h=Wj0CipE9N7mjYe zjrf%cfQUZ=S^=pMF#B`PflfJ^x)w-MycJLJapOd#uh1w_nZC*j7Doj@FobA&%p(x+ zMBX;biefc3kV6o8AZH&Pme+2({F77~A24n{om zBU%Do1&Ed>LF*wY0?9ut0ip>sbt?eI;lMrm+d(Q*-sXl7L!xf8{*F#adgC&n2{b1T zNOF`|b9q9pQ~(G;jnc#<0-A~wKz@7!*_%&13p)~1L5YSy^b3woc9;&feL_Fe}c6Bk|AKp>;|@su0HuYO(`C;VxNgI6iEd@3_UDb)$k%fTyO;n zj>JFC8Vr;#n$xHNh~}q5>lRT2RMlkx%O`97u^y-Zi1jB(>n|As>Z;Qa?`O@P9Q93p zu^#9$V5~nuT7O9q$XN0Y?(A_x{eTP6x`%u(SRJ)f3R0l)_>npYA87>1F?ueT(%jb^4y)s7vX z^Ae_107Uci>?CzlshA%+NmC_lCK@Jw%eMe30Qe$C^NWta)~)kTBhxjaGwx&zaUSIp zzD=eAfG=V+za$7SjQmAp9Q*5PlAsfuDSrJo?b%bbGI&n!98>^!<3aBtguw3I^MAx$ zw=*JCd`uUMo!`u|%2sEXb8ik60Nk;nIVDD*u(03>w6+oEfM4ReMK60Y>o320&z`vl zgw!$i_cID7JcS6P-#i0X<)xN^99@`FObPTH}fc%RU!PyrwmIZ7uf z0)qz^8Z8#)Ml1xK=(GJ$Gf0xOz!+eT0?~<`{wP*;3#$EJ?Ao>9JG`g!CNc2rXcZ{} cQHj9+17|JB4)|*j1poj507*qoM6N<$f<-V-zW@LL literal 0 HcmV?d00001 diff --git a/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@3x.png b/keymanager_mac/KeyManager/Assets.xcassets/logo.imageset/logo@3x.png new file mode 100644 index 0000000000000000000000000000000000000000..94a7b3335bfe2791c3e3ae4021e04bb438e8b055 GIT binary patch literal 25618 zcmV*mKuN!eP)Pyg07*naRCodGT?d>LMb>}alf%yDyrd<`E*V4xJDlXt>U0Ta z4!CBA-GRzMc&~Twtj{J*n$!?1pI9j$e2c^iQmmc~0fvAZfl;Fts`B!Z&+Xki?JA=| zlOGqS&rD1->P;pc$MfOqQUsR(7OTx^vpdaBr%>l`IDc0wRsZYJEB(Xqfvg!wg1kR!Wjlp*Lt`C~aqvh?%I(Y;`#7 z&U#b~U&qB6AD%mR){f4(V)qwQ0I}QltmX^>uLw+>xI~$sulQ41s_9P&iN?IF%tQ^E za=hk`lm|E~5Uduv+2(K-D|znu_{6w3rca;V8Y%MAmXj#}+K4iG41owmV9Amtyv?lt zb6kS)+Blimck#s+t@2$ex^gfD5MAxbYQqrl z8-Z)CSu#8)$Mi&cTKri#IVn1=R^>O1NH2iv2SS_0-ezvGe3OuD_|v)Po?9I0brK^# zQvhO6VtE(>QHa1DcRY4ea?R%!~xq7aVV6oDn$D<+KVo{_%P9&U+ST3a%(@ zes`5vqepAYvU)KDJRor0bxV?Z_DFo%WHQXn$w@RBjXDpx*sbFT2o|fo1>H_x>DRB< zeWOQ@#ytwrm6!sEuJ&ZLVF-9c0L?rJIa#LH(lZj~+;;(9)BJ?cC1;(;`${TQviO!#WFJlA`5|q3zz8A(&Ar9OEX>6r%$>@so*240y2}< zYI9iZR>!K$?6if^u(yCI0GYjDOdN&)4Fnc0d|8#6+VVnbis|w`x#>E!N=bt(qj4Mo zyWL^2*Y6!GDC<|V3-1k)Rtp%GX%UKaQ|PQyfZl^?w@GtiBqdt$L|HE;BRBc zZ*H|T*=^2iF1{=>T}YV%2>vx-6c_@sK;ZV99?Vb4OfKl%Cv{L#qEQwy#ext{2L>dv z+I~w)ik~uh^5oJ;sxwmnke zOqftEN4eR^L5{7$WMT+-LExUd9>2R!uaxaWhV){czZZ;Ta~n^pL9<+shWduXYgVnf zNj7qI5QNPDI)K4083J-e02g|dPP=Jizy6t%aATKT#S|qM#@T_E77L&+J-F}?7c^%% zolY0I=3IgcR7wShr;BmKg_X>3@CZpf6*98BDy*Li>$~;*3+7J2eFIKWK!qSvWTP4a zfEWvgK)4Zj=%J;3HEPx7fdjL8sMV3-C!Qyqt=6cLadVpi&nn>YRI+e4ktqIT!26DhfJM1wNX?di8C<;AThv< zJVPKD1pe`lr>7?;8dnS$m}Lrvj+A9B7CTf_HaKuoRISx!KY)Yz?eX!3?*|R)v1!Vb zDV0+2##w`6&6+hmiw;$evzQ%cfRaB$r&aYe#_1Ap_cQ7d`F3p>ZM4~-R-QR!)~vl! zVB-%>`J&`cEm&TLKolZy&prQH+`DJW6Bx=tcK)5!)lEWOT}ypSt7QlFw(Iiqv;Q}D z?p#Sad$CPRl*01mD@PtaTs2L>36u3k-H7z`gakRx5bO?@70p6dU2ws9E5z1MihN7~ zNP#M&$q)z#rr}H8nP0tk-GACa0Lv6B7-x>GRN2)G0V!PtUzz?p;B?E&&&p4HyB}fE8p2 zL>U5q|NB!b`uEG2pPCx}#om?{GnAIq*W>pWI-TapJMUchZ6v}?_D#I;#0CrN`qmRC@zHguOY1m15 z$Pv0*#l0Doz9hyT!f^X99CV2^>=Zp+uYUVhDIa z;GqYe`RcSmJ;oc2S}!@IyG?xYj}%o|+uE#aO(y;AH{5Vlv2@(zN%_q;myfHdX?Q3# z)igdWH9jo9wnPcoY|hVcVR(9|P+|%oR7f*E3;{0)+<*U5Uk)DJb3(i+^yl*y7gakd ztD82W61ZW>l3Pl=h!``smn~ayR#{oYzwiXLv(cSY5$cMQeQ{Q+ee;DE&Yc_z-b?|6 z0%gX7A>ai8^z&ai=(L;*5)wjd^T%afp|rGahtp!e<}d%adAAqwV)pinFTOPg_c#2v zPoJ~_8nrT{{Un(QIP9*CbI(6_hSUuZ(uzr48AhKW5J?C;@W68~_3N8<11>^_Ol;hh z3x^L?k_}sT-h1z&w?f7^0vQz+7OJ;y{pmi8RdH+Y-f4-UtOCx+T<9kH-1+C9cdL|q znF5d!T}GQB;01w4AA0t|oL;H-r=*xd_CJUterH*EZNb@R54|#)yn4JqOzrmS)vNpL z-(T@!Mtc0zq@=izc?>z6E+^O=H=aB1{8y<}rVF8vy?kBxvY!lrm_^`kfBWy{J#$ju z?Aa?dBwi=jk-(ut6&20(jq~nba%V*P@yp?5S-SL%Kk>ZqufDk%DWQ@F51zN{^_p`q zcF@;S@MH==3RD?QhJY6Y?zrQL5!qRB-{$4zgv8yauC7%mDXrcxX3U^-*{I)3qxfrqL)DXJsaaBu9TB5z%K+IefZgV$*BqN_vn!<>7s9AW1DdJNac$A?z`y{zXW8NgF;~Ix^=0A zMOE)*W+t5@^_~F?(P2|-)MKYlpT0dPp^q143V;TRj0Qu%3j%2OPs+|V9?Z|nN$`?| z%I)f^MrUzx^^*Jlam&M02r?pmA@J?D-|BwZwf{|=;a!B`G$b{x-@v_YK0nk8^(O?L8Kmfx$+>n)%GL{@}E>)_nX>uGnRCWD>58n2g zR6H16aR`vZasKqDD;B%#&gUB%S|wEi3YBvFhIQ-yC{8l(xtIyaJ2vbILm*%To_zAv zB$vy1C_k@leny>m&;(hwA}t z@k&MS3A1KZ2U-a>0|*p3R*oUi4FVR6b=ANDS(0`B)oAu9Dz3SPb^hHnLYN-mOhCBu z>Wdef+bnN3HnmB1WTsN7&^I`Q)xlJgDS%+mV`Uiv9uRosk>?g>Wh9Kpe^3ukgTK|> zgx)>}D(=4j{+s?6JT*o^3IvEb=$b!Xc7vtO_HJ97O^|{Ip~-`A`i2b~rUpu%DS$wc zW91kE9uQc%bg4$IRy~@Yktm6I)oQT|hmKUg`p*Y%d&&cQc1uPGpb~J7%Sc$*)Y$r& z6JtC}A(}$TD=cQ~duVnFXtco;fE2C5XvQo84GsKDy?du7NdbThcle^8|CfLH%byoY zL7&m2k3j!fv#h;yv#u^LuiHtV`Z0>=WRSFW&D#G2LZ2ysKu}|47y=#;ShD2VETchv ziP0cUoVTK)>Vvo6v2c~w{)GE9iX{@0%r^i0`RAYe9cF|n0Et?J zk&QhBluCHBfB#HLdjFEr+SWaLi-yM@s?kwnvU4{(Gx@I4vO224+}hDWQ;^nbHm_;_ zE%uu!0I^81d<=nZ5P10ErDGD}4d+O)@Y~SP=GwQfZ0-v$ENSUR1olYg2+Wx~r@&;? zzueT+Cea=Ne#EDretNn;Fi5vU#UCkHUWR~#2oS&Q(W5U*wpbi#=B(bm9meDo;L%r) zBTf|fjn9GOc~IbZ2(LMEpHpyx3!Dl|{ZY-4{f85Ds_I#@a_g5YS>n;HkLUSU`u5ET zXd$kbbRL~k{69;;uW0IX0^YGH1oyM zr7MA0t}GuzfD!`Z#{Ds_RF^i&lASxrp^wiMw3o+Z@qJ>Z&XJIe%&7OhCo915fC_|s2ou%uPaJ-` z7u^Qddvp$W%s`JgeJJR z{u9W}Nu-Li&F+Bh+YkTs!3S@Blqz9HOcn?bzx@>}R<1S}v@;cGj-)9RnhhNWjr#OS zsAzoAWitR@2(jmqBaojzU)_>BXmV@zpeyVtS>yMl_sX%R_dq+m{CyP8srwOfd(iFt z3E*XA4MnW;m;BWW8w0XQ4Ba+wFDk0c$73a_nt~JxUfE)`y@{3c={3d_K-gY^*k(Lv z)D@ZaLnhv3&gpm2fy_QR)->$!r8MJ60CxgsgZ^2>5>!i-dULDI`Fl~#6sklSG1(z7 zWy+M_KmK^lik24h?M9=HYF~_#iaZPvF&N!X_jFfrs!Y3M#GWw(29CHSt6}JryDT~V z7VPgkG|LeuO}Km(FrG);l9P=d7oYoy(s?d~;AZnUI1xC813^_=c@X_mpRs3UybkAbZB!UBBCJh-o}6MrH#K^Rgo{p2Nlqb$)p(=I6o5Bm*!`do=so=}Gn(?oJ=&Z%W|%!8E$ZI0 zG0GZPq}l`Nyx0FNzwvXT3G6}3DEPsd>ai^6usPKAm0PTFDgT5k_1}8T#BN3$0%SpW zWx+?A^hWIj6rS4u3a&EGTWXN)uBA1e^#? zWI-5r@IG2m(U6ys9`9NE2T(txN+<`^CDgbKQCIIX%A(+O)>&;hKc)VT6XU4gvwaUj1xU zRpXGU@gFhsPwT1j>|S693>bB3O8uDg-fS2?X{J3X zUH;DcfmPFMsm1C-n5`=I`rO|KE(|^Nh-El@>-0OCZ)aAxV63h@`m-$~<$Rc@FX{Y{ z{gOKZ#ALH-)tb#(jq(pPWpy}RExEaUlJoQPZC&Zc+&^zu0N8Kw2;hb-W7>6Zyzt(`!|Wk%3=foqY&| zu?wv?W1fPp`PdAgD?|c?=7|6aY<> zqlgv>$d-EJvgJqT-26rJpfL$iRJDMsl8HY5y?DB3vg||GPvZYCRl?bTqBVEu-TEi@ zZHGc3re|+bVN9E@QmK3wX%^9>t5k6MO`A52=}MC+fUbzJ-_T>he<%EQ;SH75lP_K1 zG{j5SJ4G1Q{m}d~fTL%gb>iahGF!ippwQOiw2|sBkCw+j^iAK8Fl0;uMgU_3RT>SN zLL@+Ks)_3h3Y*13%s`zIQvjXdi0vQ53n69E@^{N-|7lChfRXe=Tt+y&eQ*I-!_hm< zugGNt68a%j$(Gt92}5k}i~rjf^Fqaw@d*q8g;MceeSJ%PV5L2mLT{jHU7s)o&=rvw z{hc~-kul-^E&FOFEx7#n!6z|_gy(9j!3DjzX3q};y!(qYDZr9}7jqgDR851&6~y1W z@t(k`u#!?E&`%IntJSJfntX6iKq8ufvOCgb3ZNqzF?yYI`Ljb>=PWL596oVij6&eE z+5^z@CyS>ShmDwjR!X$^>#H&tQi5w5G4ZjadpD9W0W8T7f&Q~*S#^5NH#Qp{3QZ~D zxz!jU)P6-ra!dhqL?Z^TGZwyeb>$!C?`Z2aD0H@n2*f#=vr=6EE_3OjTA+FwpkJs8 z3KdsB{15+4x_j-deidYyLxzA-saV<8YObZp5Mu+)?nsX*fR1Ry*mcUyA3RYtalsq* z#B>tfn5AwI=!N!wn(m*6gz)QIG83pDG5M+F+dn3L=Pbz#fn29^t4gh^qbU}y^W}A< z#}q(EG-BvFdGQBN*N&fiyGx~IUOqnBU4hORJvh4VpKI;Cd~glTV~p5Jl)y8oe}3=m z&~Rj2#3JA}1L;&$H}Ro2km0AFe$uzgz!X3`5;63ha`T5z)tx=}7J*l?&R;~k_vBk4 z86$wwO0{VE+3l3i)(V%-z&GWcxjyBOkH^ufBcnqH0fkceSxc*h+NLlC&uglytIuke zjwyh4Bx2+{<<^g$su?%;R@V88Z}1e}0zFU(&`MRV@Y(*o)xnz4TW{?(;d^h-+5PY! zfFt$|4!f(G8g~wlh!KSI+vza{(2hh5d?(-h;UhI?oqH=N6l~-#vb{AmWsrUFM=)}B zktKX*D;DHA&~DBe z((11@n>TOPV&FLon*q>jC7IG$vSbNw89C_(TWU`99?%;k_824uvR6I_yQDli!6LD$fThsay#Z72(}>K=yNKY@%WJ43^@Y04zQ!mVyCtZ9Y=vm zi^bx0Lt_dc-O+&hK)j(W>$2KFGN2%zu&P9;w-3@xwVl?sKzz3ZPTfRHw2 zXqjbP|Hj0Ip%Z3=mTTm2)0Q8Bo^L(`s`^T=LSs}$NK7<%eeUmry1HgiSC>Hcil>2d zoisD~OGoPbEq#Y(^| zlZ`$RTLB3LCnNBlZ$AROwR>|6+FikDr02F-QGP7IqptW@Nc>@=gf$G3v_c8ZJ@X$7 zk_szM2>~3j({lwynb54{-Vw|c0Hp?!8=2%=Rz8defuzYzF1g5)`uTgHX!U)xqtQUG z^CxvbT5{5(FJb#8xxnF3j<#NTs6AwM$NQnHk#r%$-u zk0LCqL981ouJIYz9CJP#MwTQU*R_PfBMaH!p3XFWT41)5l9T_idey zo&qqNZD6-MIf&iLqO09N>t;_9Te!5-Tm;wj}LK&7N zr+VSkeZCAulZ{9kT!a;yv=kM9#nR>f7wzm0L%di~!jjLCm^vUVj2Y8T2=IbX>U6m1 z1*8%Lci+zxKqr_Z|3}*56^pDHz3BNZMm{8`)WB&FABvf#3CMwa@H-}Rc0X{b=*=)X z(x!E7N$Y7k>#X_geWC?ufOK3q0}x!UE+dEliIHL)#}q&i@X5AlTXz3@Whf5e=rqK0NBW#SGhF-`-(v`9G@44D<2sKZf&+)&ziyp| z-rF6VFsw8M1X3<}JgY5t@QFAd6i7xTiI)B&z@D5bs%{Dey?+sxLE>kiK3lZ){!2RPmYNsa!nu-tdyn)`^O;0pNDL@2VX#=h!NBsp@JZ6ds_>WXI z?Q*QIZ>SU!%mA$EJ)!jC$Z@W5@k;p|UJx^HY3GW@#l_h;1;rTvt}0_<3ZOI0k^Re& zm^LS}YY;l=n+A=6>M56Y%aDxzkDE%n%_sJu6VLZH_c{%Vueu+c+7pK|i7g(sd@hAb z-YeB%Lnfq*?Pvn(Y(or&{jnFDDS%)wlv`PAa%R5VWRkNyH51N<%9+;y&YC=miHCBN z9g`lP1#+`lmjFfAE&)eeWDTfM0f=8U4+I!i#wP-!M~}ASyGTs|;9E^zYy++EqCP9Y zGDwR+#zuE$bYHo2dk6=z(EFF)W&aOrJ$2fQ*|UT z5a_UHRE{Hn{Xe}mTLA>#>9jEg5GAjdO`+`{B~=MqHCk~dKt4)y3+N9Qg8tARXuc_SVw#jgXN0D_Gu)r2I0vM2W=L;tfHX@Dq&S+u$UDG_lV>}x z2CG5?W`!1ZtFqw$u9Z65mlJ4uY=^lu)b$ngOb=nMOQf9<0Ez* zS_I-LFCYm{r_)YxN)cK#7`M&{@D>Z(uHP9F_KN}n2|Kp97YiwnVkCkRXC zWC}obO&yp(n#xjY_QAj;V5OoF0c|DKb4a2QqL9=Hj}J{(s+2S%2il3?OaX+X`J`u} zuCJsvI*?vk#vu|A(3R{5&f)GSB0=1!mJy>!<*SrDH4_jAoIA28Qvgx&+9)h7I&d&| z?I>wZSyUr+OMxupU_!XJ?GC4j1IKgj!?2kGpowZ2X$dY)t3Uc{7$sn=qX_}dZUw`E zUC~sfh^`CnGwDOK0zA)^5PD1j&_p%Nv=V>V7-k6=`)ENR{nNJq<6uNfbt1kVE|-gH zJSJ?}-v}s70Yv<(ak2s=lmSZ&f#4AkAb#i8;K?uwR1o<5^Usr=4ky)kOy~u)g9yhI z0F@?^2N6YU6DZ8h@(_ke5wQrQeYOmEs^^bKEEKX3+-0{9SMVIQeLgs`!zd8^PEt9h z0A$g`^n^&-ww4|-Mk(eHP+-W5q_5Y+T)pL7Ve|l+tkJ5qv}D9hU{;k%b&$|w3V;@> zGNBW{^DCK1!o-L~1bV*n2yg=1Qz)ml!w!2oeyHv9K|+>ElO|P=Ix+jd- z3|@d57Ie^_*|?0IF%PG*bZWNJP+7UB^VB|SwN(; zmmK8GeeoXP>}=Ps9NMCz3>dO=qFSjibi5brHF^Mj-cExlfOaIJ>^oyMn*~H!lS)>d z9&bMas)iF*0m=9WzY`~3qphj2#w(SA&Te-$<>f(RK|ujJ%tTMxym_;+xv8Zu zuToH}6s{?>PMI?0M92W90H{GLKSF7rzYnebhl3@fkNkvV5``UsxZU4C>gEr^E{87x zMvYpivRdmWI-T4sJXm=InlOe|R<M`#wk+O_<5 zU$o`?+-kMX!UbC+O&Jxu;t1k*Vv9FZ05s8+8!h~A==u5su>amy@%%T|)N*T{aLN<^ z%T~zx@HtT;;MpN{qB2s>GWZEbD!S0d?n?EKvva1`r_6Nk5R@d18>3vD*x zaa0I}s0^Nqj~CwBwynVIsgRuS2`<+S3I$I$$}bO}bgVNq+fqlO>{>nuC@gKz^UVk4 zBM_4$>RsvX3?6)G`k+Az-f}vH-?39)jGVCZ_dj9T zd{h=MHZ*X>`S}+wTC!wG#PoNCg@tOn!#T|VT6-_ybh@mlO;&cy5ix*t6q;T8g8&B( zV?1aoj`&lE<&9DV5`Ov|GFQFmZ|&TH!~882Nd7^C=3nP@I*^}m6@Do7PeKaLB%WWs zeD9A#hh9855V=BKrlh1~7Ai2R0pPF>&68)$*xj)%%r4LojVQaeC1t?T%kBnSS`T;4 z)K$fJ-80H+$*Ln3ffS7IABfH0=~Q*+R%t{*}&mnF8pFN5uZd z|LaEJIA|I&7JmQRThMU&6c2Ubfy@e+67T>`l-^RbG(zA1-iU|01iUe@e9M+MEmFaA z)>-p)xX8N}JE%!g@$f?T-*Qy~xSD;hTBW4w{ew!c33&dLD1XcZzrC7HVNl}dM;L@=PcCs6fr30_WN5$-&`FnBtFQ9vcc+imv8 zu(PJ>`ss4I>`I=0+?!N%RgE_;?0!%P5Oa?uz1PQWeTVi9ijauHs=9Iv8=(S6e2R$N zEK4{MP*)T~&IeC}rm92&F@&G??fc+#+Jw>We>Hlfyh)ob4SKlX-5?06;rsS2E22Tq z9~$e|ufNvmbiT}U99;$A63S=Io|S|C{~l*@YzE*@D}_2QG57p^>jw>^ChrbK=TE9< zPs+sEKoV$64glw5@!><=+ z8}tUMJ4R zPJMIsmziH;ISyQ^J1DgSKhfXM;QTFbkDZ0yG0t9%{jdBk|MOYyT%*Tmhkh=Gz z==|{@d9y~R`HL^v*$luJLLqvtedb^tjL$z(ATJ*l#(h6R%GQrSTXqPCpB^1Hq!!kWo`~aUGMPVrzM`4)kr*dasa|H0wlzQA#G#J>P&3M#=5Sr4GHHnM*0+64}m@DAGk zsqch#;OJkYRLq+;bLKiRF9w?dh(SrhJPC@d2OFZL^Cvi=yQsDO5PGKr)U_qRJM3Ub z6Oj`al4C8AfP0DCHv`$NtFEiU{xB@&9j~yX%jb`K_tNeB$Beluxw+Z0EE+n00vzh? z9308KiI?Y*-@zob`}c4<9Ir^x`4hRw@ttBjf0Cam0D?jolQpB~m0@HrEo%~by2A-% zB<7H+u@+otB680TqHqCOQ-0VTh|O?lH!8n!+)U?`7UQ6(b9)vn$UAe%lAws3Qnm`e~g&z?Q|9DihEGXQ_kqMX+jm-c9EcK!rNJgnZ7;{J4m z)xG<;wiM#_e22=w;NFGYmNNjzUW9NY-f97T(O%FU{T)b$udb^EC5B?)Ev>{^JRBm? z;Q6~0oj(cjj8Q(l1|Fj!csOZbbE{Fmzdvr=A4h)k&FdbcYkHG!kBy+MDizciQv@E0+P`OVq=CsHIA6{HNfIGX>f%7q>cFYSXF5H&v<7e}wRq??+T2|(;L*Px95~p;|6rxP z4MSiz;inN4816!0ZgGEXxYC6q`0?hwz* zNhcZV3Wbs%)~{b(UCYbJ^D?n~KmYvmDd_dHRH;-*g^i$6Dn6V%d2*3hncDL)1<;N} zh`*EXS$j)uLMqkBe<7{{Rd(c@;*7Pgg8^M5Jtq9m<84;=N7-EOF$=rdEdpe^vSQ!9 zf=lqzZN@+z;#npyqK&&>AY~)3jBqKQC%g%9e9f2a7~_AC)ofXb1OI>yZSqB*Ja;*S zBBe%oyO_LP^GGrs>B@xtJ{19TQqC=>-i^IG9GX~CKU)U5FWl|D^N&4PXxG@KP;mE< z&Yw16LXU)a#?Jo=DQL@;CQe9~;{JfV?&QPGUKv)a^(&0=AJ<*JV4m5m_BOSOzt+=v zzhdad;NqhgSftI9a@&WQwP(yJMPK=t#y_s`JJ04GY2lAG>QcTaR7l_ue0y8r_B?(B1CUlk|^ zW&-jTITEz(u+hkyO>rDA#Bpee#-Q6qr=2${Rf5q4oDO&58C-%=&nY;)0Gw9f@SDRa zAkS-YW0b~hFb$36&fjhBS@S9wj_mapeU{%p1b%b5tmpjl%jz=!iiyj8Jj64x`^RAC zPcRY&H#Bh1;Kjm@h@s6txvjNrr<9#P;pcP-#c^?lPP{wHA?7-!N1z@7x_yOCHE?_# zpwUj?l)Ru&a_*1P{f*8mJj2W*aK3N4%{^a!07=`{%G^KRcU@$j!-*Tb9>NV?4@fCz zUf%p?vGZRnC65T9P1aSG6IrqIPq$dCJJHuaLrU4LR(ngF$%yN|lYaEl<}TFsW9apW&)WJD+0ev~TJJHdATM0TbCy8K@#IbM7!Pskb|AS~1x554X9}PTCV~7U=AM)$h#W@z@*|rQjA;~+scAj$o9yYWWELbppD0*5+E-IRS8VyGM zywRgaQ#r7kDS$3bhAvy|#qNTMzdxC|$6v(!&yOQbnD~dmFl<WtD zpmdV-Qqz$$WK^6kJ|a%#3K<}NFj7~M&0Mbm+0Dz6Gzj3x-reDhIb(pk714OvJ-R?nmzzS|lTuj#i_B8*ZH8ZUbEKmAoE^yHlm$ zKA1jpCWeopmzVXn7PLnSOGrA0AeuqtkYoRsJ@Vu zl?ZB8_y4*{NpZ$zmGY+-UU=h)MT@TWc{Z#su||!$G^MT0`9JLZV}A2!W@aKR{L?gu zkJtNxjmmRWw*q?n|1f*b?5n8|>_DXZx2QwLSh?hs3dwfuMI(lBd%nfZT5S!HG+Fye|^~;TqHgt(A}bhVOyJnEc!-Oh-cA2 zcE~tkLO#sEH5V^Zr?-k38raMtm}w>n?hCFaPv_p;=?UMB=BeE9%);tSFbb} zJ9Z#sXC*;;S_0tNu>mo}0Aw60j{Mr{#>(fHzH!w}w_Ll@UqZ)2JkRmBTr}lRO) zf1C{Do2HR>f4c(}p$c3GMqbc4v2mSqz`jRuy=S%@~K@QgdBIiVsF0xDglbL&@L3qG`EEqTT zG)TtLCF%5~@+i^iHGH;Sb4GoAOVvv+yz%Ufi>|$=yBcBK`?&i0=BN+x>Wyt;)6BCVElgV(`+ixzrs;$Mg;Ks$*Z1q$vR1_HE8Txs87R~o? z?F24fFb;Ba(?dS$C%D=jP7AtwJ~@5HjAc^e99p#|b!{lnk9+9*ZOx~RIgLp1l`W-dHbg{7boXvKxRA2?2Ub^iSP_m?bL;s*7@f{&h3Ym~R3y*_lt<>OUp zYqh$XS}ccKTidQ&y!g6p?KLDJo-x?uo9(}2;X6Lw02f|(CiLx_0s0Uw@^-}5YOz~X z8s$@XwBuhp-k0i{DS$4>8Xx&-SIdA=L%ZCLxu0>n(YuGl?qS|N0k=K6?AvezU4$L} zR~)BZT3Gn5SD*ZFDgjbKbDP!G++sP@(rUTv<(JnrIUL;fSPAi*fbN|0=ADHj{tO^H ztHYJdZ8nQWqj~_tJ3kgG8A3Mg3{{1K3vU1Dqctv$bKQmuk0GB4ko5ul^mCRA-`eef zi;nV+@2}CQAu%xy@GM-g+a1u@=)aRpQj!tKPTt%;>0#~o$=lFowwg66)t%V+zj*4~ zA>EzGp8?>18r=Pk-e6Z6mAuBF0F{o!=;t`z;BDS>s6009oKBol*uW`rf&&r)?OUVw+4iD+t)o;pfbI)en%(V?Sb1`#|FZ{5hhK6IK zd)UQsiZ9h_=h_`R3aWh-^!5DX4?q5|Lan$x97@26o$0gBt%KsDHNM0Q`E#{e1(PO? zf*CW$LS9}U$j(m1h1rvOvZkg1e*N_beEszIr5DiHOA*xfq;>h zFit;<&rjhEahrQS#e>-KP;_}Dt_=UT|BJFDVJABfzkB0|Gy|_mm=2L1|C zFXa`+gLK$eT{RmPF1!HZ;>3;1$c$j)#_!;XC;kT&6}9e45>KnCQ-(nX?&38NGY>YT z91?c^4RIRf6;tQTSsM;{{Kt0+3g?^kej&&|0f+-rKLEvU-Hd2 zuY2`VA3ps21iM`|z~$nyc;1zTopU;tO~pmaWE>R|C1J#C@^0gY{HNo5j{^?7b+pa^ znzo@0pP{zn8nAqwAn-Lf>8VyIgi5EA|8>X^*TI5<0!gB2B41Hy_3BUV0+;ZxO0Cd{ zDiCC*J$sJA>u-D>Bo(^F2M_Lxo%n6gqepr`gv-k-@qm`EK!Yc*8uU2H4{$SGK+HuH zLRZfkW1Qi_DO09=B_g{dS!AsM;vV?!tLD5j#!FK37$$nm+;jY7F8P>yzQpnFqQb%g zc24B+cXQLmjnkT2%`0$WP}1G$b#*Q9 zs;UAjUfUcF45A}X@3p38b0c~koik&`jGw~^y1W;Gm9f1bE5(ap+Wifrk=Q-5G50_@ z*7IIGQturp>Kn;4Cr_KUar3924sS49zrtOpIa1WcfeU5J-up^+o&VEM-{GFFd8#v+ z!jaCtrl!XIA=h@R75(QO;BG+gSX%Q!r0Pc3A@9ItY-kmfBjt8 z(tku=Cj{A#fDn+Qxd+WL&nG0r{k=PLPe7H8vO@d!@7L@t-1jx^5FSmtYU?-bKzsR4 z+GGQ!H-7vOxc8pR(K;u9-DY!l>h5oJO>&S99zUd`cVI^^*U`PV$~QH(LE+wF_;BTS zfF?>}mMm5%RKs`gURLj|jMVpKJp*tllp(QyN)2*2>C4gFgNFFc0E(Ln3*VF1ieoq% zsvF+@`}eovc=a;1Qh5okY)~1v{q}pQtU7h!zrU~1+_~pn#tW|NZ8nG31#+=88yebR*|M;$J$e-L)?3cQQ9sdj z(UXXY?Py6Yy!z^AojU&xHM{_$tuE^DJEWJgRsiVw8NO|KA#Db_%!s+C=j%%#yWkmF z*!pp*i{3rl(|Ab9KNt*EZ{yf1;&7tKLW3?6)GSfUS5nMz94XxgQR>MWUkqU)`Y z3M`~6)6HC4I8M2kjri#|{Mt2Z|LFqZJ`5q`m#K8~mOZ#x>PPwl1wnDqqI02N-;^LI z$g5~&Wdm&c?l;)FRh&~B4w8P==@Lh6-~I}5Q4U#>_Zk4NRD}$Q2xny4{WW^`ye*3n z|8XdZx#u1>;+O8l!mt4kY}l}2xy5WhfU zcDSetR;~ITnwrG-<+vVjn%Ug&Eb_Qc3?Eu~WUT-MW#~fW(gHNpbTn1Pkp9W*vWeY8 z%ssd<>p7km{$5zP!v6p*p$0I*`Qb5-zhV_~*Q{ClBJOd!7DGsQoeeai7s~r9zL8yx zN%&<9hYeO+w4;#>{>bKuY1Hu^HTmOhrSU<=AoA&}D5I`YWn}C$BR@)r$ zDQp(tp<$W1#{(!aerw~#jaeAg^L-2>F%D;6o!0l9X!m~){r!LL;DsU=xCRgI1vlO> z18nH_8HuU9q8@htQUsrUz6Szbl6Q1AA-{_w+oS$6(JzO>W?jOa;1FGW^r zYBIx-qH0*Z`gzgsFNlg@6B6z7>Dsk-I~=b2E2|rHD?j>9wlirQ@lwY?N`kGe7AQw^&sSgXgWY?I zq+m4~*8?6!!gonQydzC{Bfs3?0zSgtj*jS3y5_BIkg^$L_k1U-P|aH~cF#>Lb`PaS zmWa%X6)SYlKfmF}s;Z`ZiC6?p_78s;0vDV=2HhcpHJ=16O1A{+>s!&zUkAH(9)j&V z4!ffYc3U90ha@8H#C`i#Yz>Y~_od}K16Z;`%{qSo(=X`VvtCZ#J+ zyF;4M-5?^}EhSx}yHj$4pd!3QN;;%F1OWx{TuJb(3IF4hm z^?apb=(AK@`j9(GF9}6b{Ir|H{M@e!oP|Lenupf>g@Ff$+qc!+WC9*jrBPG;uQ+8* zcBy-~w|~3lyH$!xxS;|`c%0C%7GNx~CV#XV!Ike^;@q?;=387>5OfXwR=v(2->%NS z{@Jr1n6wMp2Ae+YrwjNFdW|@OagUTe{3-A5F2coqT1Hp)AB#1|b@wW%p-3wR3bdIp zQ9JY=GwUWiRXJns{mXq>Td)HEFwFf&t2R6IBbjM3SmNhIW`XP0(?4#O2&tsRh*Ab8 zH)oM9=Zou)@Uf;3f2nK4{&L zYunh!m;A*R{RaPt-U3?C8qZgn^2`aUlG4I5=ITfB>KayJ*(e+|67f1Z1XPN> zL&-1Hwy^&KJ>$Bvy7eugB*NAp>-#_skI1T5U$>V{K)Th7?Hp=4!TZ!h@9Wu|#Ax!s zW}0}j;HOz+;MT&Bf`Ihb6ZAeC&bL-k!l;P2VnO9NK#kN(7hnz}y#4qKMBmO%LYWn+ zrmEXD(gki(!Js)$Wtd$bdZ`tdAT3Gfum0pc!AbjRkaVV-Sw1`Qb%U79N=AdjSkauA zme+E~lXkR`>XtL3L7{H=4n2qR(Mf;wV!kSFoR*F^44+1%8|v$rJjT0fPED=ubumHt zd9fib%AgWL{u|Efb@!}hYkrU zNpHogQhvT>ZB?YH0jM&K!kn9XS*aUf#O-RA^=q%h1RXFHOdWLHLn)qXIWFcKw3+*gt%6+eA@O*!|ljbH}f*>|Sf2m-xyi3JXVZccE&W92{t$z^E)zF9H;+D{!+s zlut_o9JW?`$Cn!d_=T_a-0WYHDClP5v_vRY&0_LVnD$t-`ZU~TXJvux2DcPfyCkd? zy2+#ElV24SP3L#hNZnQJZT#krEx3yuK;^~Usg9` zy;E8zKSfoBM2g?`JLFixeJ9)eR+U_i`;C(~%`eG7&pYjKk+diDz9S3EeL#0LM3FpM zj$X>P?)Vp9EobhR|F8kh%ZlB$Ct9 ztlO8#s3{nUnvQ-VnoAX^Sl@@`jKfJO*-=Sg@c08tDJbaL{quzRW8qW!)(+P7EJZa! zN~gicjWBe%?vQY_vB)I;V2_-RBZOooysD(XUDa}j{t~APBP_}!0bb^i=mVX`;9#YZ zL6vtbL2BupKF*QGS`l+ZUimmfNEApTno8_q!p6QYHVxaZxM3~k zTwFx~GXyy=QPQ0vKBCvwJUIjH0p0BBwF9LnyX(&}D7YbR4}CtYiIflIs{@cMo6x*c zQ1#U?+_u?ho6mBM?(?qfbeO2*9(Mw?=J%0_<>>YYFHPnEcH!$6E*w`EP>3^ON*}_D zJzVud+3m!dqjgKi%S9JUpt*7f`6c5lBhE5t(Gz10B;NNW>Kc7pjEZ}Q)y=EQz%V*3P!x(O#9ti=)q(m z<`Sl6=dO*e4g$U@3<7V=w6mx7pJa|W^4XsBzPz(=7hXsV$gvQB>L9E~MrFK@j}^4& zJss?hWw}7AT7@VPa)8Ud!*#Ds;i01-D(suiQy7KAXa@~!KV{XN+>uI8c~509fKaro_NS6@&zL{vjHE_Pc|}{cr!WB4OYY zuBJDF3zLRc8vgN&YXo4zbp8?3GnR~p{r}WwzQLBbORJKBGs18J%~XQ6_E#`; z0TmtglH-4M9h)hfil~3;ch({9a@+WK<`Xg+m324yR=8X1ZU@_})}N>$28?S0gNl7` zN32yI!UD!i&zY^cmf5}+$mpbS&j|!4eQ(@SS`ys`_G-8O0<_D# z-^lNG6!m6i1S=FY|M;z!E|t6)@H{eQ{sFs#xvhMcdtQ`0-j7@v!C|y!P`$hwh1;EO zRo3#RU&c;DG+ZF6abqzcgudr^VO_1zr~c)kamwGb5b?#b&!oq9_SmD@dn*?L!q>$R zqIP0M*wfh%h5ftlpt^2x)=Vz~rzuQhLtd8kbqyc2v=%5w>(PnMXmy2oY9D)4c@y=l z;G($*tHXz1r)1xcdp)oy>f{rJyk3!bb7PiEr$y*28=@iluQtT*kC|3kGwS~0som+z{*bvb2#q`aGcmqQs{KG;!xzbSB>KzeLrFyYu%Dfi;%D8m=&I(9zfbxjLiDEY7jUM?K$DJ`^tSx}(f+w) zkZFFI{4(S&!uM&Svl0q_aa`hW*b{AJNIPo-(Z7YxOOpfqTIYkam*Vu}omeWl5Lo*0 zAp7k3l-KxjpUi(ou2_O*-FM%U)u|+*M zV>o>9TwOwP5>5<55EF`NhyG4lWn3mU7Ly@?<8!?L)RrdlQrA*W3~vt$vmWq*!0S;` z@?nEH9sZzZ+yCCA@9@C>3y{a7r^A?bN?!#c$HK;&8bZ*EhH*$Kh@|vunZpW7)Tf}I zKYKGpmavgJYuTCx6-!*V(UoX{kTh1M4gAXR`%?4%N;YgWjGquz!Rs|JZ$KS!HzjJ( zBMwCb-T3%rj`BGAkKh+Cb}y@I9qV!`H7Bn8PAR(g@ascebjTIq+eg9}JWFA{E&`Fw zcLM##x8RiS)4c*w*Z+Vq{A|u~QR|DgnD}PT2v%H-ZNGN{wM=#l5883>J+Nlv8#R^bXSMX zr5LY{qKbMtSJBZTcbES*ZEP%e9hH46KdmIEbBrW5xtwYI#c;m}{>cPYS#?E@8}rBU z4(e&~Ll`bj*6Edfr(9|-h#ur{vk{lD433g`iod%#lVxhQx?0h*$%)#b!F!k&pFdWv z3UIWYL>fv)WUW-rEB^kSjQ&%MX{ix^FP13yV(U+Q-9;H{TncD|DF_SW(&9JXKcpQp z7f$2F)7qJW;l5LF>8!I4<6jx_0@4Kugdr^Uic7JN!8jw+7S)A8RszgKN%_3u%Lo(oWD9bpTIq9*9Y3{>Q^hvkU%IU9WFFXDt7!~~ro8Z;vr5@L zvy3Tftr9kipn4Sbkx&W(BnlL7ZM?38THRn_1OLyLx(E0K%xqD8IY&hVC&>Rwyt+<9 zNp|bj@vAWvZIjiT?4||~`L9mX6sPp@X-KvtTu#*cC(Osc@`L+R>|+>_wkyfnwNyiL z%OlHnC}-lk5$?jbWz-{49~QTi3^V)S{9;l~p@JV_Dajp=jJQrH#5Ues{SZ*lN1-&G z;8w{3DLT5ulSI_R`*!O(I)4EVg8pHJE4sIZhXeMNdF<8XJ%YYO5x1o>VvO1UhH)AcXP!7RUCrD_t9SLB-T2iBuMIw$+BUJTsAa7iHg{Nkr@4S zm;avJUcwF!{I^%8oZJ1*qkXT#z(M3_6%%E{($7*K@_2c~3wGuwsg(GNSBf@I24DXT zD4|sqZWKM!zUw*Ot~%E~Bs9PQ@$SBd(JcSm=JqCh#1hdyXd*UJ=Jq~KVRoTwTW>wl zV#KO8%beZ{KWBm<<4-J|puFv*tbTuu zMW-4yHdXe)zqN%EHx^9{CCr~p55tQ>W%~jrfX;(7wT$qbyE;8Itq3fw+71l!zPd0NdK;y&-ux9rpi%%0{ssU*NJ7_qM}2oAKJQv-kOqUjSi^|ghZ2TBq|M?k3^7fvG1~K=KXa0n&aZp zOp*F*!mUInesJ5zwOEIqJO(c}4w9Qn`XQ*p|JCfe{(i9$Vkk$uU1(k8ZC%&52B!hl z@TA^)VJH>E5{@Vlnpm^nDGom=8Enp(Y)?>6d6iSk&1iE=X~{wyVK(y>(nVBCraBcR zoHV+$pkP+kTY_s;zQMGPZjcS7h;C`}58jy~Do3kj$Vjk0OM0r~XZsIa2*EVMph7et zBgEu#v`XKUI2}t-xts&)I5ICCcI~g=8Q0#_=dAh5v5Gph(ZTA4)wX+QUzr)N=dW1^ zYpGG!U(fn;SL^^oK`MwW9N`_!!#LjZ@o;eIc=@G|`vhf}X@t@*iB1XHYN zEg;!AdhM(Ms2B|0>e~dM_9)~)>q0czC^_r(`sKSoEO}4;pvqAr;rlz%*EJ)oD^`voUU2Kd7l z0oF@{Us9RAIOPBw!FhQ{4gkkBFr>em&ip>;morz=XEq6M=3o5IkDkX=bK(_sG*Sy= zA|L6iq%*?%U>R`yDw*#}%smpv88?Q38*7bt)DIVVSDN~(_D-ISELEWLN>)=DDu|Fg z!eI;>X$wnK$C2}Z7#o%p)MRZlo>wcU9jLe9SS&G)*yD)WRDl#y#W#oG2|mz-M3(k7 zm$gu+ee&u@%-Mx*a(|J)_!Zs{Bz;yd^6_s26b8R7w2hH?PdOi#r?n&rM^Zy(Vvy+G zwb!4K(Tp!QufnmLU%#khud1+{9+`i_3XtK&D3O1h9xzCFc&F_jvqrY=BJc1)?7^bL>mK=ek*GiK+5QGh@bU_(SWM21>mvm>H{e2fI0x$(E&5IXk> zVAC1SUvi^powNRI$J2SnAGg&mxaj%cGl7(^SMp>yF*NwvAN}dLq%@_)x9gkmR{hXH zB&njz>e{qJL@7Vp+?3ILe~i|$=@l6s`E4j*^wbpikq}J8h@CWMJO&AXyO_%upFgM7 zMddm)i4(FitRerq6)(*H{y6HJz)AQ71E2c?b+c#vmzzD~h~v560c2GtHA_Gh-In%A zA$WoeskZJoP6atvK!;x%eJC+(e{KBbKalMZkrR{rqI-B;iZhicHFRKPVA*TfDq;t} zj@8L;tj*?65S{u0AGPo!_mp~W4*m7XzvLcK=IT~!6&}o@)ZQO*LAX@k!zDDI zY6%_Rt7wTG1QkHggq+O7@C4fb$vb-1_nug54-hBZ{@s0kq4rk*V4=;N#eQ?pU&x7S zzEiuMstbJ++KDS3Uu*V5rC-eaEEXW%G`lP+#vxxYBPB~~=J|taS@xBDf82gp*nJg@ zMv|&0mE95>2retNWa9?NUWXpqtaTRDHCAFHLIw!_@GgVn6C!{ z?*{)$^+Z|<6Pl-xc~y|_-;hRpgS~uj2_YXG$yA&re~9}SE7VgsGxkROA0D4Sb_?CX zQ^qp3BPhWAWK+!aNPL3?^~n@zVM54hRf9_L^MsOhCk#MvmB$3>0asFaX!kO@nV#jdGc89=?f=UCLA2LQ zK^svuajK}JpDmF16{1k6zPST+JhXQ|LywK*K9Q&RO|leiBfYj{BpYU1m^u2%m?+bty^g zCrx}*9}NIu!hS6Qqj%&g-C|0fn#lp|MytNs``N&TL6Lb~eF8a+&vID$X~|CJ;^G?< zv?YkC;(tvUx}gVgt{+Sl zek1mabP+*g@jpy)`G)_jnNH_2T$Qpz%Id7Wh!>r;?BkFo&?p?Ngy27-zwY1qYG4WKKA*Ii0awiK60=B!t z*2s%=bCOzXuXU@ae7tfkLLf7uxFG#cO50p8S;CrV9-BJYzM&!70@&7Z=pFO_&_NQS zk^%O>C=`RMSl!umG^$G7pDjCGkzqH@;&ojkBwjG3Tol0UTHdjP0eA)ughl+3_LoFJ z_}X^1E5A}ejc{&ccYRm=;YAsB#?Om9(rZYkUb86nGm-L9;A8p|12GOTwRjND*tE1W z{___GEvj>8?cIZmzs`Mv8Y^6OhCfF{GBa+IA&wIF^}_F&oR4Lw>Scp1{h6<;?u1ta zGmdcHq2Ed4R&}m|O$CUY03*lZJ>eh!N)`l1uAcvo)M=4W1$LL}Hx^jb?=ADRd&Kge zVX&Iq57_Ol>U$Xw*^+47+6E1Mw`upUZaV1+q^n5DI&Aayoxa_(Q@g$EtQ#5ZKz+uN z0WwSmHpIbK_xLW+o`pUf81A5(bh~(p$;S(W~G=3X}+nN7)NK*Gio9e;A* zU!EJVjPAt%ak_W|;>5N};Y6(o+5^tG#K|a8(eGh(Nej4ZNB?U(8RF07`x4YQmR>Du z|8`28;@8)aDy*ha(LTuw{=G#PECi6ec2u25CTd@A%&iIqBnV1JgP&T&~lD7TmKePQ$5P;{vA@qu`+1@HKHlT#^4D;&_*WzW*;i9$eX@+sdtBW zQu!uJ1`N+LBa01>xH*dsk@K@_+(j%?fTtw%iAoM5oEk<&cnXe9pJd-3`eh{c95Xp# z9TgF|nQ|MBo98gSJz{h2y?3%?q4DEDicmjbJ30t3#S+;2SpP4SQNH2`r=G-12ewM!b5_ByOMYi#|G_{-Mz{*sq6XZ;)8M$$N$eQ2#2*VqT z%d>JR>|a$x0fUm_sm&W<53YtooXn*cNxy)GRRorei*7cZGFlIm^@i<*sg_DKZGVXn z&?n<9{FtKE6Z?ux4`5Ji9pJ=!_b8*70l2b`0mCjN%!v)(dr^#U4Ig(Baaw)2+PsX( z&YDfa+@c%E?pP!TMx6*>==nKCC?`x|x5OMgdh~gdHi%z13Z!np`&D}H#oJ3$R#emE;-{~1vPx#%5i=k9+;#g-FFu2Mq1fN6h@lUJP{0H)6#D0^+OheS3nyeRvLqiWn`FNZOhPPadA4Si1RrcjkpSvdvcn%hjn{LYV%xkA9nwHVg0P^5;@}JnBxD$ zuXXjJ&tl7YfgIq$J9^OfuiT%&P*K<%_HE03?en$C`Z23t5xWu5BY`OAA?K3Po3C1y zpeNFcY=!^2lDWbfK78;?#I(3=xvskTGZ~TH)U%iTWYmS;@=GQpWL(Y?9yuS}iGLMy zq7q#B*mx8XLhw5K?IaQ-cUk@Zs9_ed@kZ7PUAXy{Ne(CIcN0!_0weqkmO-Fvo3$8f z>x`MLYC{nKWs&$I{{KA?&HIb?5Bh!Jw^>CC&)Drx&Ox0qFJQ^jWCcQ)NU)Mh6k`v3 zF9jvlMeye!AYZLf$8fzF2+ku@A)Jx5pR`2pEMTH1RszSF@g2uPn72SRSqG~>2g-yV zPS~F2mEveV13rIOpyysBsEhDQ{_RwxD`c>Ox?OMn-;U3_BVfr*{Whv|; ztjzR^wV}atlJk_;k$s8m_iG<0%GLyYivWRZp-;k!41QGmdV84tb#*oTJx?%7@m<|dhz+QKrqa|=Zy zE(A!alJyJ&B8u#}oqxF6qZaM-4te!S$op^lFS>)08i}B*HJJ!&(?U=MD$lW>7>+_Q zLS;4X(GSn>@fyRv`KpDjws`bfiX{^xKx7r4Wnsu3aY)0tp1*4%)c2xX?o?L%A$N)d z3InmO=|RD;0>!mTgd(7uldFw7W+junFVx%Pjvyj6Fr1r)6U`1c~<+9 z@XYA4Y4Zg+ts3Yph$3DA1nDJyoBb)FXq0xdd*|NTOF_{{7>rO#jWvSJNk-I1CAbMBoIPN*HEozo_jvF4FeU`>}^GdwxH%P@%$JDEtwO17d5&EkuAK zS#kQib+|koOl84ssJy8(VMc2>_*0f(7S_JXs1S}b^`-{sDO;FMG|C1_b>aLp`iApO zS9osT@;4|*&J5=}{HY*>0&G3-v`9}sJ8ypk24ZVur9tSif?sxTx#Y5m%ZNa0W`@!~ zIPae`gJP;?h;btaaQbaeItMg46G^}?YtR4Vi-3XJ)NHXKU=nA~)jvwl@kzlN=mT;l zL~pp7iE%TZ;$kES8pSLi8_vJ_qf{p$sG4`z$ygiNc7ruE_~-V$ z*kw8x(jzBugBw{#nsE~ONW(PD<{IN~EOcw<;mOy{*pTE1wOw3mjI+2c1Gefn|k+J7>qm|*lEAKP-OEZ8$8FyK0m`CNC+_OdgzE&l6Uht_tX zmuCEbf6krvafmU3z{0TCU*g+o*&|Fj1G1@;^z`Y$+}uOIhBKz{&d01Yf0Wt&A^|1o z+b}?xl+Xpm5SbStvf! z^t@k9xGmH7^){VnfAY)-vYzxA)D$~xTd@MhBJ1l#r*2fx{}e$GII2g3_=aFKI^CO- U;#n*3Cm$enWgVse6s)8E5C25*AOHXW literal 0 HcmV?d00001 diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard new file mode 100644 index 0000000..13bc889 --- /dev/null +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -0,0 +1,1156 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + Default + + + + + + + Left to Right + + + + + + + Right to Left + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/keymanager_mac/KeyManager/HexToRgbColor.h b/keymanager_mac/KeyManager/HexToRgbColor.h new file mode 100644 index 0000000..b255817 --- /dev/null +++ b/keymanager_mac/KeyManager/HexToRgbColor.h @@ -0,0 +1,18 @@ +// +// RGBColor.h +// keychain +// +// Created by Mikhail Lutskiy on 26/11/2018. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface HexToRgbColor : NSColor + ++ (NSColor*)colorWithHexColorString:(NSString*)inColorString; + +@end + +NS_ASSUME_NONNULL_END diff --git a/keymanager_mac/KeyManager/HexToRgbColor.m b/keymanager_mac/KeyManager/HexToRgbColor.m new file mode 100644 index 0000000..0076e9b --- /dev/null +++ b/keymanager_mac/KeyManager/HexToRgbColor.m @@ -0,0 +1,35 @@ +// +// RGBColor.m +// keychain +// +// Created by Mikhail Lutskiy on 26/11/2018. +// + +#import "HexToRgbColor.h" + +@implementation HexToRgbColor + ++ (NSColor*)colorWithHexColorString:(NSString*)inColorString +{ + NSColor* result = nil; + unsigned colorCode = 0; + unsigned char redByte, greenByte, blueByte; + + if (nil != inColorString) + { + NSScanner* scanner = [NSScanner scannerWithString:inColorString]; + (void) [scanner scanHexInt:&colorCode]; // ignore error + } + redByte = (unsigned char)(colorCode >> 16); + greenByte = (unsigned char)(colorCode >> 8); + blueByte = (unsigned char)(colorCode); // masks off high bits + + result = [NSColor + colorWithCalibratedRed:(CGFloat)redByte / 0xff + green:(CGFloat)greenByte / 0xff + blue:(CGFloat)blueByte / 0xff + alpha:1.0]; + return result; +} + +@end diff --git a/keymanager_mac/KeyManager/Info.plist b/keymanager_mac/KeyManager/Info.plist new file mode 100644 index 0000000..bec4c35 --- /dev/null +++ b/keymanager_mac/KeyManager/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + 1.0 + CFBundleVersion + 1 + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + Copyright © 2018 Mikhail Lutskii. All rights reserved. + NSMainStoryboardFile + Main + NSPrincipalClass + NSApplication + + diff --git a/keymanager_mac/KeyManager/KeyFileModel.swift b/keymanager_mac/KeyManager/KeyFileModel.swift new file mode 100644 index 0000000..fe22157 --- /dev/null +++ b/keymanager_mac/KeyManager/KeyFileModel.swift @@ -0,0 +1,69 @@ +// +// KeyFileModel.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 24/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Foundation +import ObjectMapper + +class KeyFileModel: Mappable { + + var filetype: String! + var keyname: String! + var description: String! + var keychainVersion: String! + var keyInfo: KeyInfoModel! + + required init?(map: Map) { + + } + + func mapping(map: Map) { + filetype <- map["filetype"] + keyname <- map["keyname"] + description <- map["description"] + keychainVersion <- map["keychain_version"] + keyInfo <- map["keyinfo"] + } +} + +class KeyInfoModel: Mappable { + + var format: String! + var encrypted: Bool! + var curveType: String! + var privKeyData: PrivKeyDataModel! + var publicKey: String! + + required init?(map: Map) { + + } + + func mapping(map: Map) { + format <- map["format"] + encrypted <- map["encrypted"] + curveType <- map["curve_type"] + privKeyData <- map["priv_key_data"] + publicKey <- map["public_key"] + } +} + +class PrivKeyDataModel: Mappable { + + var cipherType: String! + var iv: String! + var encData: String! + + required init?(map: Map) { + + } + + func mapping(map: Map) { + cipherType <- map["cipher_type"] + iv <- map["iv"] + encData <- map["enc_data"] + } +} diff --git a/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h b/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h new file mode 100644 index 0000000..6eb1e4d --- /dev/null +++ b/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h @@ -0,0 +1,5 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + +#import "HexToRgbColor.h" diff --git a/keymanager_mac/KeyManager/KeyManager.entitlements b/keymanager_mac/KeyManager/KeyManager.entitlements new file mode 100644 index 0000000..51a7cc5 --- /dev/null +++ b/keymanager_mac/KeyManager/KeyManager.entitlements @@ -0,0 +1,10 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.files.user-selected.read-only + + + diff --git a/keymanager_mac/KeyManager/KeyManager.swift b/keymanager_mac/KeyManager/KeyManager.swift new file mode 100644 index 0000000..bd445d8 --- /dev/null +++ b/keymanager_mac/KeyManager/KeyManager.swift @@ -0,0 +1,60 @@ +// +// KeyManager.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 24/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Foundation +import ObjectMapper + +struct KeysData { + var fullKeyName: String + var description: String + var publicKey: String + var location: String + var cipherType: String + var creationDate: String + var keychainVersion: String + var curveType: String +} + +class KeyManager { + + static let shared = KeyManager() + + let fileManager = FileManager.default + + var keys = [KeysData]() + + func start () { + keys.removeAll() + loadFiledFromKeyData() + } + + func loadFiledFromKeyData () { + let keys = try! fileManager.contentsOfDirectory(atPath: "/var/keychain/key_data") + print(keys) + + for key in keys { + if key.fileExtension() == "json" { + let fileAttr = try! fileManager.attributesOfItem(atPath: "/var/keychain/key_data/" + key) + + let keyModel = Mapper().map(JSONString: try! String(contentsOfFile: "/var/keychain/key_data/" + key)) + let keyStruct = KeysData(fullKeyName: keyModel?.keyname ?? "", + description: keyModel?.description ?? "", + publicKey: keyModel?.keyInfo.publicKey ?? "", + location: "/var/keychain/key_data/" + key, + cipherType: keyModel?.keyInfo.privKeyData.cipherType ?? "", + creationDate: String(describing: fileAttr[FileAttributeKey.creationDate] as! Date), + keychainVersion: keyModel?.keychainVersion ?? "", + curveType: keyModel?.keyInfo.curveType ?? "") + self.keys.append(keyStruct) + } + print(self.keys) + + } + } + +} diff --git a/keymanager_mac/KeyManager/String+extension.swift b/keymanager_mac/KeyManager/String+extension.swift new file mode 100644 index 0000000..7f59b08 --- /dev/null +++ b/keymanager_mac/KeyManager/String+extension.swift @@ -0,0 +1,19 @@ +// +// String+extension.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 26/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Foundation + +extension String { + func fileName() -> String { + return NSURL(fileURLWithPath: self).deletingPathExtension?.lastPathComponent ?? "" + } + + func fileExtension() -> String { + return NSURL(fileURLWithPath: self).pathExtension ?? "" + } +} diff --git a/keymanager_mac/KeyManager/TableRowView.swift b/keymanager_mac/KeyManager/TableRowView.swift new file mode 100644 index 0000000..9aff8e3 --- /dev/null +++ b/keymanager_mac/KeyManager/TableRowView.swift @@ -0,0 +1,29 @@ +// +// TableRowView.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 23/01/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +import Cocoa + +class TableRowView: NSTableRowView { + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + + // Drawing code here. + } + + override func drawSelection(in dirtyRect: NSRect) { + if self.selectionHighlightStyle != .none { + let selectionRect = NSInsetRect(self.bounds, 0, 0) + NSColor(red: 166.0/255.0, green: 178.0/255.0, blue: 200.0/255.0, alpha: 1).setFill() + let selectionPath = NSBezierPath.init(roundedRect: selectionRect, xRadius: 0, yRadius: 0) + selectionPath.fill() +// selectionPath.stroke() + } + } + +} diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift new file mode 100644 index 0000000..9f7bd70 --- /dev/null +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -0,0 +1,119 @@ +// +// ViewController.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 24/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Cocoa + +class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { + + @IBOutlet weak var tableView: NSTableView! + @IBOutlet weak var websocketStatusLabel: NSTextField! + @IBOutlet weak var creationDate: NSTextFieldCell! + @IBOutlet weak var keychainVersion: NSTextFieldCell! + @IBOutlet weak var cipherType: NSTextFieldCell! + @IBOutlet weak var location: NSTextFieldCell! + @IBOutlet weak var descriptionKey: NSTextFieldCell! + @IBOutlet weak var publicKey: NSTextFieldCell! + @IBOutlet weak var detailsView: NSView! +// @IBOutlet weak var titleView: NSView! + + fileprivate enum CellIdentifiers { + static let LocationCell = "locationId" + static let KeyFormatCell = "keyFormatId" + static let EncryptionCell = "encryptionId" + } + + override func viewDidLoad() { + super.viewDidLoad() + self.tableView.delegate = self + self.tableView.dataSource = self + KeyManager.shared.start() + tableView.reloadData() + self.view.layer?.backgroundColor = NSColor(red: 242.0/255.0, green: 243.0/255.0, blue: 247.0/255.0, alpha: 1).cgColor + self.detailsView.wantsLayer = true + self.detailsView.layer?.backgroundColor = NSColor(red: 213.0/255.0, green: 220.0/255.0, blue: 230.0/255.0, alpha: 1).cgColor + +// titleView.wantsLayer = true +// titleView.layer?.backgroundColor = NSColor.white.cgColor + + websocketStatus() + Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(websocketStatus), userInfo: nil, repeats: true) + // Do any additional setup after loading the view. + } + + func updateTableView () { + + } + + override var representedObject: Any? { + didSet { + // Update the view, if already loaded. + } + } + + + func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { + + var text: String = "" + var cellIdentifier: String = "" + + let item = KeyManager.shared.keys[row] + + if tableColumn == tableView.tableColumns[0] { + text = item.fullKeyName + cellIdentifier = CellIdentifiers.LocationCell + } else if tableColumn == tableView.tableColumns[1] { + text = item.description + cellIdentifier = CellIdentifiers.KeyFormatCell + } else if tableColumn == tableView.tableColumns[2] { + text = item.creationDate + cellIdentifier = CellIdentifiers.EncryptionCell + } + + // 3 + if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { + cell.textField?.stringValue = text + return cell + } + return nil + + } + + func numberOfRows(in tableView: NSTableView) -> Int { + return KeyManager.shared.keys.count + } + + @objc func websocketStatus() { + WebsocketChecker.checkForRunningWebsocketd { (isRunning) in + self.websocketStatusLabel.stringValue = isRunning ? "Running" : "Not started" + } + } + + func tableView(_ tableView: NSTableView, didClick tableColumn: NSTableColumn) { + print("click") + } + + func tableView(_ tableView: NSTableView, rowViewForRow row: Int) -> NSTableRowView? { + return TableRowView() + } + + func tableViewSelectionDidChange(_ notification: Notification) { + print("select") + let obj = notification.object as! NSTableView + let item = KeyManager.shared.keys[obj.selectedRow] + detailsView.isHidden = false + creationDate.stringValue = item.creationDate + keychainVersion.stringValue = item.keychainVersion + cipherType.stringValue = item.cipherType + location.stringValue = item.location + descriptionKey.stringValue = item.description + publicKey.stringValue = item.publicKey + print(obj.selectedRow) + } + +} + diff --git a/keymanager_mac/KeyManager/WebsocketChecker.swift b/keymanager_mac/KeyManager/WebsocketChecker.swift new file mode 100644 index 0000000..c6d61ec --- /dev/null +++ b/keymanager_mac/KeyManager/WebsocketChecker.swift @@ -0,0 +1,26 @@ +// +// WebsocketChecker.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 26/12/2018. +// Copyright © 2018 Mikhail Lutskii. All rights reserved. +// + +import Foundation + +class WebsocketChecker { + + static func checkForRunningWebsocketd (success: @escaping(_ isRunning: Bool) -> Void) { + AppleScriptManager.runScriptWithBodyWithReturnString("ps -ax -o command | grep websocket | grep -v grep", success: { (result) in + if result != "" { + success(true) + } else { + success(false) + } + }) { (error) in + print(error) + success(false) + } + } + +} diff --git a/keymanager_mac/Podfile b/keymanager_mac/Podfile new file mode 100644 index 0000000..e14e852 --- /dev/null +++ b/keymanager_mac/Podfile @@ -0,0 +1,10 @@ +# Uncomment the next line to define a global platform for your project +# platform :ios, '9.0' + +target 'KeyManager' do + # Comment the next line if you're not using Swift and don't want to use dynamic frameworks + use_frameworks! + pod 'ObjectMapper', '~> 3.4' + # Pods for KeyManager + +end diff --git a/keymanager_mac/Podfile.lock b/keymanager_mac/Podfile.lock new file mode 100644 index 0000000..ad8ad8d --- /dev/null +++ b/keymanager_mac/Podfile.lock @@ -0,0 +1,16 @@ +PODS: + - ObjectMapper (3.4.2) + +DEPENDENCIES: + - ObjectMapper (~> 3.4) + +SPEC REPOS: + https://github.com/cocoapods/specs.git: + - ObjectMapper + +SPEC CHECKSUMS: + ObjectMapper: 0d4402610f4e468903ae64629eec4784531e5c51 + +PODFILE CHECKSUM: f564e6d329f5dff2e2d35bb85178bc0301867829 + +COCOAPODS: 1.5.3 From bbc3a8a11c77173aab35a5b8df3f14379b4f40b8 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Wed, 13 Feb 2019 13:10:26 +0300 Subject: [PATCH 02/65] merge --- .../macOS/KeyChain Installer.xcodeproj/project.pbxproj | 8 ++++---- .../macOS/KeyChain Installer/Base.lproj/Main.storyboard | 4 ++-- keychain_common-Bridging-Header.h | 4 ++++ keychain_mac/SelectKeyVC.mm | 2 +- 4 files changed, 11 insertions(+), 7 deletions(-) create mode 100644 keychain_common-Bridging-Header.h diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index fa1b5db..6e2b747 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -11,7 +11,6 @@ A776F48D21D0C696006736C9 /* Print.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75B21A6B4A60021ED5E /* Print.swift */; }; A776F48F21D0C92E006736C9 /* UninstallVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F48E21D0C92E006736C9 /* UninstallVC.swift */; }; A776F49021D0D147006736C9 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75721A6B4620021ED5E /* Alerts.swift */; }; - A78BBE432209D4E7007A5BB4 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A78BBE422209D4E7007A5BB4 /* bin.tar.gz */; }; A793A32921C2672B0061249D /* LicenseVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A793A32821C2672B0061249D /* LicenseVC.swift */; }; A799115F21C41AD500CB13B7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A799115E21C41AD500CB13B7 /* AppDelegate.swift */; }; A799116321C41AD500CB13B7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A799116221C41AD500CB13B7 /* Assets.xcassets */; }; @@ -19,6 +18,7 @@ A7A912B621CCE12D00A7594E /* NotificationExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75F21A6B6C70021ED5E /* NotificationExtensions.swift */; }; A7A912B721CCF43A00A7594E /* Consts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75921A6B4860021ED5E /* Consts.swift */; }; A7A912B821CCF8BD00A7594E /* AppleScriptManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75521A6B4520021ED5E /* AppleScriptManager.swift */; }; + A7C2B31E221300EB00A89CFE /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A7C2B31D221300EB00A89CFE /* bin.tar.gz */; }; A7DF22B621CA7BA3008F2364 /* UnistallerManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */; }; A7DF22B721CA7BA3008F2364 /* UnistallerManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */; }; A7E7F73E21A6B0CE0021ED5E /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F73D21A6B0CE0021ED5E /* AppDelegate.swift */; }; @@ -44,7 +44,6 @@ A0679F4132141184C33311C6 /* Pods-Keychain Installer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Installer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Installer/Pods-Keychain Installer.debug.xcconfig"; sourceTree = ""; }; A1FECE3906833024E5D5394D /* Pods_Keychain_Uninstaller.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Keychain_Uninstaller.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A776F48E21D0C92E006736C9 /* UninstallVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallVC.swift; sourceTree = ""; }; - A78BBE422209D4E7007A5BB4 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A793A32821C2672B0061249D /* LicenseVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseVC.swift; sourceTree = ""; }; A799115C21C41AD500CB13B7 /* Keychain Uninstaller.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Keychain Uninstaller.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A799115E21C41AD500CB13B7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -52,6 +51,7 @@ A799116521C41AD500CB13B7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; A799116721C41AD500CB13B7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A799116821C41AD500CB13B7 /* Keychain_Uninstaller.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Keychain_Uninstaller.entitlements; sourceTree = ""; }; + A7C2B31D221300EB00A89CFE /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = UnistallerManager.swift; path = Common/UnistallerManager.swift; sourceTree = SOURCE_ROOT; }; A7E7F73A21A6B0CD0021ED5E /* KeyChain Installer.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "KeyChain Installer.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A7E7F73D21A6B0CE0021ED5E /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -168,7 +168,7 @@ A7E7F74321A6B0D10021ED5E /* Main.storyboard */, A7E7F74621A6B0D10021ED5E /* Info.plist */, A7E7F74721A6B0D10021ED5E /* Keychain_Installer.entitlements */, - A78BBE422209D4E7007A5BB4 /* bin.tar.gz */, + A7C2B31D221300EB00A89CFE /* bin.tar.gz */, ); path = "KeyChain Installer"; sourceTree = ""; @@ -265,7 +265,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - A78BBE432209D4E7007A5BB4 /* bin.tar.gz in Resources */, + A7C2B31E221300EB00A89CFE /* bin.tar.gz in Resources */, A7E7F74221A6B0D10021ED5E /* Assets.xcassets in Resources */, A7E7F74521A6B0D10021ED5E /* Main.storyboard in Resources */, ); diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index 1563b49..66690ea 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -685,7 +685,7 @@ - + @@ -987,7 +987,7 @@ - + diff --git a/keychain_common-Bridging-Header.h b/keychain_common-Bridging-Header.h new file mode 100644 index 0000000..1b2cb5d --- /dev/null +++ b/keychain_common-Bridging-Header.h @@ -0,0 +1,4 @@ +// +// Use this file to import your target's public headers that you would like to expose to Swift. +// + diff --git a/keychain_mac/SelectKeyVC.mm b/keychain_mac/SelectKeyVC.mm index 98ef18e..751a5e4 100644 --- a/keychain_mac/SelectKeyVC.mm +++ b/keychain_mac/SelectKeyVC.mm @@ -61,7 +61,7 @@ - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { //we have only one table in the screen and thus we are not checking the row count based on the target table view // long recordCount = [self.dataArray count]; - return keyfile_singleton::instance(); + return 0; } - (void)runModal { From 7b957284dc22e0abe56a4dd8da5a86a8056ebb05 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Wed, 13 Feb 2019 17:23:09 +0300 Subject: [PATCH 03/65] merge --- .../Base.lproj/Main.storyboard | 2 +- keychain_mac/DialogWC.h | 1 + keychain_mac/DialogWC.mm | 11 +- keychain_mac/PassSyncStore.h | 8 ++ keychain_mac/SelectKeyVC.mm | 124 ++++++++++++++++-- keychain_mac/TableView.h | 16 +++ keychain_mac/TableView.m | 29 ++++ keychain_mac/gui_mod_mac.mm | 15 +-- keychain_mac/sec_mod_mac.mm | 28 +++- 9 files changed, 202 insertions(+), 32 deletions(-) create mode 100644 keychain_mac/TableView.h create mode 100644 keychain_mac/TableView.m diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index 66690ea..6b5d60d 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -987,7 +987,7 @@ - + diff --git a/keychain_mac/DialogWC.h b/keychain_mac/DialogWC.h index bf3b976..6f0e15d 100644 --- a/keychain_mac/DialogWC.h +++ b/keychain_mac/DialogWC.h @@ -18,6 +18,7 @@ NS_ASSUME_NONNULL_BEGIN @property (readwrite) BOOL isSignTransaction; @property (readwrite) BOOL isJson; @property (readwrite) BOOL isRawhash; +@property (readwrite) BOOL isPasswordRequire; @property (readwrite) keychain_app::secmod_commands::events_te etype; @property keychain_app::secmod_commands::secmod_parser_f parser; @property (readwrite) int unlockTime; diff --git a/keychain_mac/DialogWC.mm b/keychain_mac/DialogWC.mm index a97eb15..de3c776 100644 --- a/keychain_mac/DialogWC.mm +++ b/keychain_mac/DialogWC.mm @@ -54,6 +54,7 @@ - (instancetype)initWithFrame:(NSRect)frame { } - (void) clickCloseButton { + [[PassSyncStore sharedInstance] setButtonClickType: ButtonClickTypeCancel]; [self.window close]; } @@ -68,7 +69,9 @@ - (void) clickButton { NSLog(@"Success"); }]; } else { - [[PassSyncStore sharedInstance] setPass:pass.stringValue]; + [[PassSyncStore sharedInstance] setButtonClickType: ButtonClickTypeOK]; + if (self.isPasswordRequire) + [[PassSyncStore sharedInstance] setPass:pass.stringValue]; [self.window close]; } } @@ -87,8 +90,10 @@ - (void)runModal { NSLog(@"jsonString %@", _jsonString); // NSLog(@"currentPath %@", _currentPath); [self setupLogoiew]; - [self setupLabelPassphrase]; - [self setupPassField]; + if (self.isPasswordRequire) { + [self setupLabelPassphrase]; + [self setupPassField]; + } [self setupSignButton]; [self setupCancelButton]; if (!self.unlockOnly) { diff --git a/keychain_mac/PassSyncStore.h b/keychain_mac/PassSyncStore.h index a31bdba..3d581b8 100644 --- a/keychain_mac/PassSyncStore.h +++ b/keychain_mac/PassSyncStore.h @@ -6,12 +6,20 @@ // #import +#import NS_ASSUME_NONNULL_BEGIN +typedef enum { + ButtonClickTypeOK, + ButtonClickTypeCancel +} ButtonClickType; + @interface PassSyncStore : NSObject @property (atomic, strong) NSString *pass; +@property dev::Public public_key; +@property ButtonClickType buttonClickType; + (instancetype)sharedInstance; diff --git a/keychain_mac/SelectKeyVC.mm b/keychain_mac/SelectKeyVC.mm index 751a5e4..a79ce63 100644 --- a/keychain_mac/SelectKeyVC.mm +++ b/keychain_mac/SelectKeyVC.mm @@ -7,6 +7,13 @@ #import "SelectKeyVC.h" #import "MiddleAlignedTextFieldCell.h" +#import "FileManager.h" +#import "HexToRgbColor.h" +#import "SYFlatButton.h" +#import "PassSyncStore.h" +#import "TableView.h" + +using namespace keychain_app; @interface SelectKeyVC () @@ -40,6 +47,10 @@ - (void)windowDidLoad { // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. } + +- (void)dealloc { + [NSNotificationCenter.defaultCenter removeObserver:self]; +} - (void)windowWillClose:(NSNotification *)notification { [NSApp setActivationPolicy:NSApplicationActivationPolicyProhibited]; @@ -50,18 +61,33 @@ - (void)windowWillClose:(NSNotification *)notification { - (id)tableView:(NSTableView *)aTableView objectValueForTableColumn:(NSTableColumn *)aTableColumn row:(NSInteger)rowIndex { - // NSString *aString = [NSString stringWithFormat:@"%@, Row %ld",[aTableColumn identifier],(long)rowIndex]; + auto& keyfiles = keyfile_singleton::instance(); + auto& index = keyfiles.random_access_index(); + auto it = index.begin() + rowIndex; + auto key = *(it); NSString *aString; -// aString = [[dataForBitcoin objectAtIndex:rowIndex] objectForKey:[aTableColumn identifier]]; + + if ([[aTableColumn identifier] isEqualToString:@"key1"]) { + aString = [NSString stringWithUTF8String:key.keyname.c_str()]; + } else if ([[aTableColumn identifier] isEqualToString:@"key2"]) { + aString = [NSString stringWithUTF8String:key.public_key().hex().c_str()]; + } else if ([[aTableColumn identifier] isEqualToString:@"key3"]) { + auto seconds = key.creation_time.time_since_epoch().to_seconds(); + NSDate *createTime = [NSDate dateWithTimeIntervalSince1970:seconds]; + NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; + [formatter setDateFormat:@"MMM dd, YYYY, HH:mm:ss"]; + NSString *stringFromDate = [formatter stringFromDate:createTime]; + aString = stringFromDate; + } return aString; } // TableView Datasource method implementation - (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView { - //we have only one table in the screen and thus we are not checking the row count based on the target table view - // long recordCount = [self.dataArray count]; - return 0; + auto& keyfiles = keyfile_singleton::instance(); + auto distance = std::distance(keyfiles.begin(), keyfiles.end()); + return distance; } - (void)runModal { @@ -71,19 +97,21 @@ - (void)runModal { cover.state = NSVisualEffectStateFollowsWindowActiveState; [cover setAppearance:[NSAppearance appearanceNamed:NSAppearanceNameVibrantLight]]; [self.window.contentView addSubview:cover]; - - + [self setupLogoView]; + [self createTableView]; + [self setupCancelButton]; + [self setupOkButton]; [[NSApplication sharedApplication] runModalForWindow:self.window]; [self.window setFrame:NSMakeRect(0, 0, 575, 500) display:true]; } - (void) createTableView { - NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(22, 110, self.window.frame.size.width - 44, 150)]; + NSScrollView *scrollView = [[NSScrollView alloc] initWithFrame:CGRectMake(22, 80, self.window.frame.size.width - 44, 350)]; scrollView.backgroundColor = [NSColor clearColor]; [scrollView setBorderType:NSBezelBorder]; - NSTableView *tableView = [[NSTableView alloc] initWithFrame:scrollView.bounds]; + TableView *tableView = [[TableView alloc] initWithFrame:scrollView.bounds]; tableView.rowSizeStyle = NSTableViewRowSizeStyleLarge; tableView.backgroundColor = [NSColor clearColor]; tableView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; @@ -93,16 +121,24 @@ - (void) createTableView { tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key1"]]; id cell = [tCol dataCell]; [cell setFont: [NSFont systemFontOfSize:18]]; - [[tCol headerCell] setStringValue:@"To"]; - [tCol setWidth:self.window.frame.size.width - 149]; + [[tCol headerCell] setStringValue:@"Keyname"]; + [tCol setWidth:100]; tCol.editable = false; [[tCol dataCell] setVerticalCentering:YES]; [tableView addTableColumn:tCol]; - + tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key2"]]; cell = [tCol dataCell]; [cell setFont: [NSFont systemFontOfSize:18]]; - [[tCol headerCell] setStringValue:@"Amount"]; + [[tCol headerCell] setStringValue:@"Public key"]; + tCol.editable = false; + [[tCol dataCell] setVerticalCentering:YES]; + [tableView addTableColumn:tCol]; + + tCol = [[NSTableColumn alloc] initWithIdentifier:[NSString stringWithFormat:@"key3"]]; + cell = [tCol dataCell]; + [cell setFont: [NSFont systemFontOfSize:18]]; + [[tCol headerCell] setStringValue:@"Date"]; [tCol setWidth:100]; tCol.editable = false; [[tCol dataCell] setVerticalCentering:YES]; @@ -113,7 +149,8 @@ - (void) createTableView { [tableView setRowHeight:23.0]; [tableView setDelegate:self]; [tableView setDataSource:self]; - [tableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone]; + tableView.selectionHighlightStyle = NSTableViewSelectionHighlightStyleRegular; +// [tableView setSelectionHighlightStyle:NSTableViewSelectionHighlightStyleNone]; [tableView setAutoresizesSubviews:YES]; scrollView.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; @@ -128,4 +165,63 @@ - (void) createTableView { [self.window.contentView addSubview:scrollView]; } +- (void) setupLogoView { + NSImageView *imageView = [[NSImageView alloc] initWithFrame:NSMakeRect(22, self.window.frame.size.height - 81, 64, 54)]; + NSImage *image = [[NSImage alloc] initWithContentsOfFile:[NSString stringWithFormat:@"%@/%@", FileManager.getWorkDirectoryPath, @"resources/logo.png"]]; + imageView.image = image; + [self.window.contentView addSubview:imageView]; + + NSTextField *label = [NSTextField labelWithString:@"KeyChain"]; + label.appearance = [NSAppearance appearanceNamed:NSAppearanceNameAqua]; + label.textColor = [HexToRgbColor colorWithHexColorString:@"4f4e4e"]; + label.font = [NSFont systemFontOfSize:18]; + label.frame = NSMakeRect(90, self.window.frame.size.height - 96, 100, 54); + + [self.window.contentView addSubview:label]; +} + +- (void) setupCancelButton { + SYFlatButton *button = [[SYFlatButton alloc] initWithFrame:NSMakeRect(self.window.frame.size.width - 245, 20, 100, 35)]; + button.target = self; + button.action = @selector(clickCloseButton); + button.title = @"CANCEL"; + button.backgroundNormalColor = [NSColor whiteColor]; + button.titleNormalColor = [HexToRgbColor colorWithHexColorString:@"939497"]; + button.cornerRadius = 4; + button.momentary = YES; + [self.window.contentView addSubview:button]; +} + +- (void) setupOkButton { + SYFlatButton *button = [[SYFlatButton alloc] initWithFrame:NSMakeRect(self.window.frame.size.width - 125, 20, 100, 35)]; + button.target = self; + button.action = @selector(clickButton); + button.title = @"OK"; + button.titleNormalColor = [NSColor whiteColor]; + button.momentary = YES; + button.cornerRadius = 4.0; + button.backgroundNormalColor = [HexToRgbColor colorWithHexColorString:@"4686FF"]; + [self.window.contentView addSubview:button]; +} + +- (void) clickCloseButton { + [[PassSyncStore sharedInstance] setButtonClickType:ButtonClickTypeCancel]; + [self.window close]; +} + +- (void) clickButton { + [[PassSyncStore sharedInstance] setButtonClickType:ButtonClickTypeOK]; + [self.window close]; +} + +- (void)tableViewSelectionDidChange:(NSNotification *)notification { + NSLog(@"selected %@", [notification object]); + + auto& keyfiles = keyfile_singleton::instance(); + auto& index = keyfiles.random_access_index(); + auto it = index.begin() + [[notification object] selectedRow]; + auto key = *(it); + [[PassSyncStore sharedInstance] setPublic_key:key.public_key()]; +} + @end diff --git a/keychain_mac/TableView.h b/keychain_mac/TableView.h new file mode 100644 index 0000000..931b5b6 --- /dev/null +++ b/keychain_mac/TableView.h @@ -0,0 +1,16 @@ +// +// TableView.h +// keychain +// +// Created by Mikhail Lutskiy on 13/02/2019. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface TableView : NSTableView + +@end + +NS_ASSUME_NONNULL_END diff --git a/keychain_mac/TableView.m b/keychain_mac/TableView.m new file mode 100644 index 0000000..fd2fd06 --- /dev/null +++ b/keychain_mac/TableView.m @@ -0,0 +1,29 @@ +// +// TableView.m +// keychain +// +// Created by Mikhail Lutskiy on 13/02/2019. +// + +#import "TableView.h" + +@implementation TableView + +- (void)drawRect:(NSRect)dirtyRect { + [super drawRect:dirtyRect]; + + // Drawing code here. +} + +- (void)mouseDown:(NSEvent *)theEvent { + + NSPoint globalLocation = [theEvent locationInWindow]; + NSPoint localLocation = [self convertPoint:globalLocation fromView:nil]; + NSInteger clickedRow = [self rowAtPoint:localLocation]; + + if(clickedRow != -1) { + [super mouseDown:theEvent]; + } +} + +@end diff --git a/keychain_mac/gui_mod_mac.mm b/keychain_mac/gui_mod_mac.mm index 0828245..7a51394 100644 --- a/keychain_mac/gui_mod_mac.mm +++ b/keychain_mac/gui_mod_mac.mm @@ -9,6 +9,7 @@ #import "SelectKeyVC.h" #import #import "ApplicationShared.h" +#import "PassSyncStore.h" using namespace keychain_app; @@ -21,15 +22,11 @@ dev::Public gui_mod_mac::select_key() const { [ApplicationShared sharedInstance]; - NSRect frame = NSMakeRect(0, 0, 500, 521); - - auto& keyfiles = keyfile_singleton::instance(); - auto it = keyfiles.begin(); - if ( it==keyfiles.end() ) - return dev::Public(); - - SelectKeyVC *dialog = [[SelectKeyVC alloc] initWithFrame:frame]; + SelectKeyVC *dialog = [[SelectKeyVC alloc] initWithFrame:NSMakeRect(0, 0, 700, 540)]; [dialog runModal]; + if ([[PassSyncStore sharedInstance] buttonClickType] == ButtonClickTypeOK) { + return [[PassSyncStore sharedInstance] public_key]; + } - return it->keyinfo.public_key; + return dev::Public(); } diff --git a/keychain_mac/sec_mod_mac.mm b/keychain_mac/sec_mod_mac.mm index 7dda50a..0c8937f 100644 --- a/keychain_mac/sec_mod_mac.mm +++ b/keychain_mac/sec_mod_mac.mm @@ -37,6 +37,7 @@ auto etype = parser(json_cmd); int unlock_time = 0; bool is_json = true; + bool no_password = false; std::string blockhain_type; switch (etype) { @@ -71,6 +72,8 @@ } } + no_password = cmd.no_password; + DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; dialog.jsonString = [NSString stringWithUTF8String:json_cmd.c_str()]; dialog.isJson = is_json; @@ -81,6 +84,7 @@ dialog.etype = etype; dialog.keyname = [NSString stringWithUTF8String:cmd.keyname.c_str()]; dialog.parser = parser; + dialog.isPasswordRequire = !cmd.no_password; dialog.expertModeString = [NSString stringWithUTF8String:keychain_app::secmod_commands::to_expert_mode_string(cmd).c_str()]; dialog.blockhainType = [NSString stringWithUTF8String:blockhain_type.c_str()]; [dialog runModal]; @@ -88,6 +92,7 @@ } case secmod_commands::events_te::sign_hash: { auto cmd = parser.params(); + no_password = cmd.no_password; frame = NSMakeRect(0, 0, 1024, 285); blockhain_type = "hash"; DialogWC *dialog = [[DialogWC alloc] initWithFrame:frame]; @@ -102,6 +107,7 @@ dialog.parser = parser; dialog.expertModeString = [NSString stringWithUTF8String:cmd.hash.c_str()]; dialog.blockhainType = [NSString stringWithUTF8String:blockhain_type.c_str()]; + dialog.isPasswordRequire = !cmd.no_password; [dialog runModal]; break; } @@ -109,6 +115,7 @@ { NSLog(@"unlock"); auto cmd = parser.params(); + no_password = cmd.no_password; unlock_time = cmd.unlock_time; frame = NSMakeRect(0, 0, 575, 210); @@ -119,6 +126,7 @@ dialog.unlockOnly = true; dialog.isRawhash = false; dialog.parser = parser; + dialog.isPasswordRequire = !cmd.no_password; dialog.etype = etype; [dialog runModal]; break; @@ -128,13 +136,23 @@ FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Secmod command is not implemented, etype = %{ETYPE}", ("ETYPE", etype)); } } + + secmod_commands::secmod_response_common response; + if ([[PassSyncStore sharedInstance] buttonClickType] == ButtonClickTypeCancel) { + response.etype = secmod_commands::response_te::canceled; + } else if ([[PassSyncStore sharedInstance] buttonClickType] == ButtonClickTypeOK) { + if (no_password) { + response.etype = secmod_commands::response_te::boolean; + response.params = true; + } else { + std::string str = std::string([[[PassSyncStore sharedInstance] pass] UTF8String]); + keychain_app::byte_seq_t pass(str.begin(), str.end()); + response.etype = secmod_commands::response_te::password; + response.params = pass; + } + } - std::string str = std::string([[[PassSyncStore sharedInstance] pass] UTF8String]); - keychain_app::byte_seq_t pass(str.begin(), str.end()); [[PassSyncStore sharedInstance] setPass:@""]; - secmod_commands::secmod_resonse_common response; - response.etype = secmod_commands::response_te::password; - response.params = pass; return fc_light::json::to_pretty_string(fc_light::variant(response)); } From 5a6bb9d529bf22ee57688a018f11b5edcbc94d16 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Wed, 13 Feb 2019 17:58:04 +0300 Subject: [PATCH 04/65] keychain no_password --- .../macOS/KeyChain Installer.xcodeproj/project.pbxproj | 8 ++++---- .../macOS/KeyChain Installer/Base.lproj/Main.storyboard | 4 ++-- installer/macOS/KeyChain Installer/ProgressVC.swift | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index 6e2b747..bf20667 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -11,6 +11,7 @@ A776F48D21D0C696006736C9 /* Print.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75B21A6B4A60021ED5E /* Print.swift */; }; A776F48F21D0C92E006736C9 /* UninstallVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F48E21D0C92E006736C9 /* UninstallVC.swift */; }; A776F49021D0D147006736C9 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75721A6B4620021ED5E /* Alerts.swift */; }; + A7910FF722146745001C6761 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A7910FF622146745001C6761 /* bin.tar.gz */; }; A793A32921C2672B0061249D /* LicenseVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A793A32821C2672B0061249D /* LicenseVC.swift */; }; A799115F21C41AD500CB13B7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A799115E21C41AD500CB13B7 /* AppDelegate.swift */; }; A799116321C41AD500CB13B7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A799116221C41AD500CB13B7 /* Assets.xcassets */; }; @@ -18,7 +19,6 @@ A7A912B621CCE12D00A7594E /* NotificationExtensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75F21A6B6C70021ED5E /* NotificationExtensions.swift */; }; A7A912B721CCF43A00A7594E /* Consts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75921A6B4860021ED5E /* Consts.swift */; }; A7A912B821CCF8BD00A7594E /* AppleScriptManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75521A6B4520021ED5E /* AppleScriptManager.swift */; }; - A7C2B31E221300EB00A89CFE /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A7C2B31D221300EB00A89CFE /* bin.tar.gz */; }; A7DF22B621CA7BA3008F2364 /* UnistallerManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */; }; A7DF22B721CA7BA3008F2364 /* UnistallerManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */; }; A7E7F73E21A6B0CE0021ED5E /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F73D21A6B0CE0021ED5E /* AppDelegate.swift */; }; @@ -44,6 +44,7 @@ A0679F4132141184C33311C6 /* Pods-Keychain Installer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Installer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Installer/Pods-Keychain Installer.debug.xcconfig"; sourceTree = ""; }; A1FECE3906833024E5D5394D /* Pods_Keychain_Uninstaller.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Keychain_Uninstaller.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A776F48E21D0C92E006736C9 /* UninstallVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallVC.swift; sourceTree = ""; }; + A7910FF622146745001C6761 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A793A32821C2672B0061249D /* LicenseVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseVC.swift; sourceTree = ""; }; A799115C21C41AD500CB13B7 /* Keychain Uninstaller.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Keychain Uninstaller.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A799115E21C41AD500CB13B7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -51,7 +52,6 @@ A799116521C41AD500CB13B7 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; A799116721C41AD500CB13B7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A799116821C41AD500CB13B7 /* Keychain_Uninstaller.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = Keychain_Uninstaller.entitlements; sourceTree = ""; }; - A7C2B31D221300EB00A89CFE /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A7DF22B521CA7BA3008F2364 /* UnistallerManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; name = UnistallerManager.swift; path = Common/UnistallerManager.swift; sourceTree = SOURCE_ROOT; }; A7E7F73A21A6B0CD0021ED5E /* KeyChain Installer.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "KeyChain Installer.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A7E7F73D21A6B0CE0021ED5E /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; @@ -168,7 +168,7 @@ A7E7F74321A6B0D10021ED5E /* Main.storyboard */, A7E7F74621A6B0D10021ED5E /* Info.plist */, A7E7F74721A6B0D10021ED5E /* Keychain_Installer.entitlements */, - A7C2B31D221300EB00A89CFE /* bin.tar.gz */, + A7910FF622146745001C6761 /* bin.tar.gz */, ); path = "KeyChain Installer"; sourceTree = ""; @@ -265,7 +265,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - A7C2B31E221300EB00A89CFE /* bin.tar.gz in Resources */, + A7910FF722146745001C6761 /* bin.tar.gz in Resources */, A7E7F74221A6B0D10021ED5E /* Assets.xcassets in Resources */, A7E7F74521A6B0D10021ED5E /* Main.storyboard in Resources */, ); diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index 6b5d60d..f7a525b 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -685,7 +685,7 @@ - + @@ -987,7 +987,7 @@ - + diff --git a/installer/macOS/KeyChain Installer/ProgressVC.swift b/installer/macOS/KeyChain Installer/ProgressVC.swift index be338c3..f54c7d7 100644 --- a/installer/macOS/KeyChain Installer/ProgressVC.swift +++ b/installer/macOS/KeyChain Installer/ProgressVC.swift @@ -84,7 +84,7 @@ class ProgressVC: NSViewController { print("OK untar") print(dataPath) self.jobWorker(dataPath: dataPath) - AppleScriptManager.runScriptWithBody("cp -a '" + dataPath + "/keys/.' /var/keychain/key_data", isAdminRequired: true, success: { + AppleScriptManager.runScriptWithBody("cp -a '" + dataPath + "/keys/.' /var/keychain/key_data && mkdir /var/keychain/signlogs_data", isAdminRequired: true, success: { self.infoTextField.stringValue = "Installation complete!" self.installText("Installation complete!") }, failure: { (error) in From 96a1776957ef459530bd4e44bfebab05db563841 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Thu, 14 Feb 2019 16:22:49 +0300 Subject: [PATCH 05/65] keymanager --- .../KeyManager.xcodeproj/project.pbxproj | 143 ++++++++++- .../KeyManager/Base.lproj/Main.storyboard | 237 +++++++++++------- keymanager_mac/KeyManager/CPlusPlusBridger.h | 19 ++ keymanager_mac/KeyManager/CPlusPlusBridger.mm | 22 ++ .../{HexToRgbColor.m => HexToRgbColor.mm} | 0 keymanager_mac/KeyManager/KeyFileModel.swift | 4 + .../KeyManager/KeyManager-Bridging-Header.h | 2 + keymanager_mac/KeyManager/KeyManager.swift | 2 +- .../KeyManager/ViewController.swift | 11 +- 9 files changed, 337 insertions(+), 103 deletions(-) create mode 100644 keymanager_mac/KeyManager/CPlusPlusBridger.h create mode 100644 keymanager_mac/KeyManager/CPlusPlusBridger.mm rename keymanager_mac/KeyManager/{HexToRgbColor.m => HexToRgbColor.mm} (100%) diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj index 48d1404..8a1ccce 100644 --- a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -16,7 +16,13 @@ A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B721D39AB7006736C9 /* String+extension.swift */; }; A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */; }; A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */; }; - A79F78BA21F89D0400E2C184 /* HexToRgbColor.m in Sources */ = {isa = PBXBuildFile; fileRef = A79F78B921F89D0400E2C184 /* HexToRgbColor.m */; }; + A7910FF922146DC7001C6761 /* libkeychain_common.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A7910FF822146DC7001C6761 /* libkeychain_common.a */; }; + A7910FFB22146DDE001C6761 /* libfc_light.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A7910FFA22146DDE001C6761 /* libfc_light.a */; }; + A7910FFD22146DE8001C6761 /* libeth-crypto.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A7910FFC22146DE8001C6761 /* libeth-crypto.a */; }; + A7910FFF22146DF7001C6761 /* libethash.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A7910FFE22146DF7001C6761 /* libethash.a */; }; + A791100122146E04001C6761 /* libsecp256k1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A791100022146E04001C6761 /* libsecp256k1.a */; }; + A791100422147903001C6761 /* CPlusPlusBridger.mm in Sources */ = {isa = PBXBuildFile; fileRef = A791100322147903001C6761 /* CPlusPlusBridger.mm */; }; + A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */ = {isa = PBXBuildFile; fileRef = A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */; }; A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79F78BB21F8A17900E2C184 /* TableRowView.swift */; }; AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 130888C1592515A58F013398 /* Pods_KeyManager.framework */; }; /* End PBXBuildFile section */ @@ -37,9 +43,16 @@ A776F4B721D39AB7006736C9 /* String+extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+extension.swift"; sourceTree = ""; }; A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppleScriptManager.swift; sourceTree = ""; }; A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebsocketChecker.swift; sourceTree = ""; }; + A7910FF822146DC7001C6761 /* libkeychain_common.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libkeychain_common.a; sourceTree = ""; }; + A7910FFA22146DDE001C6761 /* libfc_light.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libfc_light.a; sourceTree = ""; }; + A7910FFC22146DE8001C6761 /* libeth-crypto.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = "libeth-crypto.a"; sourceTree = ""; }; + A7910FFE22146DF7001C6761 /* libethash.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libethash.a; sourceTree = ""; }; + A791100022146E04001C6761 /* libsecp256k1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libsecp256k1.a; sourceTree = ""; }; + A791100222147903001C6761 /* CPlusPlusBridger.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CPlusPlusBridger.h; sourceTree = ""; }; + A791100322147903001C6761 /* CPlusPlusBridger.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = CPlusPlusBridger.mm; sourceTree = ""; }; A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "KeyManager-Bridging-Header.h"; sourceTree = ""; }; A79F78B821F89D0400E2C184 /* HexToRgbColor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HexToRgbColor.h; sourceTree = ""; }; - A79F78B921F89D0400E2C184 /* HexToRgbColor.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = HexToRgbColor.m; sourceTree = ""; }; + A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = HexToRgbColor.mm; sourceTree = ""; }; A79F78BB21F8A17900E2C184 /* TableRowView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TableRowView.swift; sourceTree = ""; }; /* End PBXFileReference section */ @@ -48,7 +61,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( + A7910FFD22146DE8001C6761 /* libeth-crypto.a in Frameworks */, + A7910FF922146DC7001C6761 /* libkeychain_common.a in Frameworks */, + A791100122146E04001C6761 /* libsecp256k1.a in Frameworks */, AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */, + A7910FFF22146DF7001C6761 /* libethash.a in Frameworks */, + A7910FFB22146DDE001C6761 /* libfc_light.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -97,8 +115,10 @@ A776F4B121D0E66B006736C9 /* KeyManager.swift */, A776F4B721D39AB7006736C9 /* String+extension.swift */, A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */, + A791100222147903001C6761 /* CPlusPlusBridger.h */, + A791100322147903001C6761 /* CPlusPlusBridger.mm */, A79F78B821F89D0400E2C184 /* HexToRgbColor.h */, - A79F78B921F89D0400E2C184 /* HexToRgbColor.m */, + A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */, A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */, ); path = KeyManager; @@ -107,6 +127,11 @@ F73689D206923AF1FA7A3A0E /* Frameworks */ = { isa = PBXGroup; children = ( + A791100022146E04001C6761 /* libsecp256k1.a */, + A7910FFE22146DF7001C6761 /* libethash.a */, + A7910FFC22146DE8001C6761 /* libeth-crypto.a */, + A7910FF822146DC7001C6761 /* libkeychain_common.a */, + A7910FFA22146DDE001C6761 /* libfc_light.a */, 130888C1592515A58F013398 /* Pods_KeyManager.framework */, ); name = Frameworks; @@ -124,6 +149,7 @@ A776F49921D0DD95006736C9 /* Frameworks */, A776F49A21D0DD95006736C9 /* Resources */, 4E78683ECFE60E4C180EB408 /* [CP] Embed Pods Frameworks */, + A78BBE0B2209B2FC007A5BB4 /* ShellScript */, ); buildRules = ( ); @@ -217,6 +243,23 @@ shellScript = "\"${SRCROOT}/Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager-frameworks.sh\"\n"; showEnvVarsInLog = 0; }; + A78BBE0B2209B2FC007A5BB4 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "# Type a script or drag a script file from your workspace to insert its path.\n"; + }; /* End PBXShellScriptBuildPhase section */ /* Begin PBXSourcesBuildPhase section */ @@ -228,11 +271,12 @@ A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */, A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */, A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */, - A79F78BA21F89D0400E2C184 /* HexToRgbColor.m in Sources */, + A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */, A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */, A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */, A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */, A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */, + A791100422147903001C6761 /* CPlusPlusBridger.mm in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -370,17 +414,63 @@ baseConfigurationReference = 9E7F5FE43CEBFF8FE8BEDA2F /* Pods-KeyManager.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_CXX_LANGUAGE_STANDARD = "c++17"; + CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = KeyManager/KeyManager.entitlements; CODE_SIGN_IDENTITY = "Mac Developer"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEVELOPMENT_TEAM = 8YBKQD6YZD; + GCC_C_LANGUAGE_STANDARD = gnu11; + HEADER_SEARCH_PATHS = ( + ../keychain_lib/include, + "../libraries/eth-crypto/include", + ../libraries/fc_light/include, + ../libraries/secp256k1/include, + /usr/local/include, + "/Users/mikhaillutskiy/openssl-install/include", + ../libraries/secp256k1_ext/include, + ../libraries/kaitai_struct_cpp_stl_runtime, + ); INFOPLIST_FILE = KeyManager/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)", + ); + OTHER_CPLUSPLUSFLAGS = ( + "$(OTHER_CFLAGS)", + "-std=c++14", + "-v", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + "\"ObjectMapper\"", + libsecp256k1.a, + "/usr/local/lib/libboost_log-mt.a", + "/usr/local/lib/libboost_date_time-mt.a", + "/usr/local/lib/libboost_system-mt.a", + "/usr/local/lib/libboost_filesystem-mt.a", + "/usr/local/lib/libboost_program_options-mt.a", + "/usr/local/lib/libboost_serialization-mt.a", + "/usr/local/lib/libboost_chrono-mt.a", + "/usr/local/lib/libboost_unit_test_framework-mt.a", + "/usr/local/lib/libboost_locale-mt.a", + "/usr/local/lib/libboost_thread-mt.a", + "/usr/local/lib/libboost_exception-mt.a", + "/Users/mikhaillutskiy/openssl-install/lib/libcrypto.a", + "/usr/local/lib/libboost_iostreams-mt.a", + "/usr/local/lib/libboost_log_setup-mt.a", + "/usr/local/lib/libboost_regex-mt.a", + "/usr/local/lib/libboost_atomic-mt.a", + "/Users/mikhaillutskiy/openssl-install/lib/libssl.a", + /usr/lib/libc.dylib, + ); PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -395,17 +485,62 @@ baseConfigurationReference = 188A215C60F625DB886DF7B7 /* Pods-KeyManager.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_CXX_LANGUAGE_STANDARD = "c++17"; + CLANG_CXX_LIBRARY = "libc++"; CLANG_ENABLE_MODULES = YES; CODE_SIGN_ENTITLEMENTS = KeyManager/KeyManager.entitlements; CODE_SIGN_IDENTITY = "Mac Developer"; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; DEVELOPMENT_TEAM = 8YBKQD6YZD; + GCC_C_LANGUAGE_STANDARD = gnu11; + HEADER_SEARCH_PATHS = ( + ../keychain_lib/include, + "../libraries/eth-crypto/include", + ../libraries/fc_light/include, + ../libraries/secp256k1/include, + /usr/local/include, + "/Users/mikhaillutskiy/openssl-install/include", + ../libraries/secp256k1_ext/include, + ../libraries/kaitai_struct_cpp_stl_runtime, + ); INFOPLIST_FILE = KeyManager/Info.plist; LD_RUNPATH_SEARCH_PATHS = ( "$(inherited)", "@executable_path/../Frameworks", ); + LIBRARY_SEARCH_PATHS = ( + "$(inherited)", + "$(PROJECT_DIR)", + ); + OTHER_CPLUSPLUSFLAGS = ( + "$(OTHER_CFLAGS)", + "-std=c++14", + ); + OTHER_LDFLAGS = ( + "$(inherited)", + "-framework", + "\"ObjectMapper\"", + libsecp256k1.a, + "/usr/local/lib/libboost_log-mt.a", + "/usr/local/lib/libboost_date_time-mt.a", + "/usr/local/lib/libboost_system-mt.a", + "/usr/local/lib/libboost_filesystem-mt.a", + "/usr/local/lib/libboost_program_options-mt.a", + "/usr/local/lib/libboost_serialization-mt.a", + "/usr/local/lib/libboost_chrono-mt.a", + "/usr/local/lib/libboost_unit_test_framework-mt.a", + "/usr/local/lib/libboost_locale-mt.a", + "/usr/local/lib/libboost_thread-mt.a", + "/usr/local/lib/libboost_exception-mt.a", + "/Users/mikhaillutskiy/openssl-install/lib/libcrypto.a", + "/usr/local/lib/libboost_iostreams-mt.a", + "/usr/local/lib/libboost_log_setup-mt.a", + "/usr/local/lib/libboost_regex-mt.a", + "/usr/local/lib/libboost_atomic-mt.a", + "/Users/mikhaillutskiy/openssl-install/lib/libssl.a", + /usr/lib/libc.dylib, + ); PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard index 13bc889..2afa6ae 100644 --- a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -730,19 +730,19 @@ - + - + - + - + @@ -756,11 +756,11 @@ - + - + @@ -780,88 +780,15 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + - + + + + + + - - diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.h b/keymanager_mac/KeyManager/CPlusPlusBridger.h new file mode 100644 index 0000000..83eaf85 --- /dev/null +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.h @@ -0,0 +1,19 @@ +// +// CPlusPlusBridger.h +// KeyManager +// +// Created by Mikhail Lutskiy on 13/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface CPlusPlusBridger : NSObject + +- (NSInteger) getKeyfilesCount; + +@end + +NS_ASSUME_NONNULL_END diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.mm b/keymanager_mac/KeyManager/CPlusPlusBridger.mm new file mode 100644 index 0000000..1c5fd52 --- /dev/null +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.mm @@ -0,0 +1,22 @@ +// +// CPlusPlusBridger.m +// KeyManager +// +// Created by Mikhail Lutskiy on 13/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import "CPlusPlusBridger.h" +#include + +using namespace keychain_app; + +@implementation CPlusPlusBridger + +- (NSInteger) getKeyfilesCount { + auto& keyfiles = keyfile_singleton::instance(); + auto distance = std::distance(keyfiles.begin(), keyfiles.end()); + return distance; +} + +@end diff --git a/keymanager_mac/KeyManager/HexToRgbColor.m b/keymanager_mac/KeyManager/HexToRgbColor.mm similarity index 100% rename from keymanager_mac/KeyManager/HexToRgbColor.m rename to keymanager_mac/KeyManager/HexToRgbColor.mm diff --git a/keymanager_mac/KeyManager/KeyFileModel.swift b/keymanager_mac/KeyManager/KeyFileModel.swift index fe22157..6e3c249 100644 --- a/keymanager_mac/KeyManager/KeyFileModel.swift +++ b/keymanager_mac/KeyManager/KeyFileModel.swift @@ -16,6 +16,8 @@ class KeyFileModel: Mappable { var description: String! var keychainVersion: String! var keyInfo: KeyInfoModel! + var creationTime: String! + var usageTime: String! required init?(map: Map) { @@ -27,6 +29,8 @@ class KeyFileModel: Mappable { description <- map["description"] keychainVersion <- map["keychain_version"] keyInfo <- map["keyinfo"] + creationTime <- map["creation_time"] + usageTime <- map["usage_time"] } } diff --git a/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h b/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h index 6eb1e4d..d140d88 100644 --- a/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h +++ b/keymanager_mac/KeyManager/KeyManager-Bridging-Header.h @@ -3,3 +3,5 @@ // #import "HexToRgbColor.h" + +#import "CPlusPlusBridger.h" diff --git a/keymanager_mac/KeyManager/KeyManager.swift b/keymanager_mac/KeyManager/KeyManager.swift index bd445d8..ef551f8 100644 --- a/keymanager_mac/KeyManager/KeyManager.swift +++ b/keymanager_mac/KeyManager/KeyManager.swift @@ -46,7 +46,7 @@ class KeyManager { description: keyModel?.description ?? "", publicKey: keyModel?.keyInfo.publicKey ?? "", location: "/var/keychain/key_data/" + key, - cipherType: keyModel?.keyInfo.privKeyData.cipherType ?? "", + cipherType: keyModel?.keyInfo.privKeyData != nil ? keyModel?.keyInfo.privKeyData.cipherType ?? "" : "", creationDate: String(describing: fileAttr[FileAttributeKey.creationDate] as! Date), keychainVersion: keyModel?.keychainVersion ?? "", curveType: keyModel?.keyInfo.curveType ?? "") diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index 9f7bd70..1b71e3e 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -23,8 +23,6 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour fileprivate enum CellIdentifiers { static let LocationCell = "locationId" - static let KeyFormatCell = "keyFormatId" - static let EncryptionCell = "encryptionId" } override func viewDidLoad() { @@ -66,12 +64,6 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour if tableColumn == tableView.tableColumns[0] { text = item.fullKeyName cellIdentifier = CellIdentifiers.LocationCell - } else if tableColumn == tableView.tableColumns[1] { - text = item.description - cellIdentifier = CellIdentifiers.KeyFormatCell - } else if tableColumn == tableView.tableColumns[2] { - text = item.creationDate - cellIdentifier = CellIdentifiers.EncryptionCell } // 3 @@ -84,7 +76,8 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour } func numberOfRows(in tableView: NSTableView) -> Int { - return KeyManager.shared.keys.count + return CPlusPlusBridger().getKeyfilesCount() +// return KeyManager.shared.keys.count } @objc func websocketStatus() { From 88f2bdf00b07137c57ec6da057ed19ccc14b6d42 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Thu, 14 Feb 2019 18:49:11 +0300 Subject: [PATCH 06/65] keymanager create pass --- keychain_mac/DialogWC.mm | 2 +- .../KeyManager.xcodeproj/project.pbxproj | 28 ++ .../KeyManager/Base.lproj/Main.storyboard | 256 +++++++++++++++--- keymanager_mac/KeyManager/CPlusPlusBridger.h | 4 +- keymanager_mac/KeyManager/CPlusPlusBridger.mm | 23 ++ keymanager_mac/KeyManager/CreateKeyVC.swift | 65 +++++ keymanager_mac/KeyManager/Key.h | 19 ++ keymanager_mac/KeyManager/Key.m | 13 + .../KeyManager/ViewController.swift | 5 +- keymanager_mac/KeyManager/WindowController.h | 18 ++ keymanager_mac/KeyManager/WindowController.m | 28 ++ 11 files changed, 425 insertions(+), 36 deletions(-) create mode 100644 keymanager_mac/KeyManager/CreateKeyVC.swift create mode 100644 keymanager_mac/KeyManager/Key.h create mode 100644 keymanager_mac/KeyManager/Key.m create mode 100644 keymanager_mac/KeyManager/WindowController.h create mode 100644 keymanager_mac/KeyManager/WindowController.m diff --git a/keychain_mac/DialogWC.mm b/keychain_mac/DialogWC.mm index de3c776..8c53c06 100644 --- a/keychain_mac/DialogWC.mm +++ b/keychain_mac/DialogWC.mm @@ -63,7 +63,7 @@ - (void) clickButton { NSAlert *alert = [NSAlert new]; [alert setIcon:[NSImage new]]; alert.messageText = @"Error"; - alert.informativeText = @"Passphrases must match"; + alert.informativeText = @"Pa"; [alert addButtonWithTitle:@"OK"]; [alert beginSheetModalForWindow:[self.window.contentView window] completionHandler:^(NSInteger result) { NSLog(@"Success"); diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj index 8a1ccce..14eae9a 100644 --- a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -22,6 +22,11 @@ A7910FFF22146DF7001C6761 /* libethash.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A7910FFE22146DF7001C6761 /* libethash.a */; }; A791100122146E04001C6761 /* libsecp256k1.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A791100022146E04001C6761 /* libsecp256k1.a */; }; A791100422147903001C6761 /* CPlusPlusBridger.mm in Sources */ = {isa = PBXBuildFile; fileRef = A791100322147903001C6761 /* CPlusPlusBridger.mm */; }; + A79110182215A682001C6761 /* libkaitai_struct_cpp_stl_runtime.a in Frameworks */ = {isa = PBXBuildFile; fileRef = A79110172215A682001C6761 /* libkaitai_struct_cpp_stl_runtime.a */; }; + A791101B2215AB48001C6761 /* Key.m in Sources */ = {isa = PBXBuildFile; fileRef = A791101A2215AB48001C6761 /* Key.m */; }; + A79523712215B05300078EE5 /* SYFlatButton.m in Sources */ = {isa = PBXBuildFile; fileRef = A79523702215B05300078EE5 /* SYFlatButton.m */; }; + A79523772215B36600078EE5 /* WindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = A79523762215B36600078EE5 /* WindowController.m */; }; + A79523792215B55100078EE5 /* CreateKeyVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79523782215B55100078EE5 /* CreateKeyVC.swift */; }; A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */ = {isa = PBXBuildFile; fileRef = A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */; }; A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79F78BB21F8A17900E2C184 /* TableRowView.swift */; }; AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 130888C1592515A58F013398 /* Pods_KeyManager.framework */; }; @@ -50,6 +55,14 @@ A791100022146E04001C6761 /* libsecp256k1.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libsecp256k1.a; sourceTree = ""; }; A791100222147903001C6761 /* CPlusPlusBridger.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = CPlusPlusBridger.h; sourceTree = ""; }; A791100322147903001C6761 /* CPlusPlusBridger.mm */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.objcpp; path = CPlusPlusBridger.mm; sourceTree = ""; }; + A79110172215A682001C6761 /* libkaitai_struct_cpp_stl_runtime.a */ = {isa = PBXFileReference; lastKnownFileType = archive.ar; path = libkaitai_struct_cpp_stl_runtime.a; sourceTree = ""; }; + A79110192215AB48001C6761 /* Key.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Key.h; sourceTree = ""; }; + A791101A2215AB48001C6761 /* Key.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Key.m; sourceTree = ""; }; + A795236F2215B05300078EE5 /* SYFlatButton.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = SYFlatButton.h; path = ../../keychain_mac/SYFlatButton.h; sourceTree = ""; }; + A79523702215B05300078EE5 /* SYFlatButton.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = SYFlatButton.m; path = ../../keychain_mac/SYFlatButton.m; sourceTree = ""; }; + A79523752215B36600078EE5 /* WindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WindowController.h; sourceTree = ""; }; + A79523762215B36600078EE5 /* WindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = WindowController.m; sourceTree = ""; }; + A79523782215B55100078EE5 /* CreateKeyVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateKeyVC.swift; sourceTree = ""; }; A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "KeyManager-Bridging-Header.h"; sourceTree = ""; }; A79F78B821F89D0400E2C184 /* HexToRgbColor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HexToRgbColor.h; sourceTree = ""; }; A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = HexToRgbColor.mm; sourceTree = ""; }; @@ -65,6 +78,7 @@ A7910FF922146DC7001C6761 /* libkeychain_common.a in Frameworks */, A791100122146E04001C6761 /* libsecp256k1.a in Frameworks */, AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */, + A79110182215A682001C6761 /* libkaitai_struct_cpp_stl_runtime.a in Frameworks */, A7910FFF22146DF7001C6761 /* libethash.a in Frameworks */, A7910FFB22146DDE001C6761 /* libfc_light.a in Frameworks */, ); @@ -104,9 +118,12 @@ isa = PBXGroup; children = ( A776F49F21D0DD95006736C9 /* AppDelegate.swift */, + A79523752215B36600078EE5 /* WindowController.h */, + A79523762215B36600078EE5 /* WindowController.m */, A776F4A121D0DD95006736C9 /* ViewController.swift */, A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */, A79F78BB21F8A17900E2C184 /* TableRowView.swift */, + A79523782215B55100078EE5 /* CreateKeyVC.swift */, A776F4A321D0DD97006736C9 /* Assets.xcassets */, A776F4A521D0DD97006736C9 /* Main.storyboard */, A776F4A821D0DD97006736C9 /* Info.plist */, @@ -115,8 +132,12 @@ A776F4B121D0E66B006736C9 /* KeyManager.swift */, A776F4B721D39AB7006736C9 /* String+extension.swift */, A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */, + A795236F2215B05300078EE5 /* SYFlatButton.h */, + A79523702215B05300078EE5 /* SYFlatButton.m */, A791100222147903001C6761 /* CPlusPlusBridger.h */, A791100322147903001C6761 /* CPlusPlusBridger.mm */, + A79110192215AB48001C6761 /* Key.h */, + A791101A2215AB48001C6761 /* Key.m */, A79F78B821F89D0400E2C184 /* HexToRgbColor.h */, A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */, A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */, @@ -127,6 +148,7 @@ F73689D206923AF1FA7A3A0E /* Frameworks */ = { isa = PBXGroup; children = ( + A79110172215A682001C6761 /* libkaitai_struct_cpp_stl_runtime.a */, A791100022146E04001C6761 /* libsecp256k1.a */, A7910FFE22146DF7001C6761 /* libethash.a */, A7910FFC22146DE8001C6761 /* libeth-crypto.a */, @@ -267,13 +289,17 @@ isa = PBXSourcesBuildPhase; buildActionMask = 2147483647; files = ( + A791101B2215AB48001C6761 /* Key.m in Sources */, + A79523772215B36600078EE5 /* WindowController.m in Sources */, A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */, A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */, A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */, A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */, A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */, A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */, + A79523792215B55100078EE5 /* CreateKeyVC.swift in Sources */, A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */, + A79523712215B05300078EE5 /* SYFlatButton.m in Sources */, A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */, A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */, A791100422147903001C6761 /* CPlusPlusBridger.mm in Sources */, @@ -470,6 +496,7 @@ "/usr/local/lib/libboost_atomic-mt.a", "/Users/mikhaillutskiy/openssl-install/lib/libssl.a", /usr/lib/libc.dylib, + libkaitai_struct_cpp_stl_runtime.a, ); PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; PRODUCT_NAME = "$(TARGET_NAME)"; @@ -540,6 +567,7 @@ "/usr/local/lib/libboost_atomic-mt.a", "/Users/mikhaillutskiy/openssl-install/lib/libssl.a", /usr/lib/libc.dylib, + libkaitai_struct_cpp_stl_runtime.a, ); PRODUCT_BUNDLE_IDENTIFIER = ru.lwts.KeyManager; PRODUCT_NAME = "$(TARGET_NAME)"; diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard index 2afa6ae..76b79bd 100644 --- a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -683,15 +683,34 @@ - - + + - - + + + + + + + + + + + @@ -1126,7 +1145,7 @@ - - - + + - - - - + + + - - - - - + + + + + + - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + - - - - - - + + + + + + + + + + + - + - + diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.h b/keymanager_mac/KeyManager/CPlusPlusBridger.h index 83eaf85..6fa2497 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.h +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.h @@ -7,12 +7,14 @@ // #import - +#import "Key.h" NS_ASSUME_NONNULL_BEGIN @interface CPlusPlusBridger : NSObject - (NSInteger) getKeyfilesCount; +- (Key *) getKeyById:(NSInteger) indexRow; +- (void) createKeyWithName:(NSString* )keyname description:(NSString*)keyDescription encrypted:(BOOL)encrypted password:(NSString *) password cipher:(NSString *) cipher; @end diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.mm b/keymanager_mac/KeyManager/CPlusPlusBridger.mm index 1c5fd52..228f0fb 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.mm +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.mm @@ -19,4 +19,27 @@ - (NSInteger) getKeyfilesCount { return distance; } +- (Key *) getKeyById:(NSInteger) indexRow { + auto& keyfiles = keyfile_singleton::instance(); + auto& index = keyfiles[indexRow]; + Key *key = [[Key alloc] init]; + key.name = [NSString stringWithUTF8String:index.keyname.c_str()]; + return key; +} + +- (void) createKeyWithName:(NSString* )keyname description:(NSString*)keyDescription encrypted:(BOOL)encrypted password:(NSString *) password cipher:(NSString *) cipher { + + auto pass = [password UTF8String]; +// typedef typename decltype(pass)::print_type print; + + auto& keyfiles = keyfile_singleton::instance(); + + keyfiles.create(std::bind(&create_new_keyfile, [keyname UTF8String], [keyDescription UTF8String], encrypted, keyfile_format::cipher_etype::aes256, keyfile_format::curve_etype::secp256k1, [&pass](const std::string& keyname) { + std::vector result; + std::copy(pass, pass + strlen(pass), std::back_inserter(result)); + return result; + })); +} + + @end diff --git a/keymanager_mac/KeyManager/CreateKeyVC.swift b/keymanager_mac/KeyManager/CreateKeyVC.swift new file mode 100644 index 0000000..58838da --- /dev/null +++ b/keymanager_mac/KeyManager/CreateKeyVC.swift @@ -0,0 +1,65 @@ +// +// CreateKeyVC.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 14/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +import Cocoa + +class CreateKeyVC: NSViewController { + + @IBOutlet weak var nameTextField: NSTextField! + @IBOutlet weak var descriptionTextField: NSTextField! + @IBOutlet weak var cipherPopUpButton: NSPopUpButton! + @IBOutlet weak var passwordTextField: NSSecureTextField! + @IBOutlet weak var rePasswordTextField: NSSecureTextField! + @IBOutlet weak var passwordView: NSView! + + var isEncrypted = true + + override func viewDidLoad() { + super.viewDidLoad() + // Do view setup here. + } + + @IBAction func cancelAction(_ sender: Any) { + self.dismiss(self) + } + + @IBAction func createAction(_ sender: Any) { + if nameTextField.stringValue != "" { + if isEncrypted { + if passwordTextField.stringValue == rePasswordTextField.stringValue && passwordTextField.stringValue != "" { + CPlusPlusBridger().createKey(withName: nameTextField.stringValue, description: descriptionTextField.stringValue, encrypted: isEncrypted, password: passwordTextField.stringValue, cipher: "") + self.dismiss(self) + } else { + let alert = NSAlert() + alert.icon = NSImage() + alert.messageText = "Error" + alert.informativeText = "Passphrases must match and not be empty" + alert.addButton(withTitle: "OK") + alert.beginSheetModal(for: self.view.window!, completionHandler: nil) + } + } + } else { + let alert = NSAlert() + alert.icon = NSImage() + alert.messageText = "Error" + alert.informativeText = "Keyname must not be empty" + alert.addButton(withTitle: "OK") + alert.beginSheetModal(for: self.view.window!, completionHandler: nil) + } + } + + @IBAction func clickToEncryptedCheckbox(_ sender: NSButton) { + if sender.state == .on { + isEncrypted = true + passwordView.isHidden = false + } else if sender.state == .off { + isEncrypted = false + passwordView.isHidden = true + } + } +} diff --git a/keymanager_mac/KeyManager/Key.h b/keymanager_mac/KeyManager/Key.h new file mode 100644 index 0000000..1bafa20 --- /dev/null +++ b/keymanager_mac/KeyManager/Key.h @@ -0,0 +1,19 @@ +// +// Key.h +// KeyManager +// +// Created by Mikhail Lutskiy on 14/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface Key : NSObject + +@property (nonatomic, strong) NSString *name; + +@end + +NS_ASSUME_NONNULL_END diff --git a/keymanager_mac/KeyManager/Key.m b/keymanager_mac/KeyManager/Key.m new file mode 100644 index 0000000..7b1259e --- /dev/null +++ b/keymanager_mac/KeyManager/Key.m @@ -0,0 +1,13 @@ +// +// Key.m +// KeyManager +// +// Created by Mikhail Lutskiy on 14/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import "Key.h" + +@implementation Key + +@end diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index 1b71e3e..8f2ff24 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -59,10 +59,11 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour var text: String = "" var cellIdentifier: String = "" - let item = KeyManager.shared.keys[row] +// let item = KeyManager.shared.keys[row] + let key = CPlusPlusBridger().getKeyById(row) if tableColumn == tableView.tableColumns[0] { - text = item.fullKeyName + text = key.name cellIdentifier = CellIdentifiers.LocationCell } diff --git a/keymanager_mac/KeyManager/WindowController.h b/keymanager_mac/KeyManager/WindowController.h new file mode 100644 index 0000000..422fc78 --- /dev/null +++ b/keymanager_mac/KeyManager/WindowController.h @@ -0,0 +1,18 @@ +// +// WindowController.h +// KeyManager +// +// Created by Mikhail Lutskiy on 14/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import + +NS_ASSUME_NONNULL_BEGIN + +@interface WindowController : NSWindowController +- (IBAction)createKeyAction:(id)sender; + +@end + +NS_ASSUME_NONNULL_END diff --git a/keymanager_mac/KeyManager/WindowController.m b/keymanager_mac/KeyManager/WindowController.m new file mode 100644 index 0000000..5a4d673 --- /dev/null +++ b/keymanager_mac/KeyManager/WindowController.m @@ -0,0 +1,28 @@ +// +// WindowController.m +// KeyManager +// +// Created by Mikhail Lutskiy on 14/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import "WindowController.h" +#import "KeyManager-Swift.h" + +@interface WindowController () + +@end + +@implementation WindowController + +- (void)windowDidLoad { + [super windowDidLoad]; + + // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. +} + +- (IBAction)createKeyAction:(id)sender { + CreateKeyVC *vc = [self.storyboard instantiateControllerWithIdentifier:@"CreateKeyVC"]; + [self.contentViewController presentViewControllerAsSheet:vc]; +} +@end From 001a69dbaeceba81ed6b60e8b0c87a629517b091 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Fri, 15 Feb 2019 13:40:49 +0300 Subject: [PATCH 07/65] sm --- .../project.pbxproj | 8 ++-- .../Base.lproj/Main.storyboard | 4 +- .../keychain_lib/keychain_commands.hpp | 4 +- keychain_lib/src/keyfile_singleton.cpp | 4 +- .../KeyManager.xcodeproj/project.pbxproj | 6 +++ .../KeyManager/Base.lproj/Main.storyboard | 40 +++++++++++++++---- keymanager_mac/KeyManager/CPlusPlusBridger.h | 1 + keymanager_mac/KeyManager/CPlusPlusBridger.mm | 10 +++++ keymanager_mac/KeyManager/CreateKeyVC.swift | 2 + .../KeyManager/ViewController.swift | 11 ++++- 10 files changed, 71 insertions(+), 19 deletions(-) diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index bf20667..54f7fe7 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -11,8 +11,8 @@ A776F48D21D0C696006736C9 /* Print.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75B21A6B4A60021ED5E /* Print.swift */; }; A776F48F21D0C92E006736C9 /* UninstallVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F48E21D0C92E006736C9 /* UninstallVC.swift */; }; A776F49021D0D147006736C9 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75721A6B4620021ED5E /* Alerts.swift */; }; - A7910FF722146745001C6761 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A7910FF622146745001C6761 /* bin.tar.gz */; }; A793A32921C2672B0061249D /* LicenseVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A793A32821C2672B0061249D /* LicenseVC.swift */; }; + A795237E2215CCE400078EE5 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A795237D2215CCE400078EE5 /* bin.tar.gz */; }; A799115F21C41AD500CB13B7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A799115E21C41AD500CB13B7 /* AppDelegate.swift */; }; A799116321C41AD500CB13B7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A799116221C41AD500CB13B7 /* Assets.xcassets */; }; A799116621C41AD500CB13B7 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A799116421C41AD500CB13B7 /* Main.storyboard */; }; @@ -44,8 +44,8 @@ A0679F4132141184C33311C6 /* Pods-Keychain Installer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Installer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Installer/Pods-Keychain Installer.debug.xcconfig"; sourceTree = ""; }; A1FECE3906833024E5D5394D /* Pods_Keychain_Uninstaller.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Keychain_Uninstaller.framework; sourceTree = BUILT_PRODUCTS_DIR; }; A776F48E21D0C92E006736C9 /* UninstallVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallVC.swift; sourceTree = ""; }; - A7910FF622146745001C6761 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A793A32821C2672B0061249D /* LicenseVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseVC.swift; sourceTree = ""; }; + A795237D2215CCE400078EE5 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A799115C21C41AD500CB13B7 /* Keychain Uninstaller.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Keychain Uninstaller.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A799115E21C41AD500CB13B7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; A799116221C41AD500CB13B7 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -168,7 +168,7 @@ A7E7F74321A6B0D10021ED5E /* Main.storyboard */, A7E7F74621A6B0D10021ED5E /* Info.plist */, A7E7F74721A6B0D10021ED5E /* Keychain_Installer.entitlements */, - A7910FF622146745001C6761 /* bin.tar.gz */, + A795237D2215CCE400078EE5 /* bin.tar.gz */, ); path = "KeyChain Installer"; sourceTree = ""; @@ -265,7 +265,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - A7910FF722146745001C6761 /* bin.tar.gz in Resources */, + A795237E2215CCE400078EE5 /* bin.tar.gz in Resources */, A7E7F74221A6B0D10021ED5E /* Assets.xcassets in Resources */, A7E7F74521A6B0D10021ED5E /* Main.storyboard in Resources */, ); diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index f7a525b..1628684 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -685,7 +685,7 @@ - + @@ -987,7 +987,7 @@ - + diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 1b66926..96f346a 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -62,8 +62,8 @@ #else #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) - #define KEY_DEFAULT_PATH "./keychain" - #define LOG_DEFAULT_PATH "./keychain/logs" + #define KEY_DEFAULT_PATH "/keychain" + #define LOG_DEFAULT_PATH "/keychain/logs" #else #ifdef _WIN32 diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 1943b2b..3018acb 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -80,7 +80,7 @@ void keyfile_singleton::signlog_load() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto dir = bfs::path(getenv("HOME")); - key_dir += bfs::path(SIGN_LOGS_DEFAULT_PATH_); + dir += bfs::path(SIGN_LOGS_DEFAULT_PATH_); #else bfs::path dir(SIGN_LOGS_DEFAULT_PATH_); #endif @@ -440,4 +440,4 @@ bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_p } -} \ No newline at end of file +} diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj index 14eae9a..a7aa844 100644 --- a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -27,6 +27,7 @@ A79523712215B05300078EE5 /* SYFlatButton.m in Sources */ = {isa = PBXBuildFile; fileRef = A79523702215B05300078EE5 /* SYFlatButton.m */; }; A79523772215B36600078EE5 /* WindowController.m in Sources */ = {isa = PBXBuildFile; fileRef = A79523762215B36600078EE5 /* WindowController.m */; }; A79523792215B55100078EE5 /* CreateKeyVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79523782215B55100078EE5 /* CreateKeyVC.swift */; }; + A795237C2215C6E000078EE5 /* TableView.m in Sources */ = {isa = PBXBuildFile; fileRef = A795237A2215C6E000078EE5 /* TableView.m */; }; A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */ = {isa = PBXBuildFile; fileRef = A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */; }; A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A79F78BB21F8A17900E2C184 /* TableRowView.swift */; }; AD6703CBBAA6B5EB11907AA8 /* Pods_KeyManager.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 130888C1592515A58F013398 /* Pods_KeyManager.framework */; }; @@ -63,6 +64,8 @@ A79523752215B36600078EE5 /* WindowController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = WindowController.h; sourceTree = ""; }; A79523762215B36600078EE5 /* WindowController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = WindowController.m; sourceTree = ""; }; A79523782215B55100078EE5 /* CreateKeyVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CreateKeyVC.swift; sourceTree = ""; }; + A795237A2215C6E000078EE5 /* TableView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = TableView.m; path = ../../keychain_mac/TableView.m; sourceTree = ""; }; + A795237B2215C6E000078EE5 /* TableView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = TableView.h; path = ../../keychain_mac/TableView.h; sourceTree = ""; }; A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "KeyManager-Bridging-Header.h"; sourceTree = ""; }; A79F78B821F89D0400E2C184 /* HexToRgbColor.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = HexToRgbColor.h; sourceTree = ""; }; A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = HexToRgbColor.mm; sourceTree = ""; }; @@ -141,6 +144,8 @@ A79F78B821F89D0400E2C184 /* HexToRgbColor.h */, A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */, A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */, + A795237B2215C6E000078EE5 /* TableView.h */, + A795237A2215C6E000078EE5 /* TableView.m */, ); path = KeyManager; sourceTree = ""; @@ -292,6 +297,7 @@ A791101B2215AB48001C6761 /* Key.m in Sources */, A79523772215B36600078EE5 /* WindowController.m in Sources */, A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */, + A795237C2215C6E000078EE5 /* TableView.m in Sources */, A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */, A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */, A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */, diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard index 76b79bd..8505854 100644 --- a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -691,10 +691,8 @@ - + - - + + + + + + + + + + @@ -754,14 +776,14 @@ - + - + @@ -1181,6 +1203,7 @@ + @@ -1295,14 +1318,14 @@ - + - + - + @@ -1403,5 +1426,6 @@ Gw + diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.h b/keymanager_mac/KeyManager/CPlusPlusBridger.h index 6fa2497..3726fbe 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.h +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.h @@ -15,6 +15,7 @@ NS_ASSUME_NONNULL_BEGIN - (NSInteger) getKeyfilesCount; - (Key *) getKeyById:(NSInteger) indexRow; - (void) createKeyWithName:(NSString* )keyname description:(NSString*)keyDescription encrypted:(BOOL)encrypted password:(NSString *) password cipher:(NSString *) cipher; +- (void) reloadData; @end diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.mm b/keymanager_mac/KeyManager/CPlusPlusBridger.mm index 228f0fb..1d92bc0 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.mm +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.mm @@ -41,5 +41,15 @@ - (void) createKeyWithName:(NSString* )keyname description:(NSString*)keyDescrip })); } +- (void) reloadData { + auto& keyfiles = keyfile_singleton::instance(); + keyfiles.keydata_load(); +} + +- (void) deleteKey:(NSString *)publicKey { + auto& keyfiles = keyfile_singleton::instance(); + auto pkey = dev::Public([publicKey UTF8String]); +// keyfiles.remove(pkey, std::bind(&remove_unlock, my_unlock_functor)); +} @end diff --git a/keymanager_mac/KeyManager/CreateKeyVC.swift b/keymanager_mac/KeyManager/CreateKeyVC.swift index 58838da..02d54a2 100644 --- a/keymanager_mac/KeyManager/CreateKeyVC.swift +++ b/keymanager_mac/KeyManager/CreateKeyVC.swift @@ -34,6 +34,8 @@ class CreateKeyVC: NSViewController { if passwordTextField.stringValue == rePasswordTextField.stringValue && passwordTextField.stringValue != "" { CPlusPlusBridger().createKey(withName: nameTextField.stringValue, description: descriptionTextField.stringValue, encrypted: isEncrypted, password: passwordTextField.stringValue, cipher: "") self.dismiss(self) + NotificationCenter.default.post(name: Notification.Name(rawValue: "reloadData"), object: nil) + print("send") } else { let alert = NSAlert() alert.icon = NSImage() diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index 8f2ff24..ab502bc 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -11,6 +11,7 @@ import Cocoa class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSource { @IBOutlet weak var tableView: NSTableView! + @IBOutlet weak var transactionTableView: NSTableView! @IBOutlet weak var websocketStatusLabel: NSTextField! @IBOutlet weak var creationDate: NSTextFieldCell! @IBOutlet weak var keychainVersion: NSTextFieldCell! @@ -35,6 +36,8 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour self.detailsView.wantsLayer = true self.detailsView.layer?.backgroundColor = NSColor(red: 213.0/255.0, green: 220.0/255.0, blue: 230.0/255.0, alpha: 1).cgColor + NotificationCenter.default.addObserver(self, selector: #selector(reloadTableView), name: NSNotification.Name("reloadData"), object: nil) + // titleView.wantsLayer = true // titleView.layer?.backgroundColor = NSColor.white.cgColor @@ -43,6 +46,12 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour // Do any additional setup after loading the view. } + @objc func reloadTableView () { + CPlusPlusBridger().reloadData() + self.tableView.reloadData() + print("load") + } + func updateTableView () { } @@ -96,7 +105,7 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour } func tableViewSelectionDidChange(_ notification: Notification) { - print("select") + print(notification.object) let obj = notification.object as! NSTableView let item = KeyManager.shared.keys[obj.selectedRow] detailsView.isHidden = false From efffad078fd2616e5247e78a05e115f61dc1aef5 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Fri, 15 Feb 2019 16:10:53 +0300 Subject: [PATCH 08/65] km --- .../macOS/Common/UnistallerManager.swift | 6 +- .../macOS/KeyChain Installer/ProgressVC.swift | 20 ++-- .../keychain_lib/keychain_commands.hpp | 4 +- keychain_lib/src/keyfile_singleton.cpp | 7 +- .../KeyManager.xcodeproj/project.pbxproj | 18 +-- .../xcschemes/KeyManager.xcscheme | 1 - .../KeyManager/Base.lproj/Main.storyboard | 106 +++++++++++++++++- keymanager_mac/KeyManager/CPlusPlusBridger.h | 3 + keymanager_mac/KeyManager/CPlusPlusBridger.mm | 47 ++++++++ keymanager_mac/KeyManager/DeleteKeyVC.swift | 26 +++++ keymanager_mac/KeyManager/Key.h | 5 + keymanager_mac/KeyManager/KeyFileModel.swift | 73 ------------ keymanager_mac/KeyManager/KeyManager.swift | 60 ---------- keymanager_mac/KeyManager/Log.h | 31 +++++ keymanager_mac/KeyManager/Log.m | 13 +++ .../KeyManager/ViewController.swift | 78 ++++++++----- keymanager_mac/KeyManager/WindowController.h | 2 + keymanager_mac/KeyManager/WindowController.m | 4 + 18 files changed, 314 insertions(+), 190 deletions(-) create mode 100644 keymanager_mac/KeyManager/DeleteKeyVC.swift delete mode 100644 keymanager_mac/KeyManager/KeyFileModel.swift delete mode 100644 keymanager_mac/KeyManager/KeyManager.swift create mode 100644 keymanager_mac/KeyManager/Log.h create mode 100644 keymanager_mac/KeyManager/Log.m diff --git a/installer/macOS/Common/UnistallerManager.swift b/installer/macOS/Common/UnistallerManager.swift index f40fd2c..5be97cf 100644 --- a/installer/macOS/Common/UnistallerManager.swift +++ b/installer/macOS/Common/UnistallerManager.swift @@ -84,17 +84,17 @@ class UninstallerManager { func disableAutoRunProcess () { do { - try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .globalLaunchDaemon) + try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { print(error.localizedDescription) } do { - try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .globalLaunchDaemon) + try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { print(error.localizedDescription) } do { - try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .globalLaunchDaemon) + try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .userLaunchAgent) } catch { print(error.localizedDescription) } diff --git a/installer/macOS/KeyChain Installer/ProgressVC.swift b/installer/macOS/KeyChain Installer/ProgressVC.swift index f54c7d7..318aa28 100644 --- a/installer/macOS/KeyChain Installer/ProgressVC.swift +++ b/installer/macOS/KeyChain Installer/ProgressVC.swift @@ -31,7 +31,7 @@ class ProgressVC: NSViewController { fileprivate func jobWorker(dataPath: String) { self.infoTextField.stringValue = "Searching old versions..." self.stopJobs() - self.deleteFileAtPath("/Library/LaunchDaemons/" + Consts.JOB_PLIST) +// self.deleteFileAtPath("/Library/LaunchDaemons/" + Consts.JOB_PLIST) self.addRpathToBinary(path: dataPath) if LocalStorage.shared.isAutoStart { self.infoTextField.stringValue = "Creating autoload daemon..." @@ -50,7 +50,7 @@ class ProgressVC: NSViewController { job.runAtLoad = true job.keepAlive = true do { - try ahLaunchCtl.add(job, to: .globalLaunchDaemon) + try ahLaunchCtl.add(job, to: .userLaunchAgent) } catch { print(error.localizedDescription) } @@ -84,13 +84,13 @@ class ProgressVC: NSViewController { print("OK untar") print(dataPath) self.jobWorker(dataPath: dataPath) - AppleScriptManager.runScriptWithBody("cp -a '" + dataPath + "/keys/.' /var/keychain/key_data && mkdir /var/keychain/signlogs_data", isAdminRequired: true, success: { +// AppleScriptManager.runScriptWithBody("cp -a '" + dataPath + "/keys/.' /var/keychain/key_data && mkdir /var/keychain/signlogs_data", isAdminRequired: true, success: { self.infoTextField.stringValue = "Installation complete!" self.installText("Installation complete!") - }, failure: { (error) in - print("ERROR: \(error)") - self.installText(error.description) - }) +// }, failure: { (error) in +// print("ERROR: \(error)") +// self.installText(error.description) +// }) }) { (error) in print("ERROR: \(error)") @@ -101,17 +101,17 @@ class ProgressVC: NSViewController { /// Function stop launchd job func stopJobs() { do { - try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .globalLaunchDaemon) + try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { print(error.localizedDescription) } do { - try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .globalLaunchDaemon) + try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { print(error.localizedDescription) } do { - try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .globalLaunchDaemon) + try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .userLaunchAgent) } catch { print(error.localizedDescription) } diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 96f346a..efefbec 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -62,8 +62,8 @@ #else #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) - #define KEY_DEFAULT_PATH "/keychain" - #define LOG_DEFAULT_PATH "/keychain/logs" + #define KEY_DEFAULT_PATH "/Library/Application Support/keychain" + #define LOG_DEFAULT_PATH "/Library/Application Support/keychain/logs" #else #ifdef _WIN32 diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 78d8f2e..d474259 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -79,8 +79,11 @@ void keyfile_singleton::keydata_load() void keyfile_singleton::signlog_load() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) - auto dir = bfs::path(getenv("HOME")); - dir += bfs::path(SIGN_LOGS_DEFAULT_PATH_); + auto dir = bfs::path(getenv("HOME")); + dir += "/"; + dir += bfs::path(SIGN_LOGS_DEFAULT_PATH_); +// auto dir = bfs::path(getenv("HOME")); +// dir += bfs::path(SIGN_LOGS_DEFAULT_PATH_); #else bfs::path dir(SIGN_LOGS_DEFAULT_PATH_); #endif diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj index a7aa844..7e1d2d7 100644 --- a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -7,12 +7,12 @@ objects = { /* Begin PBXBuildFile section */ + A71840942216D8C9009A8D49 /* Log.m in Sources */ = {isa = PBXBuildFile; fileRef = A71840932216D8C9009A8D49 /* Log.m */; }; + A71840962216E10A009A8D49 /* DeleteKeyVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A71840952216E10A009A8D49 /* DeleteKeyVC.swift */; }; A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F49F21D0DD95006736C9 /* AppDelegate.swift */; }; A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4A121D0DD95006736C9 /* ViewController.swift */; }; A776F4A421D0DD97006736C9 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A776F4A321D0DD97006736C9 /* Assets.xcassets */; }; A776F4A721D0DD97006736C9 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A776F4A521D0DD97006736C9 /* Main.storyboard */; }; - A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */; }; - A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B121D0E66B006736C9 /* KeyManager.swift */; }; A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B721D39AB7006736C9 /* String+extension.swift */; }; A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */; }; A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */; }; @@ -37,6 +37,9 @@ 130888C1592515A58F013398 /* Pods_KeyManager.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_KeyManager.framework; sourceTree = BUILT_PRODUCTS_DIR; }; 188A215C60F625DB886DF7B7 /* Pods-KeyManager.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KeyManager.release.xcconfig"; path = "Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager.release.xcconfig"; sourceTree = ""; }; 9E7F5FE43CEBFF8FE8BEDA2F /* Pods-KeyManager.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KeyManager.debug.xcconfig"; path = "Pods/Target Support Files/Pods-KeyManager/Pods-KeyManager.debug.xcconfig"; sourceTree = ""; }; + A71840922216D8C9009A8D49 /* Log.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = Log.h; sourceTree = ""; }; + A71840932216D8C9009A8D49 /* Log.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = Log.m; sourceTree = ""; }; + A71840952216E10A009A8D49 /* DeleteKeyVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeleteKeyVC.swift; sourceTree = ""; }; A776F49C21D0DD95006736C9 /* KeyManager.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KeyManager.app; sourceTree = BUILT_PRODUCTS_DIR; }; A776F49F21D0DD95006736C9 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; A776F4A121D0DD95006736C9 /* ViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ViewController.swift; sourceTree = ""; }; @@ -44,8 +47,6 @@ A776F4A621D0DD97006736C9 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; A776F4A821D0DD97006736C9 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; A776F4A921D0DD97006736C9 /* KeyManager.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = KeyManager.entitlements; sourceTree = ""; }; - A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyFileModel.swift; sourceTree = ""; }; - A776F4B121D0E66B006736C9 /* KeyManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KeyManager.swift; sourceTree = ""; }; A776F4B721D39AB7006736C9 /* String+extension.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+extension.swift"; sourceTree = ""; }; A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppleScriptManager.swift; sourceTree = ""; }; A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebsocketChecker.swift; sourceTree = ""; }; @@ -127,12 +128,11 @@ A776F4BB21D3A7F8006736C9 /* WebsocketChecker.swift */, A79F78BB21F8A17900E2C184 /* TableRowView.swift */, A79523782215B55100078EE5 /* CreateKeyVC.swift */, + A71840952216E10A009A8D49 /* DeleteKeyVC.swift */, A776F4A321D0DD97006736C9 /* Assets.xcassets */, A776F4A521D0DD97006736C9 /* Main.storyboard */, A776F4A821D0DD97006736C9 /* Info.plist */, A776F4A921D0DD97006736C9 /* KeyManager.entitlements */, - A776F4AF21D0DF58006736C9 /* KeyFileModel.swift */, - A776F4B121D0E66B006736C9 /* KeyManager.swift */, A776F4B721D39AB7006736C9 /* String+extension.swift */, A776F4B921D3A78A006736C9 /* AppleScriptManager.swift */, A795236F2215B05300078EE5 /* SYFlatButton.h */, @@ -141,6 +141,8 @@ A791100322147903001C6761 /* CPlusPlusBridger.mm */, A79110192215AB48001C6761 /* Key.h */, A791101A2215AB48001C6761 /* Key.m */, + A71840922216D8C9009A8D49 /* Log.h */, + A71840932216D8C9009A8D49 /* Log.m */, A79F78B821F89D0400E2C184 /* HexToRgbColor.h */, A79F78B921F89D0400E2C184 /* HexToRgbColor.mm */, A79F78B721F89D0300E2C184 /* KeyManager-Bridging-Header.h */, @@ -296,15 +298,15 @@ files = ( A791101B2215AB48001C6761 /* Key.m in Sources */, A79523772215B36600078EE5 /* WindowController.m in Sources */, + A71840942216D8C9009A8D49 /* Log.m in Sources */, A776F4A221D0DD95006736C9 /* ViewController.swift in Sources */, + A71840962216E10A009A8D49 /* DeleteKeyVC.swift in Sources */, A795237C2215C6E000078EE5 /* TableView.m in Sources */, A776F4BC21D3A7F8006736C9 /* WebsocketChecker.swift in Sources */, A776F4B821D39AB7006736C9 /* String+extension.swift in Sources */, A776F4A021D0DD95006736C9 /* AppDelegate.swift in Sources */, A79F78BA21F89D0400E2C184 /* HexToRgbColor.mm in Sources */, - A776F4B021D0DF58006736C9 /* KeyFileModel.swift in Sources */, A79523792215B55100078EE5 /* CreateKeyVC.swift in Sources */, - A776F4B221D0E66B006736C9 /* KeyManager.swift in Sources */, A79523712215B05300078EE5 /* SYFlatButton.m in Sources */, A776F4BA21D3A78A006736C9 /* AppleScriptManager.swift in Sources */, A79F78BC21F8A17900E2C184 /* TableRowView.swift in Sources */, diff --git a/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme b/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme index 04aaa28..8eaef96 100644 --- a/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme +++ b/keymanager_mac/KeyManager.xcodeproj/xcshareddata/xcschemes/KeyManager.xcscheme @@ -45,7 +45,6 @@ buildConfiguration = "Debug" selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB" selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB" - debugAsWhichUser = "root" launchStyle = "0" useCustomWorkingDirectory = "NO" ignoresPersistentStateOnLaunch = "NO" diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard index 8505854..fce786a 100644 --- a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -705,16 +705,19 @@ - + + + + @@ -739,6 +742,7 @@ + @@ -1423,6 +1427,104 @@ Gw + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + NSAllRomanInputSourcesLocaleIdentifier + + + + + + + + + + + + + + + + diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.h b/keymanager_mac/KeyManager/CPlusPlusBridger.h index 3726fbe..831df70 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.h +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.h @@ -8,6 +8,8 @@ #import #import "Key.h" +#import "Log.h" + NS_ASSUME_NONNULL_BEGIN @interface CPlusPlusBridger : NSObject @@ -16,6 +18,7 @@ NS_ASSUME_NONNULL_BEGIN - (Key *) getKeyById:(NSInteger) indexRow; - (void) createKeyWithName:(NSString* )keyname description:(NSString*)keyDescription encrypted:(BOOL)encrypted password:(NSString *) password cipher:(NSString *) cipher; - (void) reloadData; +- (NSMutableArray *) getTransactionLogForPublicKey:(NSString *) publicKey; @end diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.mm b/keymanager_mac/KeyManager/CPlusPlusBridger.mm index 1d92bc0..82df7a6 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.mm +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.mm @@ -24,6 +24,13 @@ - (Key *) getKeyById:(NSInteger) indexRow { auto& index = keyfiles[indexRow]; Key *key = [[Key alloc] init]; key.name = [NSString stringWithUTF8String:index.keyname.c_str()]; + key.descriptionKey = [NSString stringWithUTF8String:index.description.c_str()]; + key.publicKey = [NSString stringWithUTF8String:index.public_key().hex().c_str()]; + auto seconds = index.creation_time.time_since_epoch().to_seconds(); + NSDate *createTime = [NSDate dateWithTimeIntervalSince1970:seconds]; + key.createTime = createTime; + key.keychainVersion = @"0.15"; + key.cipherType = @"aes256"; return key; } @@ -52,4 +59,44 @@ - (void) deleteKey:(NSString *)publicKey { // keyfiles.remove(pkey, std::bind(&remove_unlock, my_unlock_functor)); } +- (NSMutableArray *) getTransactionLogForPublicKey:(NSString *) publicKey { + NSMutableArray * logsArray = [NSMutableArray new]; + auto& keyfiles = keyfile_singleton::instance(); + NSLog(@"publicKey %@", publicKey); + printf("%s", [publicKey UTF8String]); + auto pkey = dev::Public([publicKey UTF8String]); + auto& logs = keyfiles.get_logs(pkey); + for (NSUInteger i = 0; i < std::distance(logs.begin(), logs.end()); i++) { + auto& log = logs[i]; + Log *logItem = [[Log alloc] init]; + switch (log.blockchain_type) { + case keychain_app::blockchain_te::array: + logItem.blockchainType = BlockchainTypeArray; + break; + case keychain_app::blockchain_te::unknown: + logItem.blockchainType = BlockchainTypeUnknown; + break; + case keychain_app::blockchain_te::bitshares: + logItem.blockchainType = BlockchainTypeBitshares; + break; + case keychain_app::blockchain_te::ethereum: + logItem.blockchainType = BlockchainTypeEthereum; + break; + case keychain_app::blockchain_te::bitcoin: + logItem.blockchainType = BlockchainTypeBitcoin; + break; + case keychain_app::blockchain_te::rawhash: + logItem.blockchainType = BlockchainTypeRawhash; + break; + } + logItem.chainId = [NSString stringWithUTF8String:log.chainid.c_str()]; + auto seconds = log.sign_time.time_since_epoch().to_seconds(); + NSDate *signTime = [NSDate dateWithTimeIntervalSince1970:seconds]; + logItem.signTime = signTime; +// logItem.transaction = log.transaction; + [logsArray addObject:logItem]; + } + return logsArray; +} + @end diff --git a/keymanager_mac/KeyManager/DeleteKeyVC.swift b/keymanager_mac/KeyManager/DeleteKeyVC.swift new file mode 100644 index 0000000..fcf7002 --- /dev/null +++ b/keymanager_mac/KeyManager/DeleteKeyVC.swift @@ -0,0 +1,26 @@ +// +// DeleteKeyVC.swift +// KeyManager +// +// Created by Mikhail Lutskiy on 15/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +import Cocoa + +class DeleteKeyVC: NSViewController { + + @IBOutlet weak var passwordTextField: NSSecureTextField! + @IBOutlet weak var passwordLabel: NSTextField! + override func viewDidLoad() { + super.viewDidLoad() + // Do view setup here. + } + + @IBAction func cancelAction(_ sender: Any) { + self.dismiss(self) + } + + @IBAction func deleteAction(_ sender: Any) { + } +} diff --git a/keymanager_mac/KeyManager/Key.h b/keymanager_mac/KeyManager/Key.h index 1bafa20..4e1eaba 100644 --- a/keymanager_mac/KeyManager/Key.h +++ b/keymanager_mac/KeyManager/Key.h @@ -13,6 +13,11 @@ NS_ASSUME_NONNULL_BEGIN @interface Key : NSObject @property (nonatomic, strong) NSString *name; +@property (nonatomic, strong) NSString *descriptionKey; +@property (nonatomic, strong) NSString *publicKey; +@property (nonatomic, strong) NSDate *createTime; +@property (nonatomic, strong) NSString *keychainVersion; +@property (nonatomic, strong) NSString *cipherType; @end diff --git a/keymanager_mac/KeyManager/KeyFileModel.swift b/keymanager_mac/KeyManager/KeyFileModel.swift deleted file mode 100644 index 6e3c249..0000000 --- a/keymanager_mac/KeyManager/KeyFileModel.swift +++ /dev/null @@ -1,73 +0,0 @@ -// -// KeyFileModel.swift -// KeyManager -// -// Created by Mikhail Lutskiy on 24/12/2018. -// Copyright © 2018 Mikhail Lutskii. All rights reserved. -// - -import Foundation -import ObjectMapper - -class KeyFileModel: Mappable { - - var filetype: String! - var keyname: String! - var description: String! - var keychainVersion: String! - var keyInfo: KeyInfoModel! - var creationTime: String! - var usageTime: String! - - required init?(map: Map) { - - } - - func mapping(map: Map) { - filetype <- map["filetype"] - keyname <- map["keyname"] - description <- map["description"] - keychainVersion <- map["keychain_version"] - keyInfo <- map["keyinfo"] - creationTime <- map["creation_time"] - usageTime <- map["usage_time"] - } -} - -class KeyInfoModel: Mappable { - - var format: String! - var encrypted: Bool! - var curveType: String! - var privKeyData: PrivKeyDataModel! - var publicKey: String! - - required init?(map: Map) { - - } - - func mapping(map: Map) { - format <- map["format"] - encrypted <- map["encrypted"] - curveType <- map["curve_type"] - privKeyData <- map["priv_key_data"] - publicKey <- map["public_key"] - } -} - -class PrivKeyDataModel: Mappable { - - var cipherType: String! - var iv: String! - var encData: String! - - required init?(map: Map) { - - } - - func mapping(map: Map) { - cipherType <- map["cipher_type"] - iv <- map["iv"] - encData <- map["enc_data"] - } -} diff --git a/keymanager_mac/KeyManager/KeyManager.swift b/keymanager_mac/KeyManager/KeyManager.swift deleted file mode 100644 index ef551f8..0000000 --- a/keymanager_mac/KeyManager/KeyManager.swift +++ /dev/null @@ -1,60 +0,0 @@ -// -// KeyManager.swift -// KeyManager -// -// Created by Mikhail Lutskiy on 24/12/2018. -// Copyright © 2018 Mikhail Lutskii. All rights reserved. -// - -import Foundation -import ObjectMapper - -struct KeysData { - var fullKeyName: String - var description: String - var publicKey: String - var location: String - var cipherType: String - var creationDate: String - var keychainVersion: String - var curveType: String -} - -class KeyManager { - - static let shared = KeyManager() - - let fileManager = FileManager.default - - var keys = [KeysData]() - - func start () { - keys.removeAll() - loadFiledFromKeyData() - } - - func loadFiledFromKeyData () { - let keys = try! fileManager.contentsOfDirectory(atPath: "/var/keychain/key_data") - print(keys) - - for key in keys { - if key.fileExtension() == "json" { - let fileAttr = try! fileManager.attributesOfItem(atPath: "/var/keychain/key_data/" + key) - - let keyModel = Mapper().map(JSONString: try! String(contentsOfFile: "/var/keychain/key_data/" + key)) - let keyStruct = KeysData(fullKeyName: keyModel?.keyname ?? "", - description: keyModel?.description ?? "", - publicKey: keyModel?.keyInfo.publicKey ?? "", - location: "/var/keychain/key_data/" + key, - cipherType: keyModel?.keyInfo.privKeyData != nil ? keyModel?.keyInfo.privKeyData.cipherType ?? "" : "", - creationDate: String(describing: fileAttr[FileAttributeKey.creationDate] as! Date), - keychainVersion: keyModel?.keychainVersion ?? "", - curveType: keyModel?.keyInfo.curveType ?? "") - self.keys.append(keyStruct) - } - print(self.keys) - - } - } - -} diff --git a/keymanager_mac/KeyManager/Log.h b/keymanager_mac/KeyManager/Log.h new file mode 100644 index 0000000..08d2002 --- /dev/null +++ b/keymanager_mac/KeyManager/Log.h @@ -0,0 +1,31 @@ +// +// Log.h +// KeyManager +// +// Created by Mikhail Lutskiy on 15/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import + +typedef NS_ENUM(NSUInteger, BlockchainType) { + BlockchainTypeArray, + BlockchainTypeUnknown, + BlockchainTypeBitshares, + BlockchainTypeEthereum, + BlockchainTypeBitcoin, + BlockchainTypeRawhash +}; + +NS_ASSUME_NONNULL_BEGIN + +@interface Log : NSObject + +@property BlockchainType blockchainType; +@property (nonatomic, strong) NSString* chainId; +@property (nonatomic, strong) NSDate* signTime; +@property (nonatomic, strong) NSString* transaction; + +@end + +NS_ASSUME_NONNULL_END diff --git a/keymanager_mac/KeyManager/Log.m b/keymanager_mac/KeyManager/Log.m new file mode 100644 index 0000000..b3c0ed6 --- /dev/null +++ b/keymanager_mac/KeyManager/Log.m @@ -0,0 +1,13 @@ +// +// Log.m +// KeyManager +// +// Created by Mikhail Lutskiy on 15/02/2019. +// Copyright © 2019 Mikhail Lutskii. All rights reserved. +// + +#import "Log.h" + +@implementation Log + +@end diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index ab502bc..39edfc6 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -20,6 +20,8 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour @IBOutlet weak var descriptionKey: NSTextFieldCell! @IBOutlet weak var publicKey: NSTextFieldCell! @IBOutlet weak var detailsView: NSView! + + var selectedPublicKey = "" // @IBOutlet weak var titleView: NSView! fileprivate enum CellIdentifiers { @@ -30,7 +32,8 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour super.viewDidLoad() self.tableView.delegate = self self.tableView.dataSource = self - KeyManager.shared.start() + self.transactionTableView.delegate = self + self.transactionTableView.dataSource = self tableView.reloadData() self.view.layer?.backgroundColor = NSColor(red: 242.0/255.0, green: 243.0/255.0, blue: 247.0/255.0, alpha: 1).cgColor self.detailsView.wantsLayer = true @@ -64,30 +67,42 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { - - var text: String = "" - var cellIdentifier: String = "" - -// let item = KeyManager.shared.keys[row] - let key = CPlusPlusBridger().getKeyById(row) - - if tableColumn == tableView.tableColumns[0] { - text = key.name - cellIdentifier = CellIdentifiers.LocationCell - } - - // 3 - if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { - cell.textField?.stringValue = text - return cell + if tableView == self.tableView { + var text: String = "" + var cellIdentifier: String = "" + + // let item = KeyManager.shared.keys[row] + let key = CPlusPlusBridger().getKeyById(row) + + if tableColumn == tableView.tableColumns[0] { + text = key.name + cellIdentifier = CellIdentifiers.LocationCell + } + + // 3 + if let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: cellIdentifier), owner: nil) as? NSTableCellView { + cell.textField?.stringValue = text + return cell + } + } else if tableView == self.transactionTableView { + if selectedPublicKey != "" { + let log = CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey) + } } return nil } func numberOfRows(in tableView: NSTableView) -> Int { - return CPlusPlusBridger().getKeyfilesCount() -// return KeyManager.shared.keys.count + if tableView == self.tableView { + return CPlusPlusBridger().getKeyfilesCount() + } else { + if selectedPublicKey != "" { + return CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey).count + } else { + return 0 + } + } } @objc func websocketStatus() { @@ -105,17 +120,22 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour } func tableViewSelectionDidChange(_ notification: Notification) { - print(notification.object) let obj = notification.object as! NSTableView - let item = KeyManager.shared.keys[obj.selectedRow] - detailsView.isHidden = false - creationDate.stringValue = item.creationDate - keychainVersion.stringValue = item.keychainVersion - cipherType.stringValue = item.cipherType - location.stringValue = item.location - descriptionKey.stringValue = item.description - publicKey.stringValue = item.publicKey - print(obj.selectedRow) + if obj == self.tableView { + let item = CPlusPlusBridger().getKeyById(obj.selectedRow) + detailsView.isHidden = false + let formatter = DateFormatter() + formatter.dateFormat = "MMM dd, YYYY, HH:mm:ss" + creationDate.stringValue = formatter.string(from: item.createTime) + keychainVersion.stringValue = item.keychainVersion + cipherType.stringValue = item.cipherType + location.stringValue = "" + descriptionKey.stringValue = item.descriptionKey + publicKey.stringValue = item.publicKey + selectedPublicKey = item.publicKey + transactionTableView.reloadData() + print(obj.selectedRow) + } } } diff --git a/keymanager_mac/KeyManager/WindowController.h b/keymanager_mac/KeyManager/WindowController.h index 422fc78..33273ea 100644 --- a/keymanager_mac/KeyManager/WindowController.h +++ b/keymanager_mac/KeyManager/WindowController.h @@ -12,6 +12,8 @@ NS_ASSUME_NONNULL_BEGIN @interface WindowController : NSWindowController - (IBAction)createKeyAction:(id)sender; +@property (weak) IBOutlet NSToolbarItem *removeKeyItem; +- (IBAction)removeKeyAction:(id)sender; @end diff --git a/keymanager_mac/KeyManager/WindowController.m b/keymanager_mac/KeyManager/WindowController.m index 5a4d673..cf7d1ff 100644 --- a/keymanager_mac/KeyManager/WindowController.m +++ b/keymanager_mac/KeyManager/WindowController.m @@ -25,4 +25,8 @@ - (IBAction)createKeyAction:(id)sender { CreateKeyVC *vc = [self.storyboard instantiateControllerWithIdentifier:@"CreateKeyVC"]; [self.contentViewController presentViewControllerAsSheet:vc]; } +- (IBAction)removeKeyAction:(id)sender { + DeleteKeyVC *vc = [self.storyboard instantiateControllerWithIdentifier:@"DeleteKeyVC"]; + [self.contentViewController presentViewControllerAsSheet:vc]; +} @end From 3c433dce42c17224e60eb26f0cf319dfdfad157c Mon Sep 17 00:00:00 2001 From: loutskiy Date: Fri, 15 Feb 2019 17:42:49 +0300 Subject: [PATCH 09/65] 1 --- .../macOS/KeyChain Installer.xcodeproj/project.pbxproj | 2 ++ keychain_lib/src/keychain.cpp | 4 ++-- keychain_lib/src/keychain_logger.cpp | 2 +- keychain_lib/src/keyfile_singleton.cpp | 8 ++++---- keymanager_mac/KeyManager.xcodeproj/project.pbxproj | 2 ++ keymanager_mac/KeyManager/CPlusPlusBridger.mm | 5 +++++ keymanager_mac/KeyManager/ViewController.swift | 2 ++ 7 files changed, 18 insertions(+), 7 deletions(-) diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index 54f7fe7..a465a55 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -422,6 +422,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); + MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = "io.array.Keychain-Uninstaller"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; @@ -444,6 +445,7 @@ "$(inherited)", "@executable_path/../Frameworks", ); + MACOSX_DEPLOYMENT_TARGET = 10.10; PRODUCT_BUNDLE_IDENTIFIER = "io.array.Keychain-Uninstaller"; PRODUCT_NAME = "$(TARGET_NAME)"; PROVISIONING_PROFILE_SPECIFIER = ""; diff --git a/keychain_lib/src/keychain.cpp b/keychain_lib/src/keychain.cpp index fe36381..353531e 100644 --- a/keychain_lib/src/keychain.cpp +++ b/keychain_lib/src/keychain.cpp @@ -48,7 +48,7 @@ keychain::keychain() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto key_dir = bfs::path(getenv("HOME")); - key_dir += bfs::path("/"KEY_DEFAULT_PATH_); + key_dir += bfs::path("/" KEY_DEFAULT_PATH_); #else bfs::path key_dir(KEY_DEFAULT_PATH_); #endif @@ -141,4 +141,4 @@ void keychain_app::secure_dlg_mod_base::connect(keychain_app::keychain_base &key void keychain_app::gui_mod_base::connect(keychain_app::keychain_base &keychain_) const { keychain_.select_key.connect(std::bind(&gui_mod_base::select_key, this)); -} \ No newline at end of file +} diff --git a/keychain_lib/src/keychain_logger.cpp b/keychain_lib/src/keychain_logger.cpp index 8cff0df..20badc3 100644 --- a/keychain_lib/src/keychain_logger.cpp +++ b/keychain_lib/src/keychain_logger.cpp @@ -20,7 +20,7 @@ logger_singleton::logger_singleton(std::string postfix) { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto dir = bfs::path(getenv("HOME")); - dir += bfs::path("/"LOG_DEFAULT_PATH); + dir += bfs::path("/" LOG_DEFAULT_PATH); #else bfs::path dir(LOG_DEFAULT_PATH); #endif diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 25f187a..e524694 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -47,7 +47,7 @@ void keyfile_singleton::keydata_load() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto key_dir = bfs::path(getenv("HOME")); - key_dir += bfs::path("/"KEY_DEFAULT_PATH_); + key_dir += bfs::path("/" KEY_DEFAULT_PATH_); #else bfs::path key_dir(KEY_DEFAULT_PATH_); #endif @@ -80,7 +80,7 @@ void keyfile_singleton::signlog_load() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto dir = bfs::path(getenv("HOME")); - dir += bfs::path("/"SIGN_LOGS_DEFAULT_PATH_); + dir += bfs::path("/" SIGN_LOGS_DEFAULT_PATH_); #else bfs::path dir(SIGN_LOGS_DEFAULT_PATH_); #endif @@ -263,7 +263,7 @@ void keyfile_singleton::flush_keyfile_impl(const value_t& keyfile_data) const { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto filepath = bfs::path(getenv("HOME")); - filepath += bfs::path("/"KEY_DEFAULT_PATH_"/"); + filepath += bfs::path("/" KEY_DEFAULT_PATH_"/"); #else bfs::path filepath(KEY_DEFAULT_PATH_"/"); #endif @@ -310,7 +310,7 @@ void keyfile_singleton::flush_all() const { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto keyfile_dir = bfs::path(getenv("HOME")); - keyfile_dir += bfs::path("/"KEY_DEFAULT_PATH_); + keyfile_dir += bfs::path("/" KEY_DEFAULT_PATH_); #else bfs::path keyfile_dir(KEY_DEFAULT_PATH_); #endif diff --git a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj index 7e1d2d7..ba23613 100644 --- a/keymanager_mac/KeyManager.xcodeproj/project.pbxproj +++ b/keymanager_mac/KeyManager.xcodeproj/project.pbxproj @@ -476,6 +476,7 @@ "$(inherited)", "$(PROJECT_DIR)", ); + MACOSX_DEPLOYMENT_TARGET = 10.14; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-std=c++14", @@ -548,6 +549,7 @@ "$(inherited)", "$(PROJECT_DIR)", ); + MACOSX_DEPLOYMENT_TARGET = 10.14; OTHER_CPLUSPLUSFLAGS = ( "$(OTHER_CFLAGS)", "-std=c++14", diff --git a/keymanager_mac/KeyManager/CPlusPlusBridger.mm b/keymanager_mac/KeyManager/CPlusPlusBridger.mm index 82df7a6..51e14ab 100644 --- a/keymanager_mac/KeyManager/CPlusPlusBridger.mm +++ b/keymanager_mac/KeyManager/CPlusPlusBridger.mm @@ -56,6 +56,7 @@ - (void) reloadData { - (void) deleteKey:(NSString *)publicKey { auto& keyfiles = keyfile_singleton::instance(); auto pkey = dev::Public([publicKey UTF8String]); +// keyfiles.remove(pkey, std::bind(&remove_unlock)) // keyfiles.remove(pkey, std::bind(&remove_unlock, my_unlock_functor)); } @@ -65,6 +66,7 @@ - (void) deleteKey:(NSString *)publicKey { NSLog(@"publicKey %@", publicKey); printf("%s", [publicKey UTF8String]); auto pkey = dev::Public([publicKey UTF8String]); + try { auto& logs = keyfiles.get_logs(pkey); for (NSUInteger i = 0; i < std::distance(logs.begin(), logs.end()); i++) { auto& log = logs[i]; @@ -96,6 +98,9 @@ - (void) deleteKey:(NSString *)publicKey { // logItem.transaction = log.transaction; [logsArray addObject:logItem]; } + } catch (fc_light::exception& e) { + NSLog(@"%@", [NSString stringWithUTF8String: e.to_detail_json_string().c_str()]); + } return logsArray; } diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index 39edfc6..116a396 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -86,6 +86,7 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour } } else if tableView == self.transactionTableView { if selectedPublicKey != "" { + print("self.transactionTableView") let log = CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey) } } @@ -98,6 +99,7 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour return CPlusPlusBridger().getKeyfilesCount() } else { if selectedPublicKey != "" { + print("numberOfRows") return CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey).count } else { return 0 From 4d84cde32c16dc53f3556ca988b084dfb138fc48 Mon Sep 17 00:00:00 2001 From: loutskiy Date: Thu, 28 Feb 2019 13:47:44 +0300 Subject: [PATCH 10/65] keymanager, installer with HOME pass --- installer/macOS/Common/UnistallerManager.swift | 15 +++++++++++++++ .../KeyChain Installer.xcodeproj/project.pbxproj | 8 ++++---- .../Base.lproj/Main.storyboard | 4 ++-- .../macOS/KeyChain Installer/ProgressVC.swift | 16 ++++++++++++++++ keychain_cmd_app/main.cpp | 8 +++++++- .../include/keychain_lib/keychain_commands.hpp | 8 ++++---- keychain_lib/src/keychain_logger.cpp | 12 ++++++++++++ .../KeyManager/Base.lproj/Main.storyboard | 2 +- keymanager_mac/KeyManager/ViewController.swift | 4 +++- 9 files changed, 64 insertions(+), 13 deletions(-) diff --git a/installer/macOS/Common/UnistallerManager.swift b/installer/macOS/Common/UnistallerManager.swift index 5be97cf..2232b2a 100644 --- a/installer/macOS/Common/UnistallerManager.swift +++ b/installer/macOS/Common/UnistallerManager.swift @@ -83,6 +83,21 @@ class UninstallerManager { } func disableAutoRunProcess () { + do { + try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } + do { + try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } + do { + try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } do { try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { diff --git a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj index a465a55..6cbb9db 100644 --- a/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj +++ b/installer/macOS/KeyChain Installer.xcodeproj/project.pbxproj @@ -8,11 +8,11 @@ /* Begin PBXBuildFile section */ 065E4561476CAD7D2A088F20 /* Pods_Keychain_Installer.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D45CE400EF06130F590AA706 /* Pods_Keychain_Installer.framework */; }; + A74663752225581F00E370A5 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A74663742225581F00E370A5 /* bin.tar.gz */; }; A776F48D21D0C696006736C9 /* Print.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75B21A6B4A60021ED5E /* Print.swift */; }; A776F48F21D0C92E006736C9 /* UninstallVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A776F48E21D0C92E006736C9 /* UninstallVC.swift */; }; A776F49021D0D147006736C9 /* Alerts.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7E7F75721A6B4620021ED5E /* Alerts.swift */; }; A793A32921C2672B0061249D /* LicenseVC.swift in Sources */ = {isa = PBXBuildFile; fileRef = A793A32821C2672B0061249D /* LicenseVC.swift */; }; - A795237E2215CCE400078EE5 /* bin.tar.gz in Resources */ = {isa = PBXBuildFile; fileRef = A795237D2215CCE400078EE5 /* bin.tar.gz */; }; A799115F21C41AD500CB13B7 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = A799115E21C41AD500CB13B7 /* AppDelegate.swift */; }; A799116321C41AD500CB13B7 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = A799116221C41AD500CB13B7 /* Assets.xcassets */; }; A799116621C41AD500CB13B7 /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = A799116421C41AD500CB13B7 /* Main.storyboard */; }; @@ -43,9 +43,9 @@ 6FF41F077014844269A8A241 /* Pods-Keychain Uninstaller.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Uninstaller.release.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Uninstaller/Pods-Keychain Uninstaller.release.xcconfig"; sourceTree = ""; }; A0679F4132141184C33311C6 /* Pods-Keychain Installer.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Keychain Installer.debug.xcconfig"; path = "Pods/Target Support Files/Pods-Keychain Installer/Pods-Keychain Installer.debug.xcconfig"; sourceTree = ""; }; A1FECE3906833024E5D5394D /* Pods_Keychain_Uninstaller.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Keychain_Uninstaller.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + A74663742225581F00E370A5 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A776F48E21D0C92E006736C9 /* UninstallVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = UninstallVC.swift; sourceTree = ""; }; A793A32821C2672B0061249D /* LicenseVC.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LicenseVC.swift; sourceTree = ""; }; - A795237D2215CCE400078EE5 /* bin.tar.gz */ = {isa = PBXFileReference; lastKnownFileType = archive.gzip; path = bin.tar.gz; sourceTree = ""; }; A799115C21C41AD500CB13B7 /* Keychain Uninstaller.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Keychain Uninstaller.app"; sourceTree = BUILT_PRODUCTS_DIR; }; A799115E21C41AD500CB13B7 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; A799116221C41AD500CB13B7 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; @@ -168,7 +168,7 @@ A7E7F74321A6B0D10021ED5E /* Main.storyboard */, A7E7F74621A6B0D10021ED5E /* Info.plist */, A7E7F74721A6B0D10021ED5E /* Keychain_Installer.entitlements */, - A795237D2215CCE400078EE5 /* bin.tar.gz */, + A74663742225581F00E370A5 /* bin.tar.gz */, ); path = "KeyChain Installer"; sourceTree = ""; @@ -265,7 +265,7 @@ isa = PBXResourcesBuildPhase; buildActionMask = 2147483647; files = ( - A795237E2215CCE400078EE5 /* bin.tar.gz in Resources */, + A74663752225581F00E370A5 /* bin.tar.gz in Resources */, A7E7F74221A6B0D10021ED5E /* Assets.xcassets in Resources */, A7E7F74521A6B0D10021ED5E /* Main.storyboard in Resources */, ); diff --git a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard index 1628684..6647cf7 100644 --- a/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard +++ b/installer/macOS/KeyChain Installer/Base.lproj/Main.storyboard @@ -685,7 +685,7 @@ - + @@ -987,7 +987,7 @@ - + diff --git a/installer/macOS/KeyChain Installer/ProgressVC.swift b/installer/macOS/KeyChain Installer/ProgressVC.swift index 318aa28..bbcd910 100644 --- a/installer/macOS/KeyChain Installer/ProgressVC.swift +++ b/installer/macOS/KeyChain Installer/ProgressVC.swift @@ -40,6 +40,7 @@ class ProgressVC: NSViewController { job.programArguments = [ dataPath + "/websocketd", "--port=16384", + "--passenv=HOME", "--staticdir=" + dataPath + "/examples", dataPath+"/keychain" ] @@ -100,6 +101,21 @@ class ProgressVC: NSViewController { /// Function stop launchd job func stopJobs() { + do { + try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } + do { + try ahLaunchCtl.unload(Consts.LABEL_JOB, in: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } + do { + try ahLaunchCtl.remove(Consts.LABEL_JOB, from: .globalLaunchDaemon) + } catch { + print(error.localizedDescription) + } do { try ahLaunchCtl.stop(Consts.LABEL_JOB, in: .userLaunchAgent) } catch { diff --git a/keychain_cmd_app/main.cpp b/keychain_cmd_app/main.cpp index 540b52c..ae3dc41 100644 --- a/keychain_cmd_app/main.cpp +++ b/keychain_cmd_app/main.cpp @@ -5,7 +5,7 @@ #include "cmd_parser.hpp" #include #include - +#include using namespace keychain_app; namespace attrs = boost::log::attributes; @@ -13,9 +13,12 @@ namespace attrs = boost::log::attributes; int main(int argc, char* argv[]) { +// std::cout << "Start keychain" << std::endl; auto& log = logger_singleton::instance(); +// std::cout << "auto keychain" << std::endl; BOOST_LOG_SEV(log.lg, info) << "KeyChain application started, version = " << keychain_app::version_info::version(); +// std::cout << "BOOST_LOG_SEV keychain" << std::endl; #ifdef LINUX BOOST_LOG_SEV(log.lg, info) << "OS: Linux"; @@ -24,8 +27,11 @@ int main(int argc, char* argv[]) #else BOOST_LOG_SEV(log.lg, info) << "OS: unknown"; #endif +// std::cout << "boost keychain" << std::endl; cmd_parser cmd_parser_; +// std::cout << "cmd_parser_ keychain" << std::endl; + return cmd_parser_.run(argc, argv); } diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 9e05c06..efb14e6 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -409,8 +409,8 @@ struct keychain_command : keychain_command_base }); auto reply = [&keyfiles, ¶ms, &id](auto& message, const dev::bytes& transaction){ - keyfiles.add_log_record(params.public_key, - keyfile_format::log_record(transaction, fc_light::time_point::now(), params.blockchain_type, params.chainid )); +// keyfiles.add_log_record(params.public_key, +// keyfile_format::log_record(transaction, fc_light::time_point::now(), params.blockchain_type, params.chainid )); json_response response(fc_light::variant(message), id); fc_light::variant res(response); return fc_light::json::to_string(res); @@ -658,8 +658,8 @@ struct keychain_command : keychain_command_base dev::bytes hash_vec; std::copy(params.hash.begin(), params.hash.end(), std::back_inserter(hash_vec)); - keyfiles.add_log_record(params.public_key, - keyfile_format::log_record(hash_vec, fc_light::time_point::now(), blockchain_te::rawhash, "")); +// keyfiles.add_log_record(params.public_key, +// keyfile_format::log_record(hash_vec, fc_light::time_point::now(), blockchain_te::rawhash, "")); json_response response(fc_light::variant(signature), id); fc_light::variant res(response); return fc_light::json::to_string(res); diff --git a/keychain_lib/src/keychain_logger.cpp b/keychain_lib/src/keychain_logger.cpp index 20badc3..d90da8f 100644 --- a/keychain_lib/src/keychain_logger.cpp +++ b/keychain_lib/src/keychain_logger.cpp @@ -19,14 +19,22 @@ namespace bfs = boost::filesystem; logger_singleton::logger_singleton(std::string postfix) { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) +// std::cout << "apple" << std::endl; +// std::cin.get(); +// auto dir = bfs::path(getenv("HOME")); auto dir = bfs::path(getenv("HOME")); +// std::cout << "dir" << dir.c_str() << std::endl; dir += bfs::path("/" LOG_DEFAULT_PATH); +// std::cout << "dir1234" << dir.c_str() << std::endl; + #else bfs::path dir(LOG_DEFAULT_PATH); #endif typedef sinks::synchronous_sink< sinks::text_file_backend > file_sink; std::string def_log_path = dir.c_str(); +// std::cout << "def_log_path" << def_log_path << std::endl; + // Create a text file sink #ifdef _WIN32 if (getenv("USERPROFILE") != NULL) { @@ -48,12 +56,15 @@ logger_singleton::logger_singleton(std::string postfix) } } #endif //_WIN32 +// std::cout << "d" << std::endl; boost::shared_ptr< file_sink > sink(new file_sink( keywords::file_name = def_log_path + "/%Y%m%d_%H%M%S_"+postfix+".log", keywords::rotation_size = 16384, keywords::auto_flush = true )); +// std::cout << "shared_ptr" << std::endl; + sink->set_formatter ( @@ -67,6 +78,7 @@ logger_singleton::logger_singleton(std::string postfix) logging::add_common_attributes(); logging::core::get()->add_sink(sink); +// std::cout << "core" << std::endl; } diff --git a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard index fce786a..fcec3df 100644 --- a/keymanager_mac/KeyManager/Base.lproj/Main.storyboard +++ b/keymanager_mac/KeyManager/Base.lproj/Main.storyboard @@ -1064,7 +1064,7 @@ - + diff --git a/keymanager_mac/KeyManager/ViewController.swift b/keymanager_mac/KeyManager/ViewController.swift index 116a396..daad5b5 100644 --- a/keymanager_mac/KeyManager/ViewController.swift +++ b/keymanager_mac/KeyManager/ViewController.swift @@ -26,6 +26,7 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour fileprivate enum CellIdentifiers { static let LocationCell = "locationId" + static let key1 = "key1" } override func viewDidLoad() { @@ -87,7 +88,8 @@ class ViewController: NSViewController, NSTableViewDelegate, NSTableViewDataSour } else if tableView == self.transactionTableView { if selectedPublicKey != "" { print("self.transactionTableView") - let log = CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey) + let logs = CPlusPlusBridger().getTransactionLog(forPublicKey: selectedPublicKey) + } } return nil From 569722cad5f8d71415677116586a374a97844c0c Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Thu, 28 Feb 2019 19:40:44 +0300 Subject: [PATCH 11/65] fix merge --- keychain_lib/include/keychain_lib/keychain_commands.hpp | 1 - 1 file changed, 1 deletion(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index f66750e..5b6f87a 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -352,7 +352,6 @@ struct keychain_command : keychain_command_base } FC_LIGHT_CAPTURE_TYPECHANGE_AND_RETHROW (fc_light::invalid_arg_exception, error, "cannot parse command params") - auto& sql = sql_singleton::instance(); unit_list_t unit_list; dev::Signature signature; std::vector raw(params.transaction.length()); From b928a44e955adc55960356097eb0fbf34332fb9e Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Fri, 1 Mar 2019 22:40:57 +0300 Subject: [PATCH 12/65] impl sql signlog --- .../keychain_lib/keychain_commands.hpp | 3 -- .../include/keychain_lib/sql_singleton.hpp | 8 +-- keychain_lib/src/keyfile_singleton.cpp | 11 +++- keychain_lib/src/sql_singleton.cpp | 53 ++++++++++++++----- 4 files changed, 55 insertions(+), 20 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 946fc10..99d2bd4 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -408,9 +408,6 @@ struct keychain_command : keychain_command_base auto reply = [&keyfiles, ¶ms, &id, &secmod_signhex_cmd](auto& message, const dev::bytes& transaction){ keyfiles.add_log_record(params.public_key, keyfile_format::log_record(transaction, fc_light::time_point::now(), params.blockchain_type )); - auto& sql = sql_singleton::instance(); - std::string key = params.public_key.hex(); - sql.insert(key, secmod_signhex_cmd); json_response response(fc_light::variant(message), id); fc_light::variant res(response); return fc_light::json::to_string(res); diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 1834f3a..272e181 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -4,15 +4,15 @@ #ifndef KEYCHAINAPP_SQL_SINGLETON_HPP #define KEYCHAINAPP_SQL_SINGLETON_HPP -#include -#include #include +#include "keychain_commands.hpp" struct sql_singleton { static sql_singleton& instance(); - std::vector select(std::string& ); - int insert(std::string&, std::string&); + const keychain_app::keyfiles_map::log_records_t select(const dev::Public& ); + int insert(const dev::Public&, const keychain_app::keyfile_format::log_record& ); + private: sql_singleton(); ~sql_singleton(); diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 73894d3..8ca88cd 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -304,7 +304,7 @@ void keyfile_singleton::flush_logrecords_impl(const prim_key_type& key, const lo { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto filepath = bfs::path(getenv("HOME")); - filepath += bfs::path(SIGN_LOGS_DEFAULT_PATH_"/"); + filepath += bfs::path("/" SIGN_LOGS_DEFAULT_PATH_"/"); #else bfs::path filepath(SIGN_LOGS_DEFAULT_PATH_"/"); #endif @@ -347,12 +347,17 @@ void keyfile_singleton::flush_all() const const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) { +/* signlog_load();//NOTE: it may be slowly, using sqlite and triggers is more preferable auto it = m_signlog_map.find(pkey); if (it == m_signlog_map.end()) FC_LIGHT_THROW_EXCEPTION(fc_light::file_not_found_exception, "Public_key: ${PKEY}", ("PKEY", pkey)); auto& records = it->second; return records.get(); +*/ + auto& sql = sql_singleton::instance(); + auto records = sql.select(pkey); + return records.get(); } const keyfile_singleton::log_date_index_type& keyfile_singleton::get_logs_date_ordered(const dev::Public& pkey) @@ -367,6 +372,9 @@ const keyfile_singleton::log_date_index_type& keyfile_singleton::get_logs_date_o void keyfile_singleton::add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record) { + auto& sql = sql_singleton::instance(); + sql.insert(pkey, record); + /* auto it = m_signlog_map.find(pkey); if (it == m_signlog_map.end()) { @@ -376,6 +384,7 @@ void keyfile_singleton::add_log_record(const dev::Public& pkey, const keyfile_fo } it->second.insert(record); flush_logrecords(pkey); + */ } keyfile_format::keyfile_t keychain_app::create_new_keyfile( diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index 4aec76c..86bd40c 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -2,7 +2,6 @@ // Created by user on 2/26/19. // #include -#include "keychain_commands.hpp" #include #define SQL_DB_DEFAULT_PATH KEY_DEFAULT_PATH "/sql" @@ -12,7 +11,7 @@ sql_singleton::sql_singleton() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) auto sql_dir = bfs::path(getenv("HOME")); - sql_dir += bfs::path("/"SQL_DB_DEFAULT_PATH); + sql_dir += bfs::path("/" SQL_DB_DEFAULT_PATH); #else bfs::path sql_dir(SQL_DB_DEFAULT_PATH); #endif @@ -26,8 +25,8 @@ sql_singleton::sql_singleton() "Can not create sql directory, path = ${directory}", ("directory", sql_dir.string())); } sqlite3_stmt * stmt; - const char * statement = "create table if not exists log (public_key text not null, " - "trx text not null)"; + const char * statement = "create table if not exists signlog (public_key text not null, " + "trx text not null, sign_time text not null, blockchain_type text not null)"; sql_dir += "/data.db"; if (sqlite3_open_v2(sql_dir.c_str(), &db, SQLITE_OPEN_FULLMUTEX|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, 0) != SQLITE_OK ) @@ -53,35 +52,65 @@ sql_singleton& sql_singleton::instance() return instance; } -std::vector sql_singleton::select(std::string& public_key) +const keychain_app::keyfiles_map::log_records_t sql_singleton::select(const dev::Public& pkey) { sqlite3_stmt * stmt; - std::vector set; - const char * statement = "select trx from log where public_key=?"; + std::vector set; + const char * statement = "select trx, sign_time, blockchain_type from signlog where public_key=?"; auto res = sqlite3_prepare_v2(db, statement, -1, &stmt, NULL); if ( res != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); - sqlite3_bind_text(stmt, 1, public_key.c_str(), -1, 0); + std::string hex = pkey.hex(); + sqlite3_bind_text(stmt, 1, hex.c_str(), -1, 0); while(true) { res = sqlite3_step(stmt); if (res == SQLITE_ROW) - set.push_back(std::string ((const char *) sqlite3_column_text(stmt, 0)) ); + { + std::string trx((const char *) sqlite3_column_text(stmt, 0)); + std::string time((const char *) sqlite3_column_text(stmt, 1)); + std::string chain((const char *) sqlite3_column_text(stmt, 2)); + + dev::bytes trx_(trx.length()); + auto len = keychain_app::from_hex(trx, trx_.data(), trx_.size() ); + trx_.resize(len); + + fc_light::variant v_time (time); + auto time_ = v_time.as(); + + fc_light::variant v_chain (chain); + auto chain_ = v_chain.as(); + + set.push_back(keychain_app::keyfile_format::log_record(trx_, time_, chain_)); + } else break; } if (sqlite3_finalize(stmt) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); - return set; + + auto log_rec_t = keychain_app::keyfiles_map::log_records_t(); + for (auto& s: set) + log_rec_t.insert(s); + + return log_rec_t; } -int sql_singleton::insert(std::string& key, std::string& val) +int sql_singleton::insert(const dev::Public& pkey, const keychain_app::keyfile_format::log_record& record) { sqlite3_stmt * stmt; - std::string statement = "insert into log (public_key, trx) values('"+ key + "', '"+val+"')"; + fc_light::variant vtime(record.sign_time); + auto time = vtime.as_string(); + fc_light::variant vtype(record.blockchain_type); + auto type = vtype.as_string(); + + std::string statement = "insert into signlog (public_key, trx, sign_time, blockchain_type)" + " values('"+pkey.hex()+"', '"+ + keychain_app::to_hex(record.transaction.data(), record.transaction.size())+"', '"+ + time+"', '"+type+ "')"; auto res = sqlite3_prepare_v2(db, statement.c_str(), -1, &stmt, NULL); if ( res != SQLITE_OK ) From 9832f21adcd78ad51bac8bb9c9879c73537888a5 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Sat, 2 Mar 2019 01:34:49 +0300 Subject: [PATCH 13/65] comment saving signlog to file --- .../include/keychain_lib/keyfile_singleton.hpp | 10 +++++----- keychain_lib/src/keyfile_singleton.cpp | 14 +++++++++++--- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 19911af..53579fe 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -78,7 +78,7 @@ class keyfile_singleton using value_t = keyfile_map_t::value_type; keyfile_map_t m_keydata_map; - signlog_map_t m_signlog_map; +// signlog_map_t m_signlog_map; using prim_index_type = keyfile_map_t::index::type; using second_index_type = keyfile_map_t::index::type; @@ -92,20 +92,20 @@ class keyfile_singleton using third_key_type = third_index_type::key_type; void flush_keyfile_impl(const value_t& keyfile_data) const; - void flush_logrecords_impl(const prim_key_type& key, const log_records_t& log_records) const; +// void flush_logrecords_impl(const prim_key_type& key, const log_records_t& log_records) const; void print_exception (const boost::filesystem::path& filename, fc_light::exception &er); public: static keyfile_singleton& instance(); void keydata_load(); - void signlog_load(); +// void signlog_load(); using iterator = keyfile_map_t::iterator; //primary_index using const_iterator = keyfile_map_t::const_iterator; //primary_index const log_random_access_index_type& get_logs(const dev::Public& pkey); - const log_date_index_type& get_logs_date_ordered(const dev::Public& pkey); +// const log_date_index_type& get_logs_date_ordered(const dev::Public& pkey); void add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record); const_iterator begin() const; //primary_index @@ -183,7 +183,7 @@ class keyfile_singleton bool is_exist(const prim_key_type& key) const; void flush_keyfile(const prim_key_type& key) const; void flush_keyfile(const second_key_type& key) const; - void flush_logrecords(const prim_key_type& key) const; +// void flush_logrecords(const prim_key_type& key) const; void flush_all() const; }; diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 8ca88cd..195e18a 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -82,6 +82,7 @@ void keyfile_singleton::keydata_load() }); } +/* void keyfile_singleton::signlog_load() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) @@ -128,6 +129,7 @@ void keyfile_singleton::signlog_load() FC_LIGHT_RETHROW_EXCEPTIONS(log_level::error, "Cannot parse key file \"${KEYFILE}\"", ("KEYFILE", unit.path().c_str())) }); } +*/ void keyfile_singleton::print_exception (const boost::filesystem::path& filename, fc_light::exception &er) { @@ -141,7 +143,7 @@ keyfile_singleton::keyfile_singleton() try { keydata_load(); - signlog_load(); +// signlog_load(); } FC_LIGHT_RETHROW_EXCEPTIONS(log_level::error, "Cannot create keyfiles map") } @@ -292,6 +294,7 @@ void keyfile_singleton::flush_keyfile_impl(const value_t& keyfile_data) const fout << fc_light::json::to_pretty_string(keyfile_data) << std::endl; } +/* void keyfile_singleton::flush_logrecords(const prim_key_type& key) const { auto it = m_signlog_map.find(key); @@ -299,7 +302,9 @@ void keyfile_singleton::flush_logrecords(const prim_key_type& key) const return; flush_logrecords_impl(key, it->second); } +*/ +/* void keyfile_singleton::flush_logrecords_impl(const prim_key_type& key, const log_records_t& log_records) const { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) @@ -320,6 +325,7 @@ void keyfile_singleton::flush_logrecords_impl(const prim_key_type& key, const lo FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Cannot open keyfile (${filename})", ("filename", filename)); fout << fc_light::json::to_pretty_string(logfile) << std::endl; } +*/ void keyfile_singleton::flush_all() const { @@ -340,9 +346,9 @@ void keyfile_singleton::flush_all() const FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Cannot open keyfile (${filename})", ("filename", filename)); fout << fc_light::json::to_pretty_string(keyfile_data) << std::endl; }); - std::for_each(m_signlog_map.begin(), m_signlog_map.end(), [this](const auto& val){ +/* std::for_each(m_signlog_map.begin(), m_signlog_map.end(), [this](const auto& val){ flush_logrecords(val.first); - }); + });*/ } const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) @@ -360,6 +366,7 @@ const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_lo return records.get(); } +/* const keyfile_singleton::log_date_index_type& keyfile_singleton::get_logs_date_ordered(const dev::Public& pkey) { signlog_load();//NOTE: it may be slowly, using sqlite and triggers is more preferable @@ -369,6 +376,7 @@ const keyfile_singleton::log_date_index_type& keyfile_singleton::get_logs_date_o auto& records = it->second; return records.get(); } +*/ void keyfile_singleton::add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record) { From 6d45faec8383a06c9b74c1f71219ae7fa1209d24 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Mon, 4 Mar 2019 15:44:06 +0300 Subject: [PATCH 14/65] fix get_logs --- .../keychain_lib/keychain_commands.hpp | 10 ++++++++- .../keychain_lib/keyfile_singleton.hpp | 11 ++++++---- .../include/keychain_lib/sql_singleton.hpp | 5 ++++- keychain_lib/src/keyfile_singleton.cpp | 8 ++++--- keychain_lib/src/sql_singleton.cpp | 22 ++++++++++++++----- 5 files changed, 42 insertions(+), 14 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 99d2bd4..5f5b348 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -358,7 +358,15 @@ struct keychain_command : keychain_command_base fc_light::variant json; dev::Secret private_key; auto& keyfiles = keyfile_singleton::instance(); - + +// auto logs = keyfiles.get_logs(params.public_key); +// int n = std::distance(logs.begin(), logs.end()); +// for (int i = 0 ; i < n ; i++) +// { +// auto &a = logs[i]; +// auto b = a.blockchain_type; +// } + //NOTE: using vector instead array because move semantic is implemented in the vector auto trans_len = keychain_app::from_hex(params.transaction, raw.data(), raw.size()); raw.resize(trans_len); diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 53579fe..29136fa 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -83,10 +83,10 @@ class keyfile_singleton using prim_index_type = keyfile_map_t::index::type; using second_index_type = keyfile_map_t::index::type; using third_index_type = keyfile_map_t::index::type; - using log_random_access_index_type = log_records_t::index::type; using log_date_index_type = log_records_t::index::type; using key_random_access_index_type = keyfile_map_t::index::type; - + using log_random_access_index_type = log_records_t::index::type; + using prim_key_type = keyfile_map_t::key_type; using second_key_type = second_index_type::key_type; using third_key_type = third_index_type::key_type; @@ -96,6 +96,7 @@ class keyfile_singleton void print_exception (const boost::filesystem::path& filename, fc_light::exception &er); public: + static keyfile_singleton& instance(); void keydata_load(); @@ -103,8 +104,10 @@ class keyfile_singleton using iterator = keyfile_map_t::iterator; //primary_index using const_iterator = keyfile_map_t::const_iterator; //primary_index - - const log_random_access_index_type& get_logs(const dev::Public& pkey); + + std::vector get_logs(const dev::Public& ); + +// const log_random_access_index_type& get_logs(const dev::Public& pkey); // const log_date_index_type& get_logs_date_ordered(const dev::Public& pkey); void add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record); diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 272e181..22f10bd 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -6,11 +6,14 @@ #include #include "keychain_commands.hpp" +#include "keyfile_singleton.hpp" struct sql_singleton { static sql_singleton& instance(); - const keychain_app::keyfiles_map::log_records_t select(const dev::Public& ); + std::vector select(const dev::Public& ); + +// const keychain_app::keyfiles_map::log_records_t select(const dev::Public& ); int insert(const dev::Public&, const keychain_app::keyfile_format::log_record& ); private: diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 195e18a..2ae5549 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -351,7 +351,8 @@ void keyfile_singleton::flush_all() const });*/ } -const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) +std::vector keyfile_singleton::get_logs(const dev::Public& pkey) +//const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) { /* signlog_load();//NOTE: it may be slowly, using sqlite and triggers is more preferable @@ -362,8 +363,9 @@ const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_lo return records.get(); */ auto& sql = sql_singleton::instance(); - auto records = sql.select(pkey); - return records.get(); + return sql.select(pkey); +// auto records = sql.select(pkey); +// return records.get(); } /* diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index 86bd40c..093496f 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -52,7 +52,8 @@ sql_singleton& sql_singleton::instance() return instance; } -const keychain_app::keyfiles_map::log_records_t sql_singleton::select(const dev::Public& pkey) +//const keychain_app::keyfiles_map::log_records_t sql_singleton::select(const dev::Public& pkey) +std::vector sql_singleton::select(const dev::Public& pkey) { sqlite3_stmt * stmt; std::vector set; @@ -92,11 +93,22 @@ const keychain_app::keyfiles_map::log_records_t sql_singleton::select(const dev: if (sqlite3_finalize(stmt) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); - auto log_rec_t = keychain_app::keyfiles_map::log_records_t(); - for (auto& s: set) - log_rec_t.insert(s); + return set; +// auto log_rec_t = keychain_app::keyfiles_map::log_records_t(); +// for (auto& s: set) +// log_rec_t.insert(s); - return log_rec_t; +// return log_rec_t; + +// keychain_app::keyfiles_map::signlog_map_t m_signlog_map; +// auto res1 = m_signlog_map.insert(keychain_app::keyfiles_map::signlog_map_t::value_type(pkey, +// keychain_app::keyfiles_map::log_records_t() )); +// auto it = m_signlog_map.begin(); +// +// auto& logmap = it->second; +//// std::copy(set.begin(), set.end(), std::inserter(logmap, logmap.begin())); +// +// return logmap.get(); } int sql_singleton::insert(const dev::Public& pkey, const keychain_app::keyfile_format::log_record& record) From 52aceaa6c9ffeb04ba095ce8e4aa70bbb1561042 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Tue, 5 Mar 2019 11:41:11 +0300 Subject: [PATCH 15/65] keyfile_singleton::get_logs update --- .../keychain_lib/keychain_commands.hpp | 16 ++++--- .../keychain_lib/keyfile_singleton.hpp | 6 +-- .../include/keychain_lib/sql_singleton.hpp | 6 +-- keychain_lib/src/keyfile_singleton.cpp | 27 ++++++------ keychain_lib/src/sql_singleton.cpp | 42 +++++-------------- 5 files changed, 35 insertions(+), 62 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 5f5b348..065c858 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -358,15 +358,13 @@ struct keychain_command : keychain_command_base fc_light::variant json; dev::Secret private_key; auto& keyfiles = keyfile_singleton::instance(); - -// auto logs = keyfiles.get_logs(params.public_key); -// int n = std::distance(logs.begin(), logs.end()); -// for (int i = 0 ; i < n ; i++) -// { -// auto &a = logs[i]; -// auto b = a.blockchain_type; -// } - + /* auto &logs = keyfiles.get_logs(params.public_key); + int n = std::distance(logs.begin(), logs.end()); + for (int i = 0 ; i < n ; i++) + { + auto &a = logs[i]; + auto b = a.blockchain_type; + }*/ //NOTE: using vector instead array because move semantic is implemented in the vector auto trans_len = keychain_app::from_hex(params.transaction, raw.data(), raw.size()); raw.resize(trans_len); diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 29136fa..495fb88 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -78,7 +78,7 @@ class keyfile_singleton using value_t = keyfile_map_t::value_type; keyfile_map_t m_keydata_map; -// signlog_map_t m_signlog_map; + signlog_map_t m_signlog_map; using prim_index_type = keyfile_map_t::index::type; using second_index_type = keyfile_map_t::index::type; @@ -105,9 +105,7 @@ class keyfile_singleton using iterator = keyfile_map_t::iterator; //primary_index using const_iterator = keyfile_map_t::const_iterator; //primary_index - std::vector get_logs(const dev::Public& ); - -// const log_random_access_index_type& get_logs(const dev::Public& pkey); + const log_random_access_index_type& get_logs(const dev::Public& pkey); // const log_date_index_type& get_logs_date_ordered(const dev::Public& pkey); void add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record); diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 22f10bd..0d469c3 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -11,10 +11,8 @@ struct sql_singleton { static sql_singleton& instance(); - std::vector select(const dev::Public& ); - -// const keychain_app::keyfiles_map::log_records_t select(const dev::Public& ); - int insert(const dev::Public&, const keychain_app::keyfile_format::log_record& ); + const std::vector select_log(const dev::Public& ); + int insert_log(const dev::Public&, const keychain_app::keyfile_format::log_record& ); private: sql_singleton(); diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 2ae5549..f3ae364 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -351,21 +351,20 @@ void keyfile_singleton::flush_all() const });*/ } -std::vector keyfile_singleton::get_logs(const dev::Public& pkey) -//const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) +const keyfile_singleton::log_random_access_index_type& keyfile_singleton::get_logs(const dev::Public& pkey) { -/* - signlog_load();//NOTE: it may be slowly, using sqlite and triggers is more preferable - auto it = m_signlog_map.find(pkey); - if (it == m_signlog_map.end()) - FC_LIGHT_THROW_EXCEPTION(fc_light::file_not_found_exception, "Public_key: ${PKEY}", ("PKEY", pkey)); - auto& records = it->second; - return records.get(); -*/ auto& sql = sql_singleton::instance(); - return sql.select(pkey); -// auto records = sql.select(pkey); -// return records.get(); + auto records = sql.select_log(pkey); + + if (records.size() == 0) + FC_LIGHT_THROW_EXCEPTION(fc_light::file_not_found_exception, "Public_key: ${PKEY}", ("PKEY", pkey)); + + m_signlog_map.clear(); + m_signlog_map.insert(signlog_map_t::value_type(pkey, log_records_t())); + auto it = m_signlog_map.begin(); + auto& logmap = it->second; + std::copy(records.begin(), records.end(), std::inserter(logmap, logmap.begin())); + return logmap.get(); } /* @@ -383,7 +382,7 @@ const keyfile_singleton::log_date_index_type& keyfile_singleton::get_logs_date_o void keyfile_singleton::add_log_record(const dev::Public& pkey, const keyfile_format::log_record& record) { auto& sql = sql_singleton::instance(); - sql.insert(pkey, record); + sql.insert_log(pkey, record); /* auto it = m_signlog_map.find(pkey); if (it == m_signlog_map.end()) diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index 093496f..8d5f1d8 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -52,11 +52,10 @@ sql_singleton& sql_singleton::instance() return instance; } -//const keychain_app::keyfiles_map::log_records_t sql_singleton::select(const dev::Public& pkey) -std::vector sql_singleton::select(const dev::Public& pkey) +const std::vector sql_singleton::select_log(const dev::Public& pkey) { sqlite3_stmt * stmt; - std::vector set; + std::vector records; const char * statement = "select trx, sign_time, blockchain_type from signlog where public_key=?"; auto res = sqlite3_prepare_v2(db, statement, -1, &stmt, NULL); @@ -75,17 +74,13 @@ std::vector sql_singleton::select(cons std::string time((const char *) sqlite3_column_text(stmt, 1)); std::string chain((const char *) sqlite3_column_text(stmt, 2)); - dev::bytes trx_(trx.length()); - auto len = keychain_app::from_hex(trx, trx_.data(), trx_.size() ); - trx_.resize(len); - - fc_light::variant v_time (time); - auto time_ = v_time.as(); - - fc_light::variant v_chain (chain); - auto chain_ = v_chain.as(); - - set.push_back(keychain_app::keyfile_format::log_record(trx_, time_, chain_)); + keychain_app::keyfile_format::log_record rec; + rec.transaction.resize(trx.length()); + auto len = keychain_app::from_hex(trx, rec.transaction.data(), rec.transaction.size() ); + rec.transaction.resize(len); + rec.sign_time = fc_light::variant(time).as(); + rec.blockchain_type = fc_light::variant(chain).as(); + records.push_back(rec); } else break; } @@ -93,25 +88,10 @@ std::vector sql_singleton::select(cons if (sqlite3_finalize(stmt) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); - return set; -// auto log_rec_t = keychain_app::keyfiles_map::log_records_t(); -// for (auto& s: set) -// log_rec_t.insert(s); - -// return log_rec_t; - -// keychain_app::keyfiles_map::signlog_map_t m_signlog_map; -// auto res1 = m_signlog_map.insert(keychain_app::keyfiles_map::signlog_map_t::value_type(pkey, -// keychain_app::keyfiles_map::log_records_t() )); -// auto it = m_signlog_map.begin(); -// -// auto& logmap = it->second; -//// std::copy(set.begin(), set.end(), std::inserter(logmap, logmap.begin())); -// -// return logmap.get(); + return records; } -int sql_singleton::insert(const dev::Public& pkey, const keychain_app::keyfile_format::log_record& record) +int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfile_format::log_record& record) { sqlite3_stmt * stmt; fc_light::variant vtime(record.sign_time); From 461ca8f11fa17eebd1405f59cd335d63e2c3f2b8 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Wed, 6 Mar 2019 22:41:16 +0300 Subject: [PATCH 16/65] add restore, seed --- .../keychain_lib/keychain_commands.hpp | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 065c858..2b98ae4 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -816,6 +816,46 @@ struct keychain_command: keychain_command_base } }; +template<> +struct keychain_command: keychain_command_base +{ + keychain_command(): keychain_command_base(command_te::seed){} + virtual ~keychain_command(){} + struct params {std::string entropy;}; + using params_t = params; + virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override + { + auto param = params_variant.as(); + std::vector entropy; + entropy.resize(param.entropy.length()); + auto res = from_hex(param.entropy, entropy.data(), entropy.size()); + entropy.resize(res); + //TODO: need to impl + std::string seed_phrase = "witch collapse practice feed shame open despair creek road again ice least"; + json_response response(seed_phrase, id); + return fc_light::json::to_string(fc_light::variant(response)); + } +}; + + +template<> +struct keychain_command: keychain_command_base +{ + keychain_command(): keychain_command_base(command_te::restore){} + virtual ~keychain_command(){} + struct params {std::string seed;}; + using params_t = params; + virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override + { + auto param = params_variant.as(); + //TODO: need to impl + std::string private_key = "5fda7b741910b05738c5e0ca8961cf7a9c2f3afe8dfcae8d57df5f01690f2a02"; + json_response response(private_key, id); + return fc_light::json::to_string(fc_light::variant(response)); + } +}; + + template<> struct keychain_command: keychain_command_base { @@ -922,6 +962,8 @@ FC_LIGHT_REFLECT(keychain_app::keychain_command::params_t, (keyname)) FC_LIGHT_REFLECT(keychain_app::keychain_command::params_t, (seconds)) FC_LIGHT_REFLECT(keychain_app::keychain_command::params_t, (public_key)(unlock_time)) +FC_LIGHT_REFLECT(keychain_app::keychain_command::params_t, (entropy)) +FC_LIGHT_REFLECT(keychain_app::keychain_command::params_t, (seed)) FC_LIGHT_REFLECT(keychain_app::keychain_command_common, (command)(id)(params)) FC_LIGHT_REFLECT(keychain_app::json_response, (id)(result)) FC_LIGHT_REFLECT(keychain_app::json_error::error_t, (code)(name)(message)(trace)) From b43910af9890511ef62cd68486a1a5720872d635 Mon Sep 17 00:00:00 2001 From: Avvrik <34011337+Avvrik@users.noreply.github.com> Date: Thu, 7 Mar 2019 10:51:29 +0300 Subject: [PATCH 17/65] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 5faa30f..9f411a5 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@              [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=A%20good,%20solid%20app%20to%20keep%20your%20keys%20safe.&url=https://keychain.array.io/&via=ProjectArray&hashtags=cybersecurity,private,cryptography,blockchain,app) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-orange.svg)](https://github.com/arrayio/array-io-keychain#contributing-to-the-project) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/arrayio/array-io-keychain/blob/master/LICENSE.md) [![npm version](https://badge.fury.io/js/web3override.svg)](https://badge.fury.io/js/web3override) - +

» Download for macOS «

» Documentation «

@@ -34,7 +34,7 @@ ## Installation -Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.18/KeyChain.Installer.v18.zip). Windows and Linux installers are coming soon. +Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.20/KeyChain.Installer.zip). Windows and Linux installers are coming soon. *Try out KeyChain on the [demo page](https://arrayio.github.io/array-io-keychain/demo/).* From fbaf8f2203efc5ca0da3b6b73ae9c1122f26d8cd Mon Sep 17 00:00:00 2001 From: dtaipov Date: Thu, 7 Mar 2019 15:09:13 +0300 Subject: [PATCH 18/65] demo docs. sign_hex command renamed to sign_trx --- docs/demo/index.html | 26 +++++++++++++------------- docs/index.html | 24 ++++++++++++------------ 2 files changed, 25 insertions(+), 25 deletions(-) diff --git a/docs/demo/index.html b/docs/demo/index.html index afc6747..06204ae 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -235,7 +235,7 @@ - + @@ -258,8 +258,8 @@ -
-
Sign hex
+
+
Sign transaction
@@ -269,13 +269,13 @@
- - + +
- - + +
@@ -305,7 +305,7 @@ - + @@ -402,21 +402,21 @@ window.onhashchange = onHash; window.onload = function () { - document.getElementById('checkbox_SIGN_HEX').addEventListener('click', function(e) { - document.getElementById('unlock_time_SIGN_HEX').readOnly = !e.target.checked; + document.getElementById('checkbox_SIGN_TRX').addEventListener('click', function(e) { + document.getElementById('unlock_time_SIGN_TRX').readOnly = !e.target.checked; const request = getRequest(); if (request) { if (!e.target.checked) { delete request.params['unlock_time']; } else { - request.params['unlock_time'] = document.getElementById('unlock_time_SIGN_HEX').value; + request.params['unlock_time'] = document.getElementById('unlock_time_SIGN_TRX').value; } document.getElementById('request').value = JSON.stringify(request, undefined, 2) } }); document.getElementById('btn_RUN_REQUEST').addEventListener('click', function() { + event.preventDefault(); runRequest(); - return null; }); const inputs = document.getElementsByClassName('param_field'); for (let i=0; i' + data.result.substr(-8, 8); document.getElementById('address').innerHTML = '0x' + ethereumjs.Util.publicToAddress('0x' + data.result).toString('hex'); } diff --git a/docs/index.html b/docs/index.html index ab99f0d..03bcd4f 100644 --- a/docs/index.html +++ b/docs/index.html @@ -235,7 +235,7 @@ - + @@ -258,8 +258,8 @@
-
-
Sign hex
+
+
Sign transaction
@@ -269,13 +269,13 @@
- - + +
- - + +
@@ -305,7 +305,7 @@ - + @@ -402,14 +402,14 @@ window.onhashchange = onHash; window.onload = function () { - document.getElementById('checkbox_SIGN_HEX').addEventListener('click', function(e) { - document.getElementById('unlock_time_SIGN_HEX').readOnly = !e.target.checked; + document.getElementById('checkbox_SIGN_TRX').addEventListener('click', function(e) { + document.getElementById('unlock_time_SIGN_TRX').readOnly = !e.target.checked; const request = getRequest(); if (request) { if (!e.target.checked) { delete request.params['unlock_time']; } else { - request.params['unlock_time'] = document.getElementById('unlock_time_SIGN_HEX').value; + request.params['unlock_time'] = document.getElementById('unlock_time_SIGN_TRX').value; } document.getElementById('request').value = JSON.stringify(request, undefined, 2) } @@ -467,7 +467,7 @@ if (request.command === 'select_key' && data.result) { document.getElementById('public_key_UNLOCK').value = data.result; document.getElementById('public_key_SIGN_HASH').value = data.result; - document.getElementById('public_key_SIGN_HEX').value = data.result; + document.getElementById('public_key_SIGN_TRX').value = data.result; document.getElementById('selectedKey').innerHTML = '0x' + data.result.substr(0, 35) + '<...>' + data.result.substr(-8, 8); document.getElementById('address').innerHTML = '0x' + ethereumjs.Util.publicToAddress('0x' + data.result).toString('hex'); } From 5ab3b170fa7a0013f37c6869bff154e4a274ea7f Mon Sep 17 00:00:00 2001 From: Avvrik <34011337+Avvrik@users.noreply.github.com> Date: Thu, 7 Mar 2019 15:53:27 +0300 Subject: [PATCH 19/65] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 9f411a5..17265ac 100644 --- a/README.md +++ b/README.md @@ -48,7 +48,7 @@ You can find a comprehensive installation guide for [macOS](https://github.com/a ## Getting started -After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.18/KeyChain.Installer.v18.zip), you can start using it with web3. Just follow these simple steps. +After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.20/KeyChain.Installer.zip), you can start using it with web3. Just follow these simple steps. NB: If you launch KeyChain for the first time, you need to get a public key with the "select_key" command. You can save the public key to local storage. Then you will not need to use "select_key" command again. From 49792460db7214a61d5098ba55ae390c6fe66fcb Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Thu, 7 Mar 2019 22:59:54 +0300 Subject: [PATCH 20/65] add gui_mod::entropy --- keychain_cmd_app/cmd_parser.cpp | 19 +++++++++++++++++++ keychain_cmd_app/gui_mod.cpp | 6 ++++++ keychain_cmd_app/gui_mod.hpp | 1 + keychain_cmd_app/main.cpp | 2 ++ .../include/keychain_lib/keychain.hpp | 1 + .../keychain_lib/keychain_commands.hpp | 3 ++- keychain_lib/src/keychain.cpp | 1 + keychain_lib/src/keyfile_singleton.cpp | 2 +- 8 files changed, 33 insertions(+), 2 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 7ca6124..5c875c2 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -113,6 +113,25 @@ int cmd_parser::run(int argc, const char* const argv[]) auto& keychain_ref = keychain::instance(); sec_mod->connect(keychain_ref); gui_mod->connect(keychain_ref); + + auto& keyfiles = keyfile_singleton::instance(); + auto it = keyfiles.begin(); + if ( it==keyfiles.end() ) + { + auto user_entropy = keychain_ref.entropy(); + std::string keyname = "master_key"; + std::string pass = "blank"; + keyfiles.create(std::bind(create_new_keyfile, + keyname, keyname, true, keyfile_format::cipher_etype::aes256, + keyfile_format::curve_etype::secp256k1, + [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }) + ); + } + keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); pipeline_parser pipe_line_parser_(std::move(f), fileno(stdin), fileno(stdout)); return pipe_line_parser_.run(); diff --git a/keychain_cmd_app/gui_mod.cpp b/keychain_cmd_app/gui_mod.cpp index 1ebd9f7..7c845ec 100644 --- a/keychain_cmd_app/gui_mod.cpp +++ b/keychain_cmd_app/gui_mod.cpp @@ -20,3 +20,9 @@ dev::Public gui_mod_dummy::select_key() const return dev::Public(); return it->keyinfo.public_key; } + +dev::bytes gui_mod_dummy::entropy() const +{ + dev::bytes value; + return value; +} \ No newline at end of file diff --git a/keychain_cmd_app/gui_mod.hpp b/keychain_cmd_app/gui_mod.hpp index ee8ef7d..dae4486 100644 --- a/keychain_cmd_app/gui_mod.hpp +++ b/keychain_cmd_app/gui_mod.hpp @@ -15,6 +15,7 @@ class gui_mod_dummy: public gui_mod_base gui_mod_dummy(); virtual ~gui_mod_dummy(); virtual dev::Public select_key() const override; + virtual dev::bytes entropy() const override; }; } diff --git a/keychain_cmd_app/main.cpp b/keychain_cmd_app/main.cpp index ae3dc41..8f8ee0a 100644 --- a/keychain_cmd_app/main.cpp +++ b/keychain_cmd_app/main.cpp @@ -24,6 +24,8 @@ int main(int argc, char* argv[]) BOOST_LOG_SEV(log.lg, info) << "OS: Linux"; #elif defined(_MSC_VER) BOOST_LOG_SEV(log.lg, info) << "OS: Win"; +#elif defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) + BOOST_LOG_SEV(log.lg, info) << "OS: Mac"; #else BOOST_LOG_SEV(log.lg, info) << "OS: unknown"; #endif diff --git a/keychain_lib/include/keychain_lib/keychain.hpp b/keychain_lib/include/keychain_lib/keychain.hpp index dffa2fd..cbb4570 100644 --- a/keychain_lib/include/keychain_lib/keychain.hpp +++ b/keychain_lib/include/keychain_lib/keychain.hpp @@ -39,6 +39,7 @@ class gui_mod_base virtual ~gui_mod_base(){} virtual dev::Public select_key() const = 0; + virtual dev::bytes entropy() const = 0; virtual void connect(keychain_base& keychain_) const; }; diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 2b98ae4..3f8c920 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -161,7 +161,8 @@ class keychain_base virtual std::string operator()(const fc_light::variant& command) = 0; boost::signals2::signal run_secmod_cmd; boost::signals2::signal select_key; - + boost::signals2::signal entropy; + dev::Secret get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); protected: diff --git a/keychain_lib/src/keychain.cpp b/keychain_lib/src/keychain.cpp index 353531e..e5b5f9a 100644 --- a/keychain_lib/src/keychain.cpp +++ b/keychain_lib/src/keychain.cpp @@ -141,4 +141,5 @@ void keychain_app::secure_dlg_mod_base::connect(keychain_app::keychain_base &key void keychain_app::gui_mod_base::connect(keychain_app::keychain_base &keychain_) const { keychain_.select_key.connect(std::bind(&gui_mod_base::select_key, this)); + keychain_.entropy.connect(std::bind(&gui_mod_base::entropy, this)); } diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index f3ae364..eed6765 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -204,7 +204,7 @@ const keyfile_format::keyfile_t& keyfile_singleton::operator[](size_t index) if(stop == true) FC_LIGHT_THROW_EXCEPTION(fc_light::out_of_range_exception, "index = ${ind_}", ("ind_", index)); keydata_load(); - bool stop = false; + bool stop = true; } return ra_ind[index]; } while (true); From 8dd6f6d7ff0426b7aded3bb1e818c34fd1143682 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Wed, 13 Mar 2019 00:20:23 +0300 Subject: [PATCH 21/65] add cryptopp --- keychain_cmd_app/cmd_parser.cpp | 21 +- keychain_lib/CMakeLists.txt | 2 +- .../keychain_lib/keyfile_singleton.hpp | 1 + keychain_lib/src/keyfile_singleton.cpp | 22 + libraries/mSIGNA/hdkeys.cpp | 360 ++++++++++++++ libraries/mSIGNA/include/BigInt.h | 189 ++++++++ libraries/mSIGNA/include/hash.h | 118 +++++ libraries/mSIGNA/include/hdkeys.h | 142 ++++++ libraries/mSIGNA/include/scrypt.h | 35 ++ libraries/mSIGNA/include/secp256k1_openssl.h | 102 ++++ libraries/mSIGNA/include/typedefs.h | 32 ++ libraries/mSIGNA/include/uchar_vector.h | 262 ++++++++++ libraries/mSIGNA/scrypt.cpp | 323 ++++++++++++ libraries/mSIGNA/secp256k1_openssl.cpp | 458 ++++++++++++++++++ 14 files changed, 2056 insertions(+), 11 deletions(-) create mode 100644 libraries/mSIGNA/hdkeys.cpp create mode 100644 libraries/mSIGNA/include/BigInt.h create mode 100644 libraries/mSIGNA/include/hash.h create mode 100644 libraries/mSIGNA/include/hdkeys.h create mode 100644 libraries/mSIGNA/include/scrypt.h create mode 100644 libraries/mSIGNA/include/secp256k1_openssl.h create mode 100644 libraries/mSIGNA/include/typedefs.h create mode 100644 libraries/mSIGNA/include/uchar_vector.h create mode 100644 libraries/mSIGNA/scrypt.cpp create mode 100644 libraries/mSIGNA/secp256k1_openssl.cpp diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 5c875c2..9d3ca00 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -118,19 +118,20 @@ int cmd_parser::run(int argc, const char* const argv[]) auto it = keyfiles.begin(); if ( it==keyfiles.end() ) { - auto user_entropy = keychain_ref.entropy(); + auto user_entropy = std::move(*(keychain_ref.entropy())); + auto seed_hex = std::move(keyfiles.seed(user_entropy)); std::string keyname = "master_key"; std::string pass = "blank"; keyfiles.create(std::bind(create_new_keyfile, - keyname, keyname, true, keyfile_format::cipher_etype::aes256, - keyfile_format::curve_etype::secp256k1, - [&pass](const std::string& keyname)->byte_seq_t{ - byte_seq_t res; - std::copy(pass.begin(), pass.end(), std::back_inserter(res)); - return res; - }) - ); - } + keyname, keyname, true, keyfile_format::cipher_etype::aes256, + keyfile_format::curve_etype::secp256k1, + [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }) +); + } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); pipeline_parser pipe_line_parser_(std::move(f), fileno(stdin), fileno(stdout)); diff --git a/keychain_lib/CMakeLists.txt b/keychain_lib/CMakeLists.txt index c0de618..d95111f 100644 --- a/keychain_lib/CMakeLists.txt +++ b/keychain_lib/CMakeLists.txt @@ -67,6 +67,6 @@ file(GLOB KEYCHAIN_LIB_INCLUDE "./include/keychain_lib/*.hpp" ) list(APPEND KEYCHAIN_LIB_SOURCES "${CMAKE_CURRENT_BINARY_DIR}/git_revision.cpp") add_library(keychain_common STATIC ${KEYCHAIN_LIB_SOURCES} ${KEYCHAIN_LIB_INCLUDE}) -target_link_libraries(keychain_common kaitai_struct_cpp_stl_runtime sqlite3) +target_link_libraries(keychain_common kaitai_struct_cpp_stl_runtime sqlite3 cryptopp) diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 495fb88..5c4dba2 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -186,6 +186,7 @@ class keyfile_singleton void flush_keyfile(const second_key_type& key) const; // void flush_logrecords(const prim_key_type& key) const; void flush_all() const; + dev::bytes seed(dev::bytes& ); }; using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index eed6765..328daba 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -4,6 +4,8 @@ #include "keychain_commands.hpp" #include "keyfile_singleton.hpp" +#include +#include using namespace keychain_app; @@ -454,6 +456,26 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( return keyfile; } +dev::bytes keyfile_singleton::seed(dev::bytes& user_entropy) +{ + using namespace CryptoPP; + SecByteBlock key(32); + std::string k; + + OS_GenerateRandomBlock(false, key, k.size()); + + HexEncoder hex(new StringSink(k)); + hex.Put(key, key.size()); + hex.MessageEnd(); + + dev::bytes seed(32); + auto res = from_hex(k, seed.data(), seed.size()); + seed.resize(res); + + return seed; +} + + bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) { try { diff --git a/libraries/mSIGNA/hdkeys.cpp b/libraries/mSIGNA/hdkeys.cpp new file mode 100644 index 0000000..d243b74 --- /dev/null +++ b/libraries/mSIGNA/hdkeys.cpp @@ -0,0 +1,360 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// hdkeys.cpp +// +// Copyright (c) 2013-2014 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#include "hdkeys.h" + +#include "hash.h" +#include "secp256k1_openssl.h" +#include "BigInt.h" + +#include "uchar_vector.h" + +#include +#include + +#include "typedefs.h" + +// cstdlib - for rand() +// #include + +using namespace Coin; +using namespace CoinCrypto; + +const uchar_vector CURVE_ORDER_BYTES("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); +const BigInt CURVE_ORDER(CURVE_ORDER_BYTES); + +const uint32_t BITCOIN_HD_PRIVATE_VERSION = 0x0488ade4; +const uint32_t BITCOIN_HD_PUBLIC_VERSION = 0x0488b21e; + +bytes_t HDSeed::getExtendedKey(bool bPrivate) const +{ + HDKeychain keychain(master_key_, master_chain_code_); + if (!bPrivate) { keychain = keychain.getPublic(); } + + return keychain.extkey(); +} + +HDKeychain::HDKeychain(const bytes_t& key, const bytes_t& chain_code, uint32_t child_num, uint32_t parent_fp, uint32_t depth) + : depth_(depth), parent_fp_(parent_fp), child_num_(child_num), chain_code_(chain_code), key_(key) +{ + if (chain_code_.size() != 32) { + throw std::runtime_error("Invalid chain code."); + } + + if (key_.size() == 32) { + // key is private + BigInt n(key_); + if (n >= CURVE_ORDER || n.isZero()) { + throw std::runtime_error("Invalid key."); + } + + uchar_vector privkey; + privkey.push_back(0x00); + privkey += key_; + key_ = privkey; + } + else if (key_.size() == 33) { + // key is public + try { + secp256k1_point K(key_); + } + catch (...) { + throw std::runtime_error("Invalid key."); + } + } + else { + throw std::runtime_error("Invalid key."); + } + + version_ = isPrivate() ? priv_version_ : pub_version_; + updatePubkey(); + + valid_ = true; +} + +HDKeychain::HDKeychain(const bytes_t& extkey) +{ + if (extkey.size() != 78) { + throw std::runtime_error("Invalid extended key length."); + } + + version_ = ((uint32_t)extkey[0] << 24) | ((uint32_t)extkey[1] << 16) | ((uint32_t)extkey[2] << 8) | (uint32_t)extkey[3]; + depth_ = extkey[4]; + parent_fp_ = ((uint32_t)extkey[5] << 24) | ((uint32_t)extkey[6] << 16) | ((uint32_t)extkey[7] << 8) | (uint32_t)extkey[8]; + child_num_ = ((uint32_t)extkey[9] << 24) | ((uint32_t)extkey[10] << 16) | ((uint32_t)extkey[11] << 8) | (uint32_t)extkey[12]; + chain_code_.assign(extkey.begin() + 13, extkey.begin() + 45); + key_.assign(extkey.begin() + 45, extkey.begin() + 78); + + updatePubkey(); + + valid_ = true; +} + +HDKeychain::HDKeychain(const HDKeychain& source) +{ + valid_ = source.valid_; + if (!valid_) return; + + version_ = source.version_; + depth_ = source.depth_; + parent_fp_ = source.parent_fp_; + child_num_ = source.child_num_; + chain_code_ = source.chain_code_; + key_ = source.key_; + updatePubkey(); +} + +HDKeychain& HDKeychain::operator=(const HDKeychain& rhs) +{ + valid_ = rhs.valid_; + if (valid_) { + version_ = rhs.version_; + depth_ = rhs.depth_; + parent_fp_ = rhs.parent_fp_; + child_num_ = rhs.child_num_; + chain_code_ = rhs.chain_code_; + key_ = rhs.key_; + updatePubkey(); + } + return *this; +} + +bool HDKeychain::operator==(const HDKeychain& rhs) const +{ + return (valid_ && rhs.valid_ && + version_ == rhs.version_ && + depth_ == rhs.depth_ && + parent_fp_ == rhs.parent_fp_ && + child_num_ == rhs.child_num_ && + chain_code_ == rhs.chain_code_ && + key_ == rhs.key_); +} + +bool HDKeychain::operator!=(const HDKeychain& rhs) const +{ + return !(*this == rhs); +} + +bytes_t HDKeychain::extkey() const +{ + uchar_vector extkey; + + extkey.push_back((uint32_t)version_ >> 24); + extkey.push_back(((uint32_t)version_ >> 16) & 0xff); + extkey.push_back(((uint32_t)version_ >> 8) & 0xff); + extkey.push_back((uint32_t)version_ & 0xff); + + extkey.push_back(depth_); + + extkey.push_back((uint32_t)parent_fp_ >> 24); + extkey.push_back(((uint32_t)parent_fp_ >> 16) & 0xff); + extkey.push_back(((uint32_t)parent_fp_ >> 8) & 0xff); + extkey.push_back((uint32_t)parent_fp_ & 0xff); + + extkey.push_back((uint32_t)child_num_ >> 24); + extkey.push_back(((uint32_t)child_num_ >> 16) & 0xff); + extkey.push_back(((uint32_t)child_num_ >> 8) & 0xff); + extkey.push_back((uint32_t)child_num_ & 0xff); + + extkey += chain_code_; + extkey += key_; + + return extkey; +} + +bytes_t HDKeychain::privkey() const +{ + if (isPrivate()) { + return bytes_t(key_.begin() + 1, key_.end()); + } + else { + return bytes_t(); + } +} + +bytes_t HDKeychain::uncompressed_pubkey() const +{ + secp256k1_key key; + key.setPubKey(pubkey_); + return key.getPubKey(false); +} + +bytes_t HDKeychain::hash() const +{ + return ripemd160(sha256(pubkey_)); +} + +bytes_t HDKeychain::full_hash() const +{ + uchar_vector_secure data(pubkey_); + data += chain_code_; + return ripemd160(sha256(data)); +} + +uint32_t HDKeychain::fp() const +{ + bytes_t hash = this->hash(); + return (uint32_t)hash[0] << 24 | (uint32_t)hash[1] << 16 | (uint32_t)hash[2] << 8 | (uint32_t)hash[3]; +} + +HDKeychain HDKeychain::getPublic() const +{ + if (!valid_) throw InvalidHDKeychainException(); + + HDKeychain pub; + pub.valid_ = valid_; + pub.version_ = pub_version_; + pub.depth_ = depth_; + pub.parent_fp_ = parent_fp_; + pub.child_num_ = child_num_; + pub.chain_code_ = chain_code_; + pub.key_ = pub.pubkey_ = pubkey_; + return pub; +} + +HDKeychain HDKeychain::getChild(uint32_t i) const +{ + if (!valid_) throw InvalidHDKeychainException(); + + bool priv_derivation = 0x80000000 & i; + if (!isPrivate() && priv_derivation) { + throw std::runtime_error("Cannot do private key derivation on public key."); + } + + HDKeychain child; + child.valid_ = false; + + uchar_vector data; + data += priv_derivation ? key_ : pubkey_; + data.push_back(i >> 24); + data.push_back((i >> 16) & 0xff); + data.push_back((i >> 8) & 0xff); + data.push_back(i & 0xff); + + bytes_t digest = hmac_sha512(chain_code_, data); + bytes_t left32(digest.begin(), digest.begin() + 32); + BigInt Il(left32); + if (Il >= CURVE_ORDER) throw InvalidHDKeychainException(); + + // The following line is used to test behavior for invalid indices + // if (rand() % 100 < 10) return child; + + if (isPrivate()) { + BigInt k(key_); + k += Il; + k %= CURVE_ORDER; + if (k.isZero()) throw InvalidHDKeychainException(); + + bytes_t child_key = k.getBytes(); + // pad with 0's to make it 33 bytes + uchar_vector padded_key(33 - child_key.size(), 0); + padded_key += child_key; + child.key_ = padded_key; + child.updatePubkey(); + } + else { + secp256k1_point K; + K.bytes(pubkey_); + K.generator_mul(left32); + if (K.is_at_infinity()) throw InvalidHDKeychainException(); + + child.key_ = child.pubkey_ = K.bytes(); + } + + child.version_ = version_; + child.depth_ = depth_ + 1; + child.parent_fp_ = fp(); + child.child_num_ = i; + child.chain_code_.assign(digest.begin() + 32, digest.end()); + + child.valid_ = true; + return child; +} + +HDKeychain HDKeychain::getChild(const std::string& path) const +{ + if (path.empty()) throw InvalidHDKeychainPathException(); + + std::vector path_vector; + + size_t i = 0; + uint64_t n = 0; + while (i < path.size()) + { + char c = path[i]; + if (c >= '0' && c <= '9') + { + n *= 10; + n += (uint32_t)(c - '0'); + if (n >= 0x80000000) throw InvalidHDKeychainPathException(); + i++; + if (i >= path.size()) { path_vector.push_back((uint32_t)n); } + } + else if (c == '\'') + { + if (i + 1 < path.size()) + { + if ((i + 2 >= path.size()) || (path[i + 1] != '/') || (path[i + 2] < '0') || (path[i + 2] > '9')) + throw InvalidHDKeychainPathException(); + } + n |= 0x80000000; + path_vector.push_back((uint32_t)n); + n = 0; + i += 2; + } + else if (c == '/') + { + if (i + 1 >= path.size() || path[i + 1] < '0' || path[i + 1] > '9') + throw InvalidHDKeychainPathException(); + path_vector.push_back((uint32_t)n); + n = 0; + i++; + } + else + { + throw InvalidHDKeychainPathException(); + } + } + + HDKeychain child(*this); + for (auto n: path_vector) + { + child = child.getChild(n); + } + return child; +} + +std::string HDKeychain::toString() const +{ + std::stringstream ss; + ss << "version: " << std::hex << version_ << std::endl + << "depth: " << depth() << std::endl + << "parent_fp: " << parent_fp_ << std::endl + << "child_num: " << child_num_ << std::endl + << "chain_code: " << uchar_vector(chain_code_).getHex() << std::endl + << "key: " << uchar_vector(key_).getHex() << std::endl + << "hash: " << uchar_vector(this->hash()).getHex() << std::endl; + return ss.str(); +} + +void HDKeychain::updatePubkey() { + if (isPrivate()) { + secp256k1_key curvekey; + curvekey.setPrivKey(bytes_t(key_.begin() + 1, key_.end())); + pubkey_ = curvekey.getPubKey(); + } + else { + pubkey_ = key_; + } +} + +uint32_t HDKeychain::priv_version_ = BITCOIN_HD_PRIVATE_VERSION; +uint32_t HDKeychain::pub_version_ = BITCOIN_HD_PUBLIC_VERSION; diff --git a/libraries/mSIGNA/include/BigInt.h b/libraries/mSIGNA/include/BigInt.h new file mode 100644 index 0000000..2c061cf --- /dev/null +++ b/libraries/mSIGNA/include/BigInt.h @@ -0,0 +1,189 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// BigInt.h +// +// Copyright (c) 2011 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#ifndef BIGINT_H_INCLUDED +#define BIGINT_H_INCLUDED + +#include +#include +#include +#include +#include +#include +#include + +class BigInt +{ +protected: + BIGNUM* bn; + BN_CTX* ctx; + bool autoclear; + + void allocate() + { + this->autoclear = false; + if (!(this->bn = BN_new())) throw std::runtime_error("BIGNUM allocation error."); + if (!(this->ctx = BN_CTX_new())) { BN_free(this->bn); throw std::runtime_error("BIGNUM allocation error."); } + } + +public: + // Allocation & Assignment + BigInt() { this->allocate(); } + BigInt(const BigInt& bigint) + { + if (!(this->bn = BN_dup(bigint.bn))) throw std::runtime_error("BIGNUM allocation error."); + if (!(this->ctx = BN_CTX_new())) { BN_free(this->bn); throw std::runtime_error("BIGNUM allocation error."); } + } + BigInt(BN_ULONG num) + { + this->allocate(); + this->setWord(num); + } + BigInt(const std::vector& bytes, bool bigEndian = false) + { + this->allocate(); + this->setBytes(bytes, bigEndian); + } + BigInt(const std::string& inBase, unsigned int base = 16, const char* alphabet = "0123456789abcdef") + { + this->allocate(); + this->setInBase(inBase, base, alphabet); + } + + ~BigInt() + { + if (this->bn) { + if (this->autoclear) BN_clear_free(this->bn); + else BN_free(this->bn); + } + if (this->ctx) BN_CTX_free(this->ctx); + } + + void setAutoclear(bool autoclear = true) { this->autoclear = autoclear; } + + void clear() { if (this->bn) BN_clear(this->bn); } + + // Assignment operations + //BigInt& operator=(BN_ULONG rhs) { if (!BN_set_word(this->bn, rhs)) throw std::runtime_error("BIGNUM Error."); return *this; } + BigInt& operator=(const BigInt& bigint) + { + if (!(BN_copy(this->bn, bigint.bn))) throw std::runtime_error("BIGNUM allocation error."); + //if (!(this->bn = BN_dup(bigint.bn))) throw std::runtime_error("BIGNUM allocation error."); + //if (!(this->ctx = BN_CTX_new())) { BN_free(this->bn); throw std::runtime_error("BIGNUM allocation error."); } + return *this; + } + + // Arithmetic Operations + BigInt& operator+=(const BigInt& rhs) { if (!BN_add(this->bn, this->bn, rhs.bn)) throw std::runtime_error("BN_add error."); return *this; } + BigInt& operator-=(const BigInt& rhs) { if (!BN_sub(this->bn, this->bn, rhs.bn)) throw std::runtime_error("BN_sub error."); return *this; } + BigInt& operator*=(const BigInt& rhs) { if (!BN_mul(this->bn, this->bn, rhs.bn, this->ctx)) throw std::runtime_error("BN_mul rror."); return *this; } + BigInt& operator/=(const BigInt& rhs) { if (!BN_div(this->bn, NULL, this->bn, rhs.bn, this->ctx)) throw std::runtime_error("BN_div error."); return *this; } + BigInt& operator%=(const BigInt& rhs) { if (!BN_div(NULL, this->bn, this->bn, rhs.bn, this->ctx)) throw std::runtime_error("BN_div error."); return *this; } + + BigInt& operator+=(BN_ULONG rhs) { if (!BN_add_word(this->bn, rhs)) throw std::runtime_error("BN_add_word error."); return *this; } + BigInt& operator-=(BN_ULONG rhs) { if (!BN_sub_word(this->bn, rhs)) throw std::runtime_error("BN_sub_word error."); return *this; } + BigInt& operator*=(BN_ULONG rhs) { if (!BN_mul_word(this->bn, rhs)) throw std::runtime_error("BN_mul_word error."); return *this; } + BigInt& operator/=(BN_ULONG rhs) { BN_div_word(this->bn, rhs); return *this; } + BigInt& operator%=(BN_ULONG rhs) { this->setWord(BN_mod_word(this->bn, rhs)); return *this; } + + const BigInt operator+(const BigInt& rightOperand) const { return BigInt(*this) += rightOperand; } + const BigInt operator-(const BigInt& rightOperand) const { return BigInt(*this) -= rightOperand; } + const BigInt operator*(const BigInt& rightOperand) const { return BigInt(*this) *= rightOperand; } + const BigInt operator/(const BigInt& rightOperand) const { return BigInt(*this) /= rightOperand; } + const BigInt operator%(const BigInt& rightOperand) const { return BigInt(*this) %= rightOperand; } + + const BigInt operator+(BN_ULONG rightOperand) const { return BigInt(*this) += rightOperand; } + const BigInt operator-(BN_ULONG rightOperand) const { return BigInt(*this) -= rightOperand; } + const BigInt operator*(BN_ULONG rightOperand) const { return BigInt(*this) *= rightOperand; } + const BigInt operator/(BN_ULONG rightOperand) const { return BigInt(*this) /= rightOperand; } + BN_LONG operator%(BN_ULONG rightOperand) const { return BN_mod_word(this->bn, rightOperand); } + + // Bitshift Operators + BigInt& operator<<=(int rhs) { if (!BN_lshift(this->bn, this->bn, rhs)) throw std::runtime_error("BN_lshift error."); return *this; } + BigInt& operator>>=(int rhs) { if (!BN_rshift(this->bn, this->bn, rhs)) throw std::runtime_error("BN_rshift error."); return *this; } + + const BigInt operator<<(int rhs) const { return BigInt(*this) <<= rhs; } + const BigInt operator>>(int rhs) const { return BigInt(*this) >>= rhs; } + + // Comparison Operators + bool operator==(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) == 0); } + bool operator!=(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) != 0); } + bool operator<(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) < 0); } + bool operator>(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) > 0); } + bool operator<=(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) <= 0); } + bool operator>=(const BigInt& rhs) const { return (BN_cmp(this->bn, rhs.bn) >= 0); } + bool isZero() const { return BN_is_zero(this->bn); } + + // Accessor Methods + BN_ULONG getWord() const { return BN_get_word(this->bn); } + void setWord(BN_ULONG num) { if (!BN_set_word(this->bn, num)) throw std::runtime_error("BN_set_word error."); } + + std::vector getBytes(bool bigEndian = false) const + { + std::vector bytes; + bytes.resize(BN_num_bytes(this->bn)); + BN_bn2bin(this->bn, &bytes[0]); + if (bigEndian) reverse(bytes.begin(), bytes.end()); + return bytes; + } + void setBytes(std::vector bytes, bool bigEndian = false) + { + if (bigEndian) reverse(bytes.begin(), bytes.end()); + BN_bin2bn(&bytes[0], bytes.size(), this->bn); + } + + int numBytes() const { return BN_num_bytes(this->bn); } + + std::string getHex() const + { + char* hex = BN_bn2hex(this->bn); + if (!hex) throw std::runtime_error("BN_bn2hex error."); + std::string rval(hex); + OPENSSL_free(hex); + return rval; + } + void setHex(const std::string& hex) { BN_hex2bn(&this->bn, hex.c_str()); } + void SetHex(const std::string& hex) { setHex(hex); } + + std::string getDec() const + { + char* dec = BN_bn2dec(this->bn); + if (!dec) throw std::runtime_error("BN_bn2dec error."); + std::string rval(dec); + OPENSSL_free(dec); + return rval; + } + void setDec(const std::string& dec) { BN_dec2bn(&this->bn, dec.c_str()); } + + std::string getInBase(unsigned int base, const char* alphabet) const + { + BigInt num = *this; + std::string inBase; + do { + inBase = alphabet[num % base] + inBase; // TODO: check whether this is most efficient structure manipulation + num /= base; + } while (!num.isZero()); + return inBase; + } + + void setInBase(const std::string& inBase, unsigned int base, const char* alphabet) + { + this->setWord(0); + for (unsigned int i = 0; i < inBase.size(); i++) { + const char* pPos = strchr(alphabet, inBase[i]); + if (!pPos) continue; + *this *= base; + *this += (pPos - alphabet); + } + } +}; + +#endif // BIGINT_H_INCLUDED diff --git a/libraries/mSIGNA/include/hash.h b/libraries/mSIGNA/include/hash.h new file mode 100644 index 0000000..b160af2 --- /dev/null +++ b/libraries/mSIGNA/include/hash.h @@ -0,0 +1,118 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// hash.h +// +// Copyright (c) 2011-2012 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#ifndef __HASH_H___ +#define __HASH_H___ + +#include +#include +#include + +#include "uchar_vector.h" + +//#include "hashblock.h" // for Hash9 +#include "scrypt.h" // for scrypt_1024_1_1_256 + +// All inputs and outputs are big endian + +inline uchar_vector sha256(const uchar_vector& data) +{ + unsigned char hash[SHA256_DIGEST_LENGTH]; + SHA256_CTX sha256; + SHA256_Init(&sha256); + SHA256_Update(&sha256, &data[0], data.size()); + SHA256_Final(hash, &sha256); + uchar_vector rval(hash, SHA256_DIGEST_LENGTH); + return rval; +} + +inline uchar_vector sha256_2(const uchar_vector& data) +{ + unsigned char hash[SHA256_DIGEST_LENGTH]; + SHA256_CTX sha256; + SHA256_Init(&sha256); + SHA256_Update(&sha256, &data[0], data.size()); + SHA256_Final(hash, &sha256); + SHA256_Init(&sha256); + SHA256_Update(&sha256, hash, SHA256_DIGEST_LENGTH); + SHA256_Final(hash, &sha256); + uchar_vector rval(hash, SHA256_DIGEST_LENGTH); + return rval; +} + +inline uchar_vector ripemd160(const uchar_vector& data) +{ + unsigned char hash[RIPEMD160_DIGEST_LENGTH]; + RIPEMD160_CTX ripemd160; + RIPEMD160_Init(&ripemd160); + RIPEMD160_Update(&ripemd160, &data[0], data.size()); + RIPEMD160_Final(hash, &ripemd160); + uchar_vector rval(hash, RIPEMD160_DIGEST_LENGTH); + return rval; +} + +inline uchar_vector hash160(const uchar_vector& data) +{ + return ripemd160(sha256(data)); +} + +inline uchar_vector mdsha(const uchar_vector& data) +{ + return ripemd160(sha256(data)); +} + +inline uchar_vector sha1(const uchar_vector& data) +{ + unsigned char hash[SHA_DIGEST_LENGTH]; + SHA_CTX sha1; + SHA1_Init(&sha1); + SHA1_Update(&sha1, &data[0], data.size()); + SHA1_Final(hash, &sha1); + uchar_vector rval(hash, SHA_DIGEST_LENGTH); + return rval; +} + +inline uchar_vector hmac_sha256(const uchar_vector& key, const uchar_vector& data) +{ + unsigned char* digest = HMAC(EVP_sha256(), (unsigned char*)&key[0], key.size(), (unsigned char*)&data[0], data.size(), NULL, NULL); + return uchar_vector(digest, 32); +} + +inline uchar_vector hmac_sha512(const uchar_vector& key, const uchar_vector& data) +{ + unsigned char* digest = HMAC(EVP_sha512(), (unsigned char*)&key[0], key.size(), (unsigned char*)&data[0], data.size(), NULL, NULL); + return uchar_vector(digest, 64); +} +/* +inline uchar_vector hash9(const uchar_vector& data) +{ + uint256 hash = Hash9((unsigned char*)&data[0], (unsigned char*)&data[0] + data.size()); + return uchar_vector((unsigned char*)&hash, (unsigned char*)&hash + 32); +} + +inline uchar_vector sha3_256(const uchar_vector& data) +{ + uchar_vector hash(32); + sph_keccak256_context ctx_keccak; + sph_keccak256_init(&ctx_keccak); + sph_keccak256(&ctx_keccak, (unsigned char*)&data[0], data.size()); + sph_keccak256_close(&ctx_keccak, (unsigned char*)&hash[0]); + return hash; +} + +inline uchar_vector scrypt_1024_1_1_256(const uchar_vector& data) +{ + uint256 hash; + scrypt_1024_1_1_256_((const char*)&data[0], (char*)&hash); + return uchar_vector((unsigned char*)&hash, (unsigned char*)&hash + 32); +} +*/ +#endif diff --git a/libraries/mSIGNA/include/hdkeys.h b/libraries/mSIGNA/include/hdkeys.h new file mode 100644 index 0000000..1500c94 --- /dev/null +++ b/libraries/mSIGNA/include/hdkeys.h @@ -0,0 +1,142 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// hdkeys.h +// +// Copyright (c) 2013-2014 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#ifndef COIN_HDKEYS_H +#define COIN_HDKEYS_H + +#include "hash.h" +#include "typedefs.h" + +#include + +namespace Coin { + +const uchar_vector BITCOIN_SEED("426974636f696e2073656564"); // key = "Bitcoin seed" + +class HDSeed +{ +public: + HDSeed(const bytes_t& seed, const bytes_t& coin_seed = BITCOIN_SEED) + { + bytes_t hmac = hmac_sha512(coin_seed, seed); + master_key_.assign(hmac.begin(), hmac.begin() + 32); + master_chain_code_.assign(hmac.begin() + 32, hmac.end()); + } + + const bytes_t& getSeed() const { return seed_; } + const bytes_t& getMasterKey() const { return master_key_; } + const bytes_t& getMasterChainCode() const { return master_chain_code_; } + bytes_t getExtendedKey(bool bPrivate = false) const; + +private: + bytes_t seed_; + bytes_t master_key_; + bytes_t master_chain_code_; +}; + +class InvalidHDKeychainException : public std::runtime_error +{ +public: + InvalidHDKeychainException() + : std::runtime_error("Keychain is invalid.") { } +}; + +class InvalidHDKeychainPathException : public std::runtime_error +{ +public: + InvalidHDKeychainPathException() + : std::runtime_error("Keychain path is invalid.") { } +}; + +class HDKeychain +{ +public: + HDKeychain() { } + HDKeychain(const bytes_t& key, const bytes_t& chain_code, uint32_t child_num = 0, uint32_t parent_fp = 0, uint32_t depth = 0); + HDKeychain(const bytes_t& extkey); + HDKeychain(const HDKeychain& source); + + HDKeychain& operator=(const HDKeychain& rhs); + + explicit operator bool() const { return valid_; } + + + bool operator==(const HDKeychain& rhs) const; + bool operator!=(const HDKeychain& rhs) const; + + // Serialization + bytes_t extkey() const; + + // Accessor Methods + uint32_t version() const { return version_; } + int depth() const { return depth_; } + uint32_t parent_fp() const { return parent_fp_; } + uint32_t child_num() const { return child_num_; } + const bytes_t& chain_code() const { return chain_code_; } + const bytes_t& key() const { return key_; } + + bytes_t privkey() const; + const bytes_t& pubkey() const { return pubkey_; } + bytes_t uncompressed_pubkey() const; + + bool isPrivate() const { return (key_.size() == 33 && key_[0] == 0x00); } + bytes_t hash() const; // hash is ripemd160(sha256(pubkey)) + uint32_t fp() const; // fingerprint is first 32 bits of hash + bytes_t full_hash() const; // full_hash is ripemd160(sha256(pubkey + chain_code)) + + HDKeychain getPublic() const; + HDKeychain getChild(uint32_t i) const; + HDKeychain getChild(const std::string& path) const; + HDKeychain getChildNode(uint32_t i, bool private_derivation = false) const + { + uint32_t mask = private_derivation ? 0x80000000ull : 0x00000000ull; + return getChild(mask).getChild(i); + } + + // Precondition: i >= 1 + bytes_t getPrivateSigningKey(uint32_t i) const + { +// if (i == 0) throw std::runtime_error("Signing key index cannot be zero."); + return getChild(i).privkey(); + } + + // Precondition: i >= 1 + bytes_t getPublicSigningKey(uint32_t i, bool bCompressed = true) const + { +// if (i == 0) throw std::runtime_error("Signing key index cannot be zero."); + return bCompressed ? getChild(i).pubkey() : getChild(i).uncompressed_pubkey(); + } + + static void setVersions(uint32_t priv_version, uint32_t pub_version) { priv_version_ = priv_version; pub_version_ = pub_version; } + + std::string toString() const; + +private: + static uint32_t priv_version_; + static uint32_t pub_version_; + + uint32_t version_; + unsigned char depth_; + uint32_t parent_fp_; + uint32_t child_num_; + bytes_t chain_code_; // 32 bytes + bytes_t key_; // 33 bytes, first byte is 0x00 for private key + + bytes_t pubkey_; + + bool valid_; + + void updatePubkey(); +}; + +} + +#endif // COIN_HDKEYS_H diff --git a/libraries/mSIGNA/include/scrypt.h b/libraries/mSIGNA/include/scrypt.h new file mode 100644 index 0000000..5db0135 --- /dev/null +++ b/libraries/mSIGNA/include/scrypt.h @@ -0,0 +1,35 @@ +#ifndef SCRYPT_H +#define SCRYPT_H +#include +#include +static const int SCRYPT_SCRATCHPAD_SIZE = 131072 + 63; + +void scrypt_1024_1_1_256_(const char *input, char *output); +void scrypt_1024_1_1_256_sp_generic(const char *input, char *output, char *scratchpad); + +#if defined(USE_SSE2) +extern void scrypt_detect_sse2(unsigned int cpuid_edx); +void scrypt_1024_1_1_256_sp_sse2(const char *input, char *output, char *scratchpad); +extern void (*scrypt_1024_1_1_256_sp)(const char *input, char *output, char *scratchpad); +#endif + +void +PBKDF2_SHA256(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt, + size_t saltlen, uint64_t c, uint8_t *buf, size_t dkLen); + +static inline uint32_t le32dec(const void *pp) +{ + const uint8_t *p = (uint8_t const *)pp; + return ((uint32_t)(p[0]) + ((uint32_t)(p[1]) << 8) + + ((uint32_t)(p[2]) << 16) + ((uint32_t)(p[3]) << 24)); +} + +static inline void le32enc(void *pp, uint32_t x) +{ + uint8_t *p = (uint8_t *)pp; + p[0] = x & 0xff; + p[1] = (x >> 8) & 0xff; + p[2] = (x >> 16) & 0xff; + p[3] = (x >> 24) & 0xff; +} +#endif diff --git a/libraries/mSIGNA/include/secp256k1_openssl.h b/libraries/mSIGNA/include/secp256k1_openssl.h new file mode 100644 index 0000000..808457f --- /dev/null +++ b/libraries/mSIGNA/include/secp256k1_openssl.h @@ -0,0 +1,102 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// secp256k1_openssl.h +// +// Copyright (c) 2013-2014 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Some portions taken from bitcoin/bitcoin, +// Copyright (c) 2009-2013 Satoshi Nakamoto, the Bitcoin developers +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#pragma once + +#include + +#include +#include +#include +#include + +#include "typedefs.h" + +namespace CoinCrypto +{ + +class secp256k1_key +{ +public: + secp256k1_key(); + ~secp256k1_key() { EC_KEY_free(pKey); } + + EC_KEY* getKey() const { return bSet ? pKey : nullptr; } + EC_KEY* newKey(); + bytes_t getPrivKey() const; + EC_KEY* setPrivKey(const bytes_t& privkey); + bytes_t getPubKey(bool bCompressed = true) const; + EC_KEY* setPubKey(const bytes_t& pubkey); + +private: + EC_KEY* pKey; + bool bSet; +}; + + +class secp256k1_point +{ +public: + secp256k1_point() { init(); } + secp256k1_point(const secp256k1_point& source); + secp256k1_point(const bytes_t& bytes); + ~secp256k1_point(); + + secp256k1_point& operator=(const secp256k1_point& rhs); + + void bytes(const bytes_t& bytes); + bytes_t bytes() const; + + secp256k1_point& operator+=(const secp256k1_point& rhs); + secp256k1_point& operator*=(const bytes_t& rhs); + + const secp256k1_point operator+(const secp256k1_point& rhs) const { return secp256k1_point(*this) += rhs; } + const secp256k1_point operator*(const bytes_t& rhs) const { return secp256k1_point(*this) *= rhs; } + + // Computes n*G + K where K is this and G is the group generator + void generator_mul(const bytes_t& n); + + // Sets to n*G + void set_generator_mul(const bytes_t& n); + + bool is_at_infinity() const { return EC_POINT_is_at_infinity(group, point); } + void set_to_infinity() { EC_POINT_set_to_infinity(group, point); } + + const EC_GROUP* getGroup() const { return group; } + const EC_POINT* getPoint() const { return point; } + +protected: + void init(); + +private: + EC_GROUP* group; + EC_POINT* point; + BN_CTX* ctx; +}; + +enum SignatureFlag +{ + SIGNATURE_ENFORCE_LOW_S = 0x1, +}; + +bytes_t secp256k1_sigToLowS(const bytes_t& signature); + +bytes_t secp256k1_sign(const secp256k1_key& key, const bytes_t& data); +bool secp256k1_verify(const secp256k1_key& key, const bytes_t& data, const bytes_t& signature, int flags = 0); + +bytes_t secp256k1_rfc6979_k(const secp256k1_key& key, const bytes_t& data); +bytes_t secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes_t& data); + +} + diff --git a/libraries/mSIGNA/include/typedefs.h b/libraries/mSIGNA/include/typedefs.h new file mode 100644 index 0000000..9ff9f4d --- /dev/null +++ b/libraries/mSIGNA/include/typedefs.h @@ -0,0 +1,32 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// typedefs.h +// +// Copyright (c) 2013 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#ifndef __TYPEDEFS_H___ +#define __TYPEDEFS_H___ + +#include +#include +#include + +typedef std::vector bytes_t; +typedef std::vector secure_bytes_t; + +typedef std::vector hashvector_t; +typedef std::set hashset_t; + +typedef std::string secure_string_t; + +typedef std::vector ints_t; +typedef std::vector secure_ints_t; + +// TODO: use custom allocators for secure types + +#endif // __TYPEDEFS_H__ diff --git a/libraries/mSIGNA/include/uchar_vector.h b/libraries/mSIGNA/include/uchar_vector.h new file mode 100644 index 0000000..6d1c0d8 --- /dev/null +++ b/libraries/mSIGNA/include/uchar_vector.h @@ -0,0 +1,262 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// uchar_vector.h +// +// Copyright (c) 2011-2012 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#ifndef UCHAR_VECTOR_H__ +#define UCHAR_VECTOR_H__ + +#include +#include + +#include +#include + +#include +#include +#include + +const char g_hexBytes[][3] = { + "00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f", + "10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f", + "20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f", + "30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f", + "40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f", + "50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f", + "60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f", + "70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f", + "80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f", + "90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f", + "a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af", + "b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf", + "c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf", + "d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df", + "e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef", + "f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff" +}; + +const char base64chars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + +typedef unsigned int uint; + +/// TODO: Add secure allocator capabilities +//template < class Allocator = allocator > +class uchar_vector : public std::vector//, Allocator> +{ +public: + uchar_vector() : std::vector() { } + uchar_vector(size_type n, const unsigned char& value = 0) : std::vector(n, value) { } + template uchar_vector(InputIterator first, InputIterator last) : std::vector(first, last) { } + uchar_vector(const std::vector& vec) : std::vector(vec) { } + uchar_vector(const unsigned char* array, unsigned int size) : std::vector(array, array + size) { } + uchar_vector(const std::string& hex) { this->setHex(hex); } + + uchar_vector& operator+=(const std::vector& rhs) + { + this->insert(this->end(), rhs.begin(), rhs.end()); + return *this; + } + + uchar_vector& operator<<(const std::vector& rhs) + { + this->insert(this->end(), rhs.begin(), rhs.end()); + return *this; + } + + uchar_vector& operator<<(unsigned char byte) + { + this->push_back(byte); + return *this; + } + + const uchar_vector operator+(const std::vector& rightOperand) const { return uchar_vector(*this) += rightOperand; } + + uchar_vector& operator=(const std::string& hex) { this->setHex(hex); return *this; } + + void copyToArray(unsigned char* array) { std::copy(this->begin(),this->end(), array); } + + void padLeft(unsigned char pad, uint total_length) + { + this->reverse(); + this->padRight(pad, total_length); + this->reverse(); + } + + void padRight(unsigned char pad, uint total_length) + { + for (uint i = this->size(); i < total_length; i++) + this->push_back(pad); + } + + std::string getHex(bool spaceBytes = false) const + { + std::string hex; + hex.reserve(this->size() * 2); + for (uint i = 0; i < this->size(); i++) { + if (spaceBytes && (i > 0)) hex += " "; + hex += g_hexBytes[(*this)[i]]; + } + return hex; + } + + void setHex(std::string hex) + { + this->clear(); + + // pad on the left if hex contains an odd number of digits. + if (hex.size() % 2 == 1) + hex = "0" + hex; + + this->reserve(hex.size() / 2); + + for (uint i = 0; i < hex.size(); i+=2) { + uint byte; + sscanf(hex.substr(i, 2).c_str(), "%x", &byte); + this->push_back(byte); + } + } + + void reverse() { std::reverse(this->begin(), this->end()); } + + uchar_vector getReverse() const + { + uchar_vector rval(*this); + rval.reverse(); + return rval; + } + + std::string getCharsAsString() const + { + std::string chars; + chars.reserve(this->size()); + for (uint i = 0; i < this->size(); i++) + chars += (*this)[i]; + return chars; + } + + void setCharsFromString(const std::string& chars) + { + this->clear(); + this->reserve(chars.size()); + for (uint i = 0; i < chars.size(); i++) + this->push_back(chars[i]); + } + + std::string getBase64() const + { + unsigned int padding = (3 - (this->size() % 3)) % 3; + std::string base64; + + uchar_vector paddedBytes = *this; + for (unsigned int i = 1; i <= padding; i++) + paddedBytes.push_back(0); + + base64.reserve(4*(paddedBytes.size()) / 3); + + for (unsigned int i = 0; i < paddedBytes.size(); i += 3) { + uint32_t triple = ((uint32_t)paddedBytes[i] << 16) | ((uint32_t)paddedBytes[i+1] << 8) | (uint32_t)paddedBytes[i+2]; + base64 += base64chars[(triple & 0x00fc0000) >> 18]; + base64 += base64chars[(triple & 0x0003f000) >> 12]; + base64 += base64chars[(triple & 0x00000fc0) >> 6]; + base64 += base64chars[triple & 0x0000003f]; + } + + for (unsigned int i = 1; i <= padding; i++) + base64[base64.size() - i] = '='; + + return base64; + } + + void setBase64(std::string base64) + { + unsigned int padding = (4 - (base64.size() % 4)) % 4; + + std::string paddedBase64; + paddedBase64.reserve(base64.size() + padding); + paddedBase64 = base64; + paddedBase64.append(padding, '='); + padding = 0; // we'll count them again in the loop so we also get any that were already there. + + this->clear(); + this->reserve(3*paddedBase64.size() / 4); + + bool bEnd = false; + for (unsigned int i = 0; (i < paddedBase64.size()) && (!bEnd); i+=4) { + uint32_t digits[4]; + for (unsigned int j = 0; j < 4; j++) { + const char* pPos = strchr(base64chars, paddedBase64[i+j]); + if (!pPos) bEnd = true; + if (bEnd) { + digits[j] = 0; + padding++; + } + else + digits[j] = (uint32_t)(pPos - base64chars); + } + + uint32_t quadruple = (digits[0] << 18) | (digits[1] << 12) | (digits[2] << 6) | digits[3]; + + this->push_back((quadruple & 0x00ff0000) >> 16); + this->push_back((quadruple & 0x0000ff00) >> 8); + this->push_back(quadruple & 0x000000ff); + } + + for (unsigned int i = 0; i < padding; i++) + this->pop_back(); + } +}; + +typedef std::string string_secure; +typedef uchar_vector uchar_vector_secure; // not really :p at least not yet! +/* +// +// Allocator that locks its contents from being paged +// out of memory and clears its contents before deletion. +// +template +struct secure_allocator : public std::allocator +{ + // MSVC8 default copy constructor is broken + typedef std::allocator base; + typedef typename base::size_type size_type; + typedef typename base::difference_type difference_type; + typedef typename base::pointer pointer; + typedef typename base::const_pointer const_pointer; + typedef typename base::reference reference; + typedef typename base::const_reference const_reference; + typedef typename base::value_type value_type; + secure_allocator() throw() {} + secure_allocator(const secure_allocator& a) throw() : base(a) {} + template + secure_allocator(const secure_allocator& a) throw() : base(a) {} + ~secure_allocator() throw() {} + template struct rebind + { typedef secure_allocator<_Other> other; }; + + T* allocate(std::size_t n, const void *hint = 0) + { + T *p; + p = std::allocator::allocate(n, hint); + if (p != NULL) + mlock(p, sizeof(T) * n); + return p; + } + + void deallocate(T* p, std::size_t n) + { + if (p != NULL) + { + memset(p, 0, sizeof(T) * n); + munlock(p, sizeof(T) * n); + } + std::allocator::deallocate(p, n); + } +}; +*/ +#endif diff --git a/libraries/mSIGNA/scrypt.cpp b/libraries/mSIGNA/scrypt.cpp new file mode 100644 index 0000000..f7f5197 --- /dev/null +++ b/libraries/mSIGNA/scrypt.cpp @@ -0,0 +1,323 @@ +/* + * Copyright 2009 Colin Percival, 2011 ArtForz, 2012-2013 pooler + * All rights reserved. + * + * 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. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``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 OR CONTRIBUTORS 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. + * + * This file was originally written by Colin Percival as part of the Tarsnap + * online backup system. + */ + +#include "scrypt.h" +//#include "util.h" +#include +#include +#include +#include + +static inline uint32_t be32dec(const void *pp) +{ + const uint8_t *p = (uint8_t const *)pp; + return ((uint32_t)(p[3]) + ((uint32_t)(p[2]) << 8) + + ((uint32_t)(p[1]) << 16) + ((uint32_t)(p[0]) << 24)); +} + +static inline void be32enc(void *pp, uint32_t x) +{ + uint8_t *p = (uint8_t *)pp; + p[3] = x & 0xff; + p[2] = (x >> 8) & 0xff; + p[1] = (x >> 16) & 0xff; + p[0] = (x >> 24) & 0xff; +} + +typedef struct HMAC_SHA256Context { + SHA256_CTX ictx; + SHA256_CTX octx; +} HMAC_SHA256_CTX; + +/* Initialize an HMAC-SHA256 operation with the given key. */ +static void +HMAC_SHA256_Init(HMAC_SHA256_CTX *ctx, const void *_K, size_t Klen) +{ + unsigned char pad[64]; + unsigned char khash[32]; + const unsigned char *K = (const unsigned char *)_K; + size_t i; + + /* If Klen > 64, the key is really SHA256(K). */ + if (Klen > 64) { + SHA256_Init(&ctx->ictx); + SHA256_Update(&ctx->ictx, K, Klen); + SHA256_Final(khash, &ctx->ictx); + K = khash; + Klen = 32; + } + + /* Inner SHA256 operation is SHA256(K xor [block of 0x36] || data). */ + SHA256_Init(&ctx->ictx); + memset(pad, 0x36, 64); + for (i = 0; i < Klen; i++) + pad[i] ^= K[i]; + SHA256_Update(&ctx->ictx, pad, 64); + + /* Outer SHA256 operation is SHA256(K xor [block of 0x5c] || hash). */ + SHA256_Init(&ctx->octx); + memset(pad, 0x5c, 64); + for (i = 0; i < Klen; i++) + pad[i] ^= K[i]; + SHA256_Update(&ctx->octx, pad, 64); + + /* Clean the stack. */ + memset(khash, 0, 32); +} + +/* Add bytes to the HMAC-SHA256 operation. */ +static void +HMAC_SHA256_Update(HMAC_SHA256_CTX *ctx, const void *in, size_t len) +{ + /* Feed data to the inner SHA256 operation. */ + SHA256_Update(&ctx->ictx, in, len); +} + +/* Finish an HMAC-SHA256 operation. */ +static void +HMAC_SHA256_Final(unsigned char digest[32], HMAC_SHA256_CTX *ctx) +{ + unsigned char ihash[32]; + + /* Finish the inner SHA256 operation. */ + SHA256_Final(ihash, &ctx->ictx); + + /* Feed the inner hash to the outer SHA256 operation. */ + SHA256_Update(&ctx->octx, ihash, 32); + + /* Finish the outer SHA256 operation. */ + SHA256_Final(digest, &ctx->octx); + + /* Clean the stack. */ + memset(ihash, 0, 32); +} + +/** + * PBKDF2_SHA256(passwd, passwdlen, salt, saltlen, c, buf, dkLen): + * Compute PBKDF2(passwd, salt, c, dkLen) using HMAC-SHA256 as the PRF, and + * write the output to buf. The value dkLen must be at most 32 * (2^32 - 1). + */ +void +PBKDF2_SHA256(const uint8_t *passwd, size_t passwdlen, const uint8_t *salt, + size_t saltlen, uint64_t c, uint8_t *buf, size_t dkLen) +{ + HMAC_SHA256_CTX PShctx, hctx; + size_t i; + uint8_t ivec[4]; + uint8_t U[32]; + uint8_t T[32]; + uint64_t j; + int k; + size_t clen; + + /* Compute HMAC state after processing P and S. */ + HMAC_SHA256_Init(&PShctx, passwd, passwdlen); + HMAC_SHA256_Update(&PShctx, salt, saltlen); + + /* Iterate through the blocks. */ + for (i = 0; i * 32 < dkLen; i++) { + /* Generate INT(i + 1). */ + be32enc(ivec, (uint32_t)(i + 1)); + + /* Compute U_1 = PRF(P, S || INT(i)). */ + memcpy(&hctx, &PShctx, sizeof(HMAC_SHA256_CTX)); + HMAC_SHA256_Update(&hctx, ivec, 4); + HMAC_SHA256_Final(U, &hctx); + + /* T_i = U_1 ... */ + memcpy(T, U, 32); + + for (j = 2; j <= c; j++) { + /* Compute U_j. */ + HMAC_SHA256_Init(&hctx, passwd, passwdlen); + HMAC_SHA256_Update(&hctx, U, 32); + HMAC_SHA256_Final(U, &hctx); + + /* ... xor U_j ... */ + for (k = 0; k < 32; k++) + T[k] ^= U[k]; + } + + /* Copy as many bytes as necessary into buf. */ + clen = dkLen - i * 32; + if (clen > 32) + clen = 32; + memcpy(&buf[i * 32], T, clen); + } + + /* Clean PShctx, since we never called _Final on it. */ + memset(&PShctx, 0, sizeof(HMAC_SHA256_CTX)); +} + +#define ROTL(a, b) (((a) << (b)) | ((a) >> (32 - (b)))) + +static inline void xor_salsa8(uint32_t B[16], const uint32_t Bx[16]) +{ + uint32_t x00,x01,x02,x03,x04,x05,x06,x07,x08,x09,x10,x11,x12,x13,x14,x15; + int i; + + x00 = (B[ 0] ^= Bx[ 0]); + x01 = (B[ 1] ^= Bx[ 1]); + x02 = (B[ 2] ^= Bx[ 2]); + x03 = (B[ 3] ^= Bx[ 3]); + x04 = (B[ 4] ^= Bx[ 4]); + x05 = (B[ 5] ^= Bx[ 5]); + x06 = (B[ 6] ^= Bx[ 6]); + x07 = (B[ 7] ^= Bx[ 7]); + x08 = (B[ 8] ^= Bx[ 8]); + x09 = (B[ 9] ^= Bx[ 9]); + x10 = (B[10] ^= Bx[10]); + x11 = (B[11] ^= Bx[11]); + x12 = (B[12] ^= Bx[12]); + x13 = (B[13] ^= Bx[13]); + x14 = (B[14] ^= Bx[14]); + x15 = (B[15] ^= Bx[15]); + for (i = 0; i < 8; i += 2) { + /* Operate on columns. */ + x04 ^= ROTL(x00 + x12, 7); x09 ^= ROTL(x05 + x01, 7); + x14 ^= ROTL(x10 + x06, 7); x03 ^= ROTL(x15 + x11, 7); + + x08 ^= ROTL(x04 + x00, 9); x13 ^= ROTL(x09 + x05, 9); + x02 ^= ROTL(x14 + x10, 9); x07 ^= ROTL(x03 + x15, 9); + + x12 ^= ROTL(x08 + x04, 13); x01 ^= ROTL(x13 + x09, 13); + x06 ^= ROTL(x02 + x14, 13); x11 ^= ROTL(x07 + x03, 13); + + x00 ^= ROTL(x12 + x08, 18); x05 ^= ROTL(x01 + x13, 18); + x10 ^= ROTL(x06 + x02, 18); x15 ^= ROTL(x11 + x07, 18); + + /* Operate on rows. */ + x01 ^= ROTL(x00 + x03, 7); x06 ^= ROTL(x05 + x04, 7); + x11 ^= ROTL(x10 + x09, 7); x12 ^= ROTL(x15 + x14, 7); + + x02 ^= ROTL(x01 + x00, 9); x07 ^= ROTL(x06 + x05, 9); + x08 ^= ROTL(x11 + x10, 9); x13 ^= ROTL(x12 + x15, 9); + + x03 ^= ROTL(x02 + x01, 13); x04 ^= ROTL(x07 + x06, 13); + x09 ^= ROTL(x08 + x11, 13); x14 ^= ROTL(x13 + x12, 13); + + x00 ^= ROTL(x03 + x02, 18); x05 ^= ROTL(x04 + x07, 18); + x10 ^= ROTL(x09 + x08, 18); x15 ^= ROTL(x14 + x13, 18); + } + B[ 0] += x00; + B[ 1] += x01; + B[ 2] += x02; + B[ 3] += x03; + B[ 4] += x04; + B[ 5] += x05; + B[ 6] += x06; + B[ 7] += x07; + B[ 8] += x08; + B[ 9] += x09; + B[10] += x10; + B[11] += x11; + B[12] += x12; + B[13] += x13; + B[14] += x14; + B[15] += x15; +} + +void scrypt_1024_1_1_256_sp_generic(const char *input, char *output, char *scratchpad) +{ + uint8_t B[128]; + uint32_t X[32]; + uint32_t *V; + uint32_t i, j, k; + + V = (uint32_t *)(((uintptr_t)(scratchpad) + 63) & ~ (uintptr_t)(63)); + + PBKDF2_SHA256((const uint8_t *)input, 80, (const uint8_t *)input, 80, 1, B, 128); + + for (k = 0; k < 32; k++) + X[k] = le32dec(&B[4 * k]); + + for (i = 0; i < 1024; i++) { + memcpy(&V[i * 32], X, 128); + xor_salsa8(&X[0], &X[16]); + xor_salsa8(&X[16], &X[0]); + } + for (i = 0; i < 1024; i++) { + j = 32 * (X[16] & 1023); + for (k = 0; k < 32; k++) + X[k] ^= V[j + k]; + xor_salsa8(&X[0], &X[16]); + xor_salsa8(&X[16], &X[0]); + } + + for (k = 0; k < 32; k++) + le32enc(&B[4 * k], X[k]); + + PBKDF2_SHA256((const uint8_t *)input, 80, B, 128, 1, (uint8_t *)output, 32); +} + +#if defined(USE_SSE2) +#if defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) || (defined(MAC_OSX) && defined(__i386__)) +/* Always SSE2 */ +void scrypt_detect_sse2(unsigned int cpuid_edx) +{ + printf("scrypt: using scrypt-sse2 as built.\n"); +} +#else +/* Detect SSE2 */ +void (*scrypt_1024_1_1_256_sp)(const char *input, char *output, char *scratchpad); + +void scrypt_detect_sse2(unsigned int cpuid_edx) +{ + if (cpuid_edx & 1<<26) + { + scrypt_1024_1_1_256_sp = &scrypt_1024_1_1_256_sp_sse2; + printf("scrypt: using scrypt-sse2 as detected.\n"); + } + else + { + scrypt_1024_1_1_256_sp = &scrypt_1024_1_1_256_sp_generic; + printf("scrypt: using scrypt-generic, SSE2 unavailable.\n"); + } +} +#endif +#endif + +void scrypt_1024_1_1_256_(const char *input, char *output) +{ + char scratchpad[SCRYPT_SCRATCHPAD_SIZE]; +#if defined(USE_SSE2) + // Detection would work, but in cases where we KNOW it always has SSE2, + // it is faster to use directly than to use a function pointer or conditional. +#if defined(_M_X64) || defined(__x86_64__) || defined(_M_AMD64) || (defined(MAC_OSX) && defined(__i386__)) + // Always SSE2: x86_64 or Intel MacOS X + scrypt_1024_1_1_256_sp_sse2(input, output, scratchpad); +#else + // Detect SSE2: 32bit x86 Linux or Windows + scrypt_1024_1_1_256_sp(input, output, scratchpad); +#endif +#else + // Generic scrypt + scrypt_1024_1_1_256_sp_generic(input, output, scratchpad); +#endif +} diff --git a/libraries/mSIGNA/secp256k1_openssl.cpp b/libraries/mSIGNA/secp256k1_openssl.cpp new file mode 100644 index 0000000..20608b7 --- /dev/null +++ b/libraries/mSIGNA/secp256k1_openssl.cpp @@ -0,0 +1,458 @@ +//////////////////////////////////////////////////////////////////////////////// +// +// secp256k1_openssl.cpp +// +// Copyright (c) 2013-2014 Eric Lombrozo +// Copyright (c) 2011-2016 Ciphrex Corp. +// +// Some portions taken from bitcoin/bitcoin, +// Copyright (c) 2009-2013 Satoshi Nakamoto, the Bitcoin developers +// +// Distributed under the MIT software license, see the accompanying +// file LICENSE or http://www.opensource.org/licenses/mit-license.php. +// + +#include "secp256k1_openssl.h" +#include "hash.h" + +#include +#include + +#ifdef TRACE_RFC6979 + #include +#endif + +using namespace CoinCrypto; + +const uchar_vector SECP256K1_FIELD_MOD("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F"); +const uchar_vector SECP256K1_GROUP_ORDER("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"); +const uchar_vector SECP256K1_GROUP_HALFORDER("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"); + +bool static EC_KEY_regenerate_key(EC_KEY* eckey, BIGNUM* priv_key) +{ + if (!eckey) return false; + + const EC_GROUP *group = EC_KEY_get0_group(eckey); + + bool rval = false; + EC_POINT* pub_key = NULL; + BN_CTX* ctx = BN_CTX_new(); + if (!ctx) goto finish; + + pub_key = EC_POINT_new(group); + if (!pub_key) goto finish; + + if (!EC_POINT_mul(group, pub_key, priv_key, NULL, NULL, ctx)) goto finish; + + EC_KEY_set_private_key(eckey, priv_key); + EC_KEY_set_public_key(eckey, pub_key); + + rval = true; + +finish: + if (pub_key) EC_POINT_free(pub_key); + if (ctx) BN_CTX_free(ctx); + return rval; +} + + +secp256k1_key::secp256k1_key() +{ + pKey = EC_KEY_new_by_curve_name(NID_secp256k1); + if (!pKey) { + throw std::runtime_error("secp256k1_key::secp256k1_key() : EC_KEY_new_by_curve_name failed."); + } + EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED); + bSet = false; +} + +EC_KEY* secp256k1_key::newKey() +{ + if (!EC_KEY_generate_key(pKey)) { + throw std::runtime_error("secp256k1_key::newKey() : EC_KEY_generate_key failed."); + } + EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED); + bSet = true; + return pKey; +} + +bytes_t secp256k1_key::getPrivKey() const +{ + if (!bSet) { + throw std::runtime_error("secp256k1_key::getPrivKey() : key is not set."); + } + + const BIGNUM* bn = EC_KEY_get0_private_key(pKey); + if (!bn) { + throw std::runtime_error("secp256k1_key::getPrivKey() : EC_KEY_get0_private_key failed."); + } + unsigned char privKey[32]; + assert(BN_num_bytes(bn) <= 32); + BN_bn2bin(bn, privKey); + return bytes_t(privKey, privKey + 32); +} + +EC_KEY* secp256k1_key::setPrivKey(const bytes_t& privkey) +{ + BIGNUM* bn = BN_bin2bn(&privkey[0], privkey.size(), NULL); + if (!bn) { + throw std::runtime_error("secp256k1_key::setPrivKey() : BN_bin2bn failed."); + } + + bool bFail = !EC_KEY_regenerate_key(pKey, bn); + BN_clear_free(bn); + if (bFail) { + throw std::runtime_error("secp256k1_key::setPrivKey() : EC_KEY_set_private_key failed."); + } + bSet = true; + return pKey; +} + +bytes_t secp256k1_key::getPubKey(bool bCompressed) const +{ + if (!bSet) { + throw std::runtime_error("secp256k1_key::getPubKey() : key is not set."); + } + + if (!bCompressed) EC_KEY_set_conv_form(pKey, POINT_CONVERSION_UNCOMPRESSED); + int nSize = i2o_ECPublicKey(pKey, NULL); + if (nSize == 0) { + if (!bCompressed) EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED); + throw std::runtime_error("secp256k1_key::getPubKey() : i2o_ECPublicKey failed."); + } + + bytes_t pubKey(nSize, 0); + unsigned char* pBegin = &pubKey[0]; + if (i2o_ECPublicKey(pKey, &pBegin) != nSize) { + if (!bCompressed) EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED); + throw std::runtime_error("secp256k1_key::getPubKey() : i2o_ECPublicKey returned unexpected size."); + } + + if (!bCompressed) EC_KEY_set_conv_form(pKey, POINT_CONVERSION_COMPRESSED); + return pubKey; +} + +EC_KEY* secp256k1_key::setPubKey(const bytes_t& pubkey) +{ + if (pubkey.empty()) throw std::runtime_error("secp256k1_key::setPubKey() : pubkey is empty."); + + const unsigned char* pBegin = (unsigned char*)&pubkey[0]; + if (!o2i_ECPublicKey(&pKey, &pBegin, pubkey.size())) throw std::runtime_error("secp256k1_key::setPubKey() : o2i_ECPublicKey failed."); + bSet = true; + return pKey; +} + + + +secp256k1_point::secp256k1_point(const secp256k1_point& source) +{ + init(); + if (!EC_GROUP_copy(group, source.group)) throw std::runtime_error("secp256k1_point::secp256k1_point(const secp256k1_point&) - EC_GROUP_copy failed."); + if (!EC_POINT_copy(point, source.point)) throw std::runtime_error("secp256k1_point::secp256k1_point(const secp256k1_point&) - EC_POINT_copy failed."); +} + +secp256k1_point::secp256k1_point(const bytes_t& bytes) +{ + init(); + this->bytes(bytes); +} + + +secp256k1_point::~secp256k1_point() +{ + if (point) EC_POINT_free(point); + if (group) EC_GROUP_free(group); + if (ctx) BN_CTX_free(ctx); +} + +secp256k1_point& secp256k1_point::operator=(const secp256k1_point& rhs) +{ + if (!EC_GROUP_copy(group, rhs.group)) throw std::runtime_error("secp256k1_point::operator= - EC_GROUP_copy failed."); + if (!EC_POINT_copy(point, rhs.point)) throw std::runtime_error("secp256k1_point::operator= - EC_POINT_copy failed."); + + return *this; +} + +void secp256k1_point::bytes(const bytes_t& bytes) +{ + std::string err; + + EC_POINT* rval; + + BIGNUM* bn = BN_bin2bn(&bytes[0], bytes.size(), NULL); + if (!bn) { + err = "BN_bin2bn failed."; + goto finish; + } + + rval = EC_POINT_bn2point(group, bn, point, ctx); + if (!rval) { + err = "EC_POINT_bn2point failed."; + goto finish; + } + +finish: + if (bn) BN_clear_free(bn); + + if (!err.empty()) { + throw std::runtime_error(std::string("secp256k1_point::set() - ") + err); + } +} + +bytes_t secp256k1_point::bytes() const +{ + bytes_t bytes(33); + + std::string err; + + BIGNUM* rval; + + BIGNUM* bn = BN_new(); + if (!bn) { + err = "BN_new failed."; + goto finish; + } + + rval = EC_POINT_point2bn(group, point, POINT_CONVERSION_COMPRESSED, bn, ctx); + if (!rval) { + err = "EC_POINT_point2bn failed."; + goto finish; + } + + assert(BN_num_bytes(bn) == 33); + BN_bn2bin(bn, &bytes[0]); + +finish: + if (bn) BN_clear_free(bn); + + if (!err.empty()) { + throw std::runtime_error(std::string("secp256k1_point::get() - ") + err); + } + + return bytes; +} + +secp256k1_point& secp256k1_point::operator+=(const secp256k1_point& rhs) +{ + if (!EC_POINT_add(group, point, point, rhs.point, ctx)) { + throw std::runtime_error("secp256k1_point::operator+= - EC_POINT_add failed."); + } + return *this; +} + +secp256k1_point& secp256k1_point::operator*=(const bytes_t& rhs) +{ + BIGNUM* bn = BN_bin2bn(&rhs[0], rhs.size(), NULL); + if (!bn) { + throw std::runtime_error("secp256k1_point::operator*= - BN_bin2bn failed."); + } + + int rval = EC_POINT_mul(group, point, NULL, point, bn, ctx); + BN_clear_free(bn); + + if (rval == 0) { + throw std::runtime_error("secp256k1_point::operator*= - EC_POINT_mul failed."); + } + + return *this; +} + +// Computes n*G + K where K is this and G is the group generator +void secp256k1_point::generator_mul(const bytes_t& n) +{ + BIGNUM* bn = BN_bin2bn(&n[0], n.size(), NULL); + if (!bn) throw std::runtime_error("secp256k1_point::generator_mul - BN_bin2bn failed."); + + //int rval = EC_POINT_mul(group, point, bn, (is_at_infinity() ? NULL : point), BN_value_one(), ctx); + int rval = EC_POINT_mul(group, point, bn, point, BN_value_one(), ctx); + BN_clear_free(bn); + + if (rval == 0) throw std::runtime_error("secp256k1_point::generator_mul - EC_POINT_mul failed."); +} + +// Sets to n*G +void secp256k1_point::set_generator_mul(const bytes_t& n) +{ + BIGNUM* bn = BN_bin2bn(&n[0], n.size(), NULL); + if (!bn) throw std::runtime_error("secp256k1_point::set_generator_mul - BN_bin2bn failed."); + + int rval = EC_POINT_mul(group, point, bn, NULL, NULL, ctx); + BN_clear_free(bn); + + if (rval == 0) throw std::runtime_error("secp256k1_point::set_generator_mul - EC_POINT_mul failed."); +} + +void secp256k1_point::init() +{ + std::string err; + + group = NULL; + point = NULL; + ctx = NULL; + + group = EC_GROUP_new_by_curve_name(NID_secp256k1); + if (!group) { + err = "EC_KEY_new_by_curve_name failed."; + goto finish; + } + + point = EC_POINT_new(group); + if (!point) { + err = "EC_POINT_new failed."; + goto finish; + } + + ctx = BN_CTX_new(); + if (!ctx) { + err = "BN_CTX_new failed."; + goto finish; + } + + return; + +finish: + if (group) EC_GROUP_free(group); + if (point) EC_POINT_free(point); + + throw std::runtime_error(std::string("secp256k1_point::init() - ") + err); +} + +bytes_t CoinCrypto::secp256k1_sigToLowS(const bytes_t& signature) +{ + const unsigned char* pvch = (const unsigned char*)&signature[0]; + ECDSA_SIG* sig = d2i_ECDSA_SIG(NULL, &pvch, signature.size()); + if (!sig) throw std::runtime_error("secp256k1_sigToLowS(): d2i_ECDSA_SIG failed."); + + BIGNUM* order = BN_bin2bn(&SECP256K1_GROUP_ORDER[0], SECP256K1_GROUP_ORDER.size(), NULL); + if (!order) + { + ECDSA_SIG_free(sig); + throw std::runtime_error("secp256k1_sigToLowS(): BN_bin2bn failed."); + } + + BIGNUM* halforder = BN_bin2bn(&SECP256K1_GROUP_HALFORDER[0], SECP256K1_GROUP_HALFORDER.size(), NULL); + if (!halforder) + { + ECDSA_SIG_free(sig); + BN_clear_free(order); + throw std::runtime_error("secp256k1_sigToLowS(): BN_bin2bn failed."); + } + + if (BN_cmp(sig->s, halforder) > 0) { BN_sub(sig->s, order, sig->s); } + + BN_clear_free(order); + BN_clear_free(halforder); + + unsigned char buffer[1024]; + unsigned char* pos = &buffer[0]; + int nSize = i2d_ECDSA_SIG(sig, &pos); + ECDSA_SIG_free(sig); + + return bytes_t(buffer, buffer + nSize); +} + +// Signing function +bytes_t CoinCrypto::secp256k1_sign(const secp256k1_key& key, const bytes_t& data) +{ + unsigned char signature[1024]; + unsigned int nSize = 0; + if (!ECDSA_sign(0, (const unsigned char*)&data[0], data.size(), signature, &nSize, key.getKey())) { + throw std::runtime_error("secp256k1_sign(): ECDSA_sign failed."); + } + return secp256k1_sigToLowS(bytes_t(signature, signature + nSize)); +} + +// Verification function +bool CoinCrypto::secp256k1_verify(const secp256k1_key& key, const bytes_t& data, const bytes_t& signature, int flags) +{ + if (flags & SIGNATURE_ENFORCE_LOW_S) + { + if (signature != secp256k1_sigToLowS(signature)) return false; + } + + int rval = ECDSA_verify(0, (const unsigned char*)&data[0], data.size(), (const unsigned char*)&signature[0], signature.size(), key.getKey()); + if (rval == -1) throw std::runtime_error("secp256k1_verify(): ECDSA_verify error."); + return (rval == 1); +} + +bytes_t CoinCrypto::secp256k1_rfc6979_k(const secp256k1_key& key, const bytes_t& data) +{ + uchar_vector hash = sha256(data); + uchar_vector v("0101010101010101010101010101010101010101010101010101010101010101"); + uchar_vector k("0000000000000000000000000000000000000000000000000000000000000000"); + uchar_vector privkey = key.getPrivKey(); + k = hmac_sha256(k, v + uchar_vector("00") + privkey + hash); + v = hmac_sha256(k, v); + k = hmac_sha256(k, v + uchar_vector("01") + privkey + hash); + v = hmac_sha256(k, v); + v = hmac_sha256(k, v); + + return v; +} + + +bytes_t CoinCrypto::secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes_t& data) +{ + bytes_t k = secp256k1_rfc6979_k(key, data); + BIGNUM* bn = BN_bin2bn(&k[0], k.size(), NULL); + if (!bn) throw std::runtime_error("secp256k1_sign_rfc6979() : BN_bin2bn failed for k."); + + BIGNUM* q = BN_bin2bn(&SECP256K1_GROUP_ORDER[0], SECP256K1_GROUP_ORDER.size(), NULL); + if (!q) + { + BN_clear_free(bn); + throw std::runtime_error("secp256k1_sign_rfc6979() : BN_bin2bn failed for field modulus."); + } + + BN_CTX* ctx = BN_CTX_new(); + if (!ctx) + { + BN_clear_free(bn); + BN_clear_free(q); + throw std::runtime_error("secp256k1_sign_rfc6979() : BN_CTX_new failed."); + } + + BIGNUM* kinv = BN_mod_inverse(NULL, bn, q, ctx); + BN_clear_free(bn); + BN_clear_free(q); + BN_CTX_free(ctx); + + if (!kinv) throw std::runtime_error("secp256k1_sign_rfc6979() : BN_mod_inverse failed."); + + unsigned char kinvbytes[32]; + assert(BN_num_bytes(kinv) <= 32); + BN_bn2bin(kinv, kinvbytes); + bytes_t kinv_(kinvbytes, kinvbytes + 32); +#ifdef TRACE_RFC6979 + std::cout << "--------------------" << std::endl << "kinv = " << uchar_vector(kinv_).getHex() << std::endl; +#endif + + secp256k1_point point; + point.set_generator_mul(k); + BIGNUM* rp = BN_new(); + if (!EC_POINT_get_affine_coordinates_GFp(point.getGroup(), point.getPoint(), rp, NULL, NULL)) + { + BN_clear_free(rp); + throw std::runtime_error("secp256k1_sign_rfc6979() : EC_POINT_get_affine_coordinates_GFp failed."); + } + + unsigned char rpbytes[32]; + assert(BN_num_bytes(rp) <= 32); + BN_bn2bin(rp, rpbytes); + bytes_t rp_(rpbytes, rpbytes + 32); +#ifdef TRACE_RFC6979 + std::cout << "--------------------" << std::endl << "rp = " << uchar_vector(rp_).getHex() << std::endl; +#endif + + unsigned char signature[1024]; + unsigned int nSize = 0; + int res = ECDSA_sign_ex(0, (const unsigned char*)&data[0], data.size(), signature, &nSize, kinv, rp, key.getKey()); + + BN_clear_free(kinv); + BN_clear_free(rp); + + if (!res) throw std::runtime_error("secp256k1_sign_rfc6979(): ECDSA_sign_ex failed."); + + return secp256k1_sigToLowS(bytes_t(signature, signature + nSize)); +} + From d61a6fe1e351332ac7949828117215100720c690 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Wed, 13 Mar 2019 01:09:38 +0300 Subject: [PATCH 22/65] gui_mod::entropy update --- keychain_cmd_app/cmd_parser.cpp | 6 +++--- keychain_cmd_app/gui_mod.cpp | 5 ++--- keychain_cmd_app/gui_mod.hpp | 2 +- keychain_lib/include/keychain_lib/keychain.hpp | 2 +- keychain_lib/include/keychain_lib/keychain_commands.hpp | 2 +- keychain_lib/include/keychain_lib/keyfile_singleton.hpp | 1 + keychain_lib/src/keyfile_singleton.cpp | 7 +++++++ 7 files changed, 16 insertions(+), 9 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 5c875c2..3a05d13 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -118,8 +118,8 @@ int cmd_parser::run(int argc, const char* const argv[]) auto it = keyfiles.begin(); if ( it==keyfiles.end() ) { - auto user_entropy = keychain_ref.entropy(); - std::string keyname = "master_key"; + auto res = keychain_ref.entropy(); + /*std::string keyname = "master_key"; std::string pass = "blank"; keyfiles.create(std::bind(create_new_keyfile, keyname, keyname, true, keyfile_format::cipher_etype::aes256, @@ -129,7 +129,7 @@ int cmd_parser::run(int argc, const char* const argv[]) std::copy(pass.begin(), pass.end(), std::back_inserter(res)); return res; }) - ); + );*/ } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); diff --git a/keychain_cmd_app/gui_mod.cpp b/keychain_cmd_app/gui_mod.cpp index 7c845ec..d79ccbf 100644 --- a/keychain_cmd_app/gui_mod.cpp +++ b/keychain_cmd_app/gui_mod.cpp @@ -21,8 +21,7 @@ dev::Public gui_mod_dummy::select_key() const return it->keyinfo.public_key; } -dev::bytes gui_mod_dummy::entropy() const +bool gui_mod_dummy::entropy() const { - dev::bytes value; - return value; + return true; } \ No newline at end of file diff --git a/keychain_cmd_app/gui_mod.hpp b/keychain_cmd_app/gui_mod.hpp index dae4486..ea518ce 100644 --- a/keychain_cmd_app/gui_mod.hpp +++ b/keychain_cmd_app/gui_mod.hpp @@ -15,7 +15,7 @@ class gui_mod_dummy: public gui_mod_base gui_mod_dummy(); virtual ~gui_mod_dummy(); virtual dev::Public select_key() const override; - virtual dev::bytes entropy() const override; + virtual bool entropy() const override; }; } diff --git a/keychain_lib/include/keychain_lib/keychain.hpp b/keychain_lib/include/keychain_lib/keychain.hpp index cbb4570..f53ae40 100644 --- a/keychain_lib/include/keychain_lib/keychain.hpp +++ b/keychain_lib/include/keychain_lib/keychain.hpp @@ -39,7 +39,7 @@ class gui_mod_base virtual ~gui_mod_base(){} virtual dev::Public select_key() const = 0; - virtual dev::bytes entropy() const = 0; + virtual bool entropy() const = 0; virtual void connect(keychain_base& keychain_) const; }; diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 3f8c920..f27621b 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -161,7 +161,7 @@ class keychain_base virtual std::string operator()(const fc_light::variant& command) = 0; boost::signals2::signal run_secmod_cmd; boost::signals2::signal select_key; - boost::signals2::signal entropy; + boost::signals2::signal entropy; dev::Secret get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 495fb88..4fcad0d 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -186,6 +186,7 @@ class keyfile_singleton void flush_keyfile(const second_key_type& key) const; // void flush_logrecords(const prim_key_type& key) const; void flush_all() const; + std::string seed_phrase(dev::bytes&); }; using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index eed6765..353c29e 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -454,6 +454,13 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( return keyfile; } +std::string keyfile_singleton::seed_phrase(dev::bytes& entropy) +{ + std::string phrase = "witch collapse practice feed shame open despair creek road again ice least"; + + return seed_phrase; +} + bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) { try { From 0a46b4a8d1c804bfd891540efd91d221eb3c782d Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Wed, 13 Mar 2019 12:46:28 +0300 Subject: [PATCH 23/65] fix seed_phrase --- keychain_lib/src/keyfile_singleton.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 353c29e..10f5f10 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -458,7 +458,7 @@ std::string keyfile_singleton::seed_phrase(dev::bytes& entropy) { std::string phrase = "witch collapse practice feed shame open despair creek road again ice least"; - return seed_phrase; + return phrase; } bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) From 65a1b9ee633c92fcbb6a42ca2ae290eb99cf813f Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Thu, 14 Mar 2019 11:58:26 +0300 Subject: [PATCH 24/65] seed generate impl --- CMakeLists.txt | 1 + keychain_lib/CMakeLists.txt | 4 +- .../keychain_lib/keyfile_singleton.hpp | 2 +- .../include/keychain_lib/wordlist.hpp | 2054 +++++++++++++++++ keychain_lib/src/keyfile_singleton.cpp | 50 +- libraries/mSIGNA/CMakeLists.txt | 20 + libraries/mSIGNA/include/BigInt.h | 4 +- libraries/mSIGNA/secp256k1_openssl.cpp | 8 +- 8 files changed, 2125 insertions(+), 18 deletions(-) create mode 100644 keychain_lib/include/keychain_lib/wordlist.hpp create mode 100644 libraries/mSIGNA/CMakeLists.txt diff --git a/CMakeLists.txt b/CMakeLists.txt index eaf7466..43441bf 100755 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,7 @@ add_subdirectory(./libraries/secp256k1_ext) add_subdirectory(./libraries/eth-crypto) add_subdirectory(./libraries/fc_light) add_subdirectory(./libraries) +add_subdirectory(./libraries/mSIGNA) diff --git a/keychain_lib/CMakeLists.txt b/keychain_lib/CMakeLists.txt index d95111f..92f3090 100644 --- a/keychain_lib/CMakeLists.txt +++ b/keychain_lib/CMakeLists.txt @@ -44,6 +44,7 @@ if( MSVC ) "${OPENSSL_ROOT_DIR}/include" ${Boost_INCLUDE_DIR} "../libraries/sqlite" + "${CMAKE_SOURCE_DIR}/libraries/mSIGNA/include" ) else ( MSVC ) include_directories( @@ -58,6 +59,7 @@ else ( MSVC ) "/usr/include/libcxxabi" ${Boost_INCLUDE_DIR} "../libraries/sqlite" + "${CMAKE_SOURCE_DIR}/libraries/mSIGNA/include" ) endif( MSVC ) @@ -67,6 +69,6 @@ file(GLOB KEYCHAIN_LIB_INCLUDE "./include/keychain_lib/*.hpp" ) list(APPEND KEYCHAIN_LIB_SOURCES "${CMAKE_CURRENT_BINARY_DIR}/git_revision.cpp") add_library(keychain_common STATIC ${KEYCHAIN_LIB_SOURCES} ${KEYCHAIN_LIB_INCLUDE}) -target_link_libraries(keychain_common kaitai_struct_cpp_stl_runtime sqlite3 cryptopp) +target_link_libraries(keychain_common kaitai_struct_cpp_stl_runtime sqlite3 cryptopp msigna) diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 5c4dba2..8f85d39 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -186,7 +186,7 @@ class keyfile_singleton void flush_keyfile(const second_key_type& key) const; // void flush_logrecords(const prim_key_type& key) const; void flush_all() const; - dev::bytes seed(dev::bytes& ); + std::vector seed(dev::bytes& ); }; using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/include/keychain_lib/wordlist.hpp b/keychain_lib/include/keychain_lib/wordlist.hpp new file mode 100644 index 0000000..3b45046 --- /dev/null +++ b/keychain_lib/include/keychain_lib/wordlist.hpp @@ -0,0 +1,2054 @@ +#ifndef WORDLIST_HPP +#define WORDLIST_HPP + +const char * wordlist [] = { + "abandon", + "ability", + "able", + "about", + "above", + "absent", + "absorb", + "abstract", + "absurd", + "abuse", + "access", + "accident", + "account", + "accuse", + "achieve", + "acid", + "acoustic", + "acquire", + "across", + "act", + "action", + "actor", + "actress", + "actual", + "adapt", + "add", + "addict", + "address", + "adjust", + "admit", + "adult", + "advance", + "advice", + "aerobic", + "affair", + "afford", + "afraid", + "again", + "age", + "agent", + "agree", + "ahead", + "aim", + "air", + "airport", + "aisle", + "alarm", + "album", + "alcohol", + "alert", + "alien", + "all", + "alley", + "allow", + "almost", + "alone", + "alpha", + "already", + "also", + "alter", + "always", + "amateur", + "amazing", + "among", + "amount", + "amused", + "analyst", + "anchor", + "ancient", + "anger", + "angle", + "angry", + "animal", + "ankle", + "announce", + "annual", + "another", + "answer", + "antenna", + "antique", + "anxiety", + "any", + "apart", + "apology", + "appear", + "apple", + "approve", + "april", + "arch", + "arctic", + "area", + "arena", + "argue", + "arm", + "armed", + "armor", + "army", + "around", + "arrange", + "arrest", + "arrive", + "arrow", + "art", + "artefact", + "artist", + "artwork", + "ask", + "aspect", + "assault", + "asset", + "assist", + "assume", + "asthma", + "athlete", + "atom", + "attack", + "attend", + "attitude", + "attract", + "auction", + "audit", + "august", + "aunt", + "author", + "auto", + "autumn", + "average", + "avocado", + "avoid", + "awake", + "aware", + "away", + "awesome", + "awful", + "awkward", + "axis", + "baby", + "bachelor", + "bacon", + "badge", + "bag", + "balance", + "balcony", + "ball", + "bamboo", + "banana", + "banner", + "bar", + "barely", + "bargain", + "barrel", + "base", + "basic", + "basket", + "battle", + "beach", + "bean", + "beauty", + "because", + "become", + "beef", + "before", + "begin", + "behave", + "behind", + "believe", + "below", + "belt", + "bench", + "benefit", + "best", + "betray", + "better", + "between", + "beyond", + "bicycle", + "bid", + "bike", + "bind", + "biology", + "bird", + "birth", + "bitter", + "black", + "blade", + "blame", + "blanket", + "blast", + "bleak", + "bless", + "blind", + "blood", + "blossom", + "blouse", + "blue", + "blur", + "blush", + "board", + "boat", + "body", + "boil", + "bomb", + "bone", + "bonus", + "book", + "boost", + "border", + "boring", + "borrow", + "boss", + "bottom", + "bounce", + "box", + "boy", + "bracket", + "brain", + "brand", + "brass", + "brave", + "bread", + "breeze", + "brick", + "bridge", + "brief", + "bright", + "bring", + "brisk", + "broccoli", + "broken", + "bronze", + "broom", + "brother", + "brown", + "brush", + "bubble", + "buddy", + "budget", + "buffalo", + "build", + "bulb", + "bulk", + "bullet", + "bundle", + "bunker", + "burden", + "burger", + "burst", + "bus", + "business", + "busy", + "butter", + "buyer", + "buzz", + "cabbage", + "cabin", + "cable", + "cactus", + "cage", + "cake", + "call", + "calm", + "camera", + "camp", + "can", + "canal", + "cancel", + "candy", + "cannon", + "canoe", + "canvas", + "canyon", + "capable", + "capital", + "captain", + "car", + "carbon", + "card", + "cargo", + "carpet", + "carry", + "cart", + "case", + "cash", + "casino", + "castle", + "casual", + "cat", + "catalog", + "catch", + "category", + "cattle", + "caught", + "cause", + "caution", + "cave", + "ceiling", + "celery", + "cement", + "census", + "century", + "cereal", + "certain", + "chair", + "chalk", + "champion", + "change", + "chaos", + "chapter", + "charge", + "chase", + "chat", + "cheap", + "check", + "cheese", + "chef", + "cherry", + "chest", + "chicken", + "chief", + "child", + "chimney", + "choice", + "choose", + "chronic", + "chuckle", + "chunk", + "churn", + "cigar", + "cinnamon", + "circle", + "citizen", + "city", + "civil", + "claim", + "clap", + "clarify", + "claw", + "clay", + "clean", + "clerk", + "clever", + "click", + "client", + "cliff", + "climb", + "clinic", + "clip", + "clock", + "clog", + "close", + "cloth", + "cloud", + "clown", + "club", + "clump", + "cluster", + "clutch", + "coach", + "coast", + "coconut", + "code", + "coffee", + "coil", + "coin", + "collect", + "color", + "column", + "combine", + "come", + "comfort", + "comic", + "common", + "company", + "concert", + "conduct", + "confirm", + "congress", + "connect", + "consider", + "control", + "convince", + "cook", + "cool", + "copper", + "copy", + "coral", + "core", + "corn", + "correct", + "cost", + "cotton", + "couch", + "country", + "couple", + "course", + "cousin", + "cover", + "coyote", + "crack", + "cradle", + "craft", + "cram", + "crane", + "crash", + "crater", + "crawl", + "crazy", + "cream", + "credit", + "creek", + "crew", + "cricket", + "crime", + "crisp", + "critic", + "crop", + "cross", + "crouch", + "crowd", + "crucial", + "cruel", + "cruise", + "crumble", + "crunch", + "crush", + "cry", + "crystal", + "cube", + "culture", + "cup", + "cupboard", + "curious", + "current", + "curtain", + "curve", + "cushion", + "custom", + "cute", + "cycle", + "dad", + "damage", + "damp", + "dance", + "danger", + "daring", + "dash", + "daughter", + "dawn", + "day", + "deal", + "debate", + "debris", + "decade", + "december", + "decide", + "decline", + "decorate", + "decrease", + "deer", + "defense", + "define", + "defy", + "degree", + "delay", + "deliver", + "demand", + "demise", + "denial", + "dentist", + "deny", + "depart", + "depend", + "deposit", + "depth", + "deputy", + "derive", + "describe", + "desert", + "design", + "desk", + "despair", + "destroy", + "detail", + "detect", + "develop", + "device", + "devote", + "diagram", + "dial", + "diamond", + "diary", + "dice", + "diesel", + "diet", + "differ", + "digital", + "dignity", + "dilemma", + "dinner", + "dinosaur", + "direct", + "dirt", + "disagree", + "discover", + "disease", + "dish", + "dismiss", + "disorder", + "display", + "distance", + "divert", + "divide", + "divorce", + "dizzy", + "doctor", + "document", + "dog", + "doll", + "dolphin", + "domain", + "donate", + "donkey", + "donor", + "door", + "dose", + "double", + "dove", + "draft", + "dragon", + "drama", + "drastic", + "draw", + "dream", + "dress", + "drift", + "drill", + "drink", + "drip", + "drive", + "drop", + "drum", + "dry", + "duck", + "dumb", + "dune", + "during", + "dust", + "dutch", + "duty", + "dwarf", + "dynamic", + "eager", + "eagle", + "early", + "earn", + "earth", + "easily", + "east", + "easy", + "echo", + "ecology", + "economy", + "edge", + "edit", + "educate", + "effort", + "egg", + "eight", + "either", + "elbow", + "elder", + "electric", + "elegant", + "element", + "elephant", + "elevator", + "elite", + "else", + "embark", + "embody", + "embrace", + "emerge", + "emotion", + "employ", + "empower", + "empty", + "enable", + "enact", + "end", + "endless", + "endorse", + "enemy", + "energy", + "enforce", + "engage", + "engine", + "enhance", + "enjoy", + "enlist", + "enough", + "enrich", + "enroll", + "ensure", + "enter", + "entire", + "entry", + "envelope", + "episode", + "equal", + "equip", + "era", + "erase", + "erode", + "erosion", + "error", + "erupt", + "escape", + "essay", + "essence", + "estate", + "eternal", + "ethics", + "evidence", + "evil", + "evoke", + "evolve", + "exact", + "example", + "excess", + "exchange", + "excite", + "exclude", + "excuse", + "execute", + "exercise", + "exhaust", + "exhibit", + "exile", + "exist", + "exit", + "exotic", + "expand", + "expect", + "expire", + "explain", + "expose", + "express", + "extend", + "extra", + "eye", + "eyebrow", + "fabric", + "face", + "faculty", + "fade", + "faint", + "faith", + "fall", + "false", + "fame", + "family", + "famous", + "fan", + "fancy", + "fantasy", + "farm", + "fashion", + "fat", + "fatal", + "father", + "fatigue", + "fault", + "favorite", + "feature", + "february", + "federal", + "fee", + "feed", + "feel", + "female", + "fence", + "festival", + "fetch", + "fever", + "few", + "fiber", + "fiction", + "field", + "figure", + "file", + "film", + "filter", + "final", + "find", + "fine", + "finger", + "finish", + "fire", + "firm", + "first", + "fiscal", + "fish", + "fit", + "fitness", + "fix", + "flag", + "flame", + "flash", + "flat", + "flavor", + "flee", + "flight", + "flip", + "float", + "flock", + "floor", + "flower", + "fluid", + "flush", + "fly", + "foam", + "focus", + "fog", + "foil", + "fold", + "follow", + "food", + "foot", + "force", + "forest", + "forget", + "fork", + "fortune", + "forum", + "forward", + "fossil", + "foster", + "found", + "fox", + "fragile", + "frame", + "frequent", + "fresh", + "friend", + "fringe", + "frog", + "front", + "frost", + "frown", + "frozen", + "fruit", + "fuel", + "fun", + "funny", + "furnace", + "fury", + "future", + "gadget", + "gain", + "galaxy", + "gallery", + "game", + "gap", + "garage", + "garbage", + "garden", + "garlic", + "garment", + "gas", + "gasp", + "gate", + "gather", + "gauge", + "gaze", + "general", + "genius", + "genre", + "gentle", + "genuine", + "gesture", + "ghost", + "giant", + "gift", + "giggle", + "ginger", + "giraffe", + "girl", + "give", + "glad", + "glance", + "glare", + "glass", + "glide", + "glimpse", + "globe", + "gloom", + "glory", + "glove", + "glow", + "glue", + "goat", + "goddess", + "gold", + "good", + "goose", + "gorilla", + "gospel", + "gossip", + "govern", + "gown", + "grab", + "grace", + "grain", + "grant", + "grape", + "grass", + "gravity", + "great", + "green", + "grid", + "grief", + "grit", + "grocery", + "group", + "grow", + "grunt", + "guard", + "guess", + "guide", + "guilt", + "guitar", + "gun", + "gym", + "habit", + "hair", + "half", + "hammer", + "hamster", + "hand", + "happy", + "harbor", + "hard", + "harsh", + "harvest", + "hat", + "have", + "hawk", + "hazard", + "head", + "health", + "heart", + "heavy", + "hedgehog", + "height", + "hello", + "helmet", + "help", + "hen", + "hero", + "hidden", + "high", + "hill", + "hint", + "hip", + "hire", + "history", + "hobby", + "hockey", + "hold", + "hole", + "holiday", + "hollow", + "home", + "honey", + "hood", + "hope", + "horn", + "horror", + "horse", + "hospital", + "host", + "hotel", + "hour", + "hover", + "hub", + "huge", + "human", + "humble", + "humor", + "hundred", + "hungry", + "hunt", + "hurdle", + "hurry", + "hurt", + "husband", + "hybrid", + "ice", + "icon", + "idea", + "identify", + "idle", + "ignore", + "ill", + "illegal", + "illness", + "image", + "imitate", + "immense", + "immune", + "impact", + "impose", + "improve", + "impulse", + "inch", + "include", + "income", + "increase", + "index", + "indicate", + "indoor", + "industry", + "infant", + "inflict", + "inform", + "inhale", + "inherit", + "initial", + "inject", + "injury", + "inmate", + "inner", + "innocent", + "input", + "inquiry", + "insane", + "insect", + "inside", + "inspire", + "install", + "intact", + "interest", + "into", + "invest", + "invite", + "involve", + "iron", + "island", + "isolate", + "issue", + "item", + "ivory", + "jacket", + "jaguar", + "jar", + "jazz", + "jealous", + "jeans", + "jelly", + "jewel", + "job", + "join", + "joke", + "journey", + "joy", + "judge", + "juice", + "jump", + "jungle", + "junior", + "junk", + "just", + "kangaroo", + "keen", + "keep", + "ketchup", + "key", + "kick", + "kid", + "kidney", + "kind", + "kingdom", + "kiss", + "kit", + "kitchen", + "kite", + "kitten", + "kiwi", + "knee", + "knife", + "knock", + "know", + "lab", + "label", + "labor", + "ladder", + "lady", + "lake", + "lamp", + "language", + "laptop", + "large", + "later", + "latin", + "laugh", + "laundry", + "lava", + "law", + "lawn", + "lawsuit", + "layer", + "lazy", + "leader", + "leaf", + "learn", + "leave", + "lecture", + "left", + "leg", + "legal", + "legend", + "leisure", + "lemon", + "lend", + "length", + "lens", + "leopard", + "lesson", + "letter", + "level", + "liar", + "liberty", + "library", + "license", + "life", + "lift", + "light", + "like", + "limb", + "limit", + "link", + "lion", + "liquid", + "list", + "little", + "live", + "lizard", + "load", + "loan", + "lobster", + "local", + "lock", + "logic", + "lonely", + "long", + "loop", + "lottery", + "loud", + "lounge", + "love", + "loyal", + "lucky", + "luggage", + "lumber", + "lunar", + "lunch", + "luxury", + "lyrics", + "machine", + "mad", + "magic", + "magnet", + "maid", + "mail", + "main", + "major", + "make", + "mammal", + "man", + "manage", + "mandate", + "mango", + "mansion", + "manual", + "maple", + "marble", + "march", + "margin", + "marine", + "market", + "marriage", + "mask", + "mass", + "master", + "match", + "material", + "math", + "matrix", + "matter", + "maximum", + "maze", + "meadow", + "mean", + "measure", + "meat", + "mechanic", + "medal", + "media", + "melody", + "melt", + "member", + "memory", + "mention", + "menu", + "mercy", + "merge", + "merit", + "merry", + "mesh", + "message", + "metal", + "method", + "middle", + "midnight", + "milk", + "million", + "mimic", + "mind", + "minimum", + "minor", + "minute", + "miracle", + "mirror", + "misery", + "miss", + "mistake", + "mix", + "mixed", + "mixture", + "mobile", + "model", + "modify", + "mom", + "moment", + "monitor", + "monkey", + "monster", + "month", + "moon", + "moral", + "more", + "morning", + "mosquito", + "mother", + "motion", + "motor", + "mountain", + "mouse", + "move", + "movie", + "much", + "muffin", + "mule", + "multiply", + "muscle", + "museum", + "mushroom", + "music", + "must", + "mutual", + "myself", + "mystery", + "myth", + "naive", + "name", + "napkin", + "narrow", + "nasty", + "nation", + "nature", + "near", + "neck", + "need", + "negative", + "neglect", + "neither", + "nephew", + "nerve", + "nest", + "net", + "network", + "neutral", + "never", + "news", + "next", + "nice", + "night", + "noble", + "noise", + "nominee", + "noodle", + "normal", + "north", + "nose", + "notable", + "note", + "nothing", + "notice", + "novel", + "now", + "nuclear", + "number", + "nurse", + "nut", + "oak", + "obey", + "object", + "oblige", + "obscure", + "observe", + "obtain", + "obvious", + "occur", + "ocean", + "october", + "odor", + "off", + "offer", + "office", + "often", + "oil", + "okay", + "old", + "olive", + "olympic", + "omit", + "once", + "one", + "onion", + "online", + "only", + "open", + "opera", + "opinion", + "oppose", + "option", + "orange", + "orbit", + "orchard", + "order", + "ordinary", + "organ", + "orient", + "original", + "orphan", + "ostrich", + "other", + "outdoor", + "outer", + "output", + "outside", + "oval", + "oven", + "over", + "own", + "owner", + "oxygen", + "oyster", + "ozone", + "pact", + "paddle", + "page", + "pair", + "palace", + "palm", + "panda", + "panel", + "panic", + "panther", + "paper", + "parade", + "parent", + "park", + "parrot", + "party", + "pass", + "patch", + "path", + "patient", + "patrol", + "pattern", + "pause", + "pave", + "payment", + "peace", + "peanut", + "pear", + "peasant", + "pelican", + "pen", + "penalty", + "pencil", + "people", + "pepper", + "perfect", + "permit", + "person", + "pet", + "phone", + "photo", + "phrase", + "physical", + "piano", + "picnic", + "picture", + "piece", + "pig", + "pigeon", + "pill", + "pilot", + "pink", + "pioneer", + "pipe", + "pistol", + "pitch", + "pizza", + "place", + "planet", + "plastic", + "plate", + "play", + "please", + "pledge", + "pluck", + "plug", + "plunge", + "poem", + "poet", + "point", + "polar", + "pole", + "police", + "pond", + "pony", + "pool", + "popular", + "portion", + "position", + "possible", + "post", + "potato", + "pottery", + "poverty", + "powder", + "power", + "practice", + "praise", + "predict", + "prefer", + "prepare", + "present", + "pretty", + "prevent", + "price", + "pride", + "primary", + "print", + "priority", + "prison", + "private", + "prize", + "problem", + "process", + "produce", + "profit", + "program", + "project", + "promote", + "proof", + "property", + "prosper", + "protect", + "proud", + "provide", + "public", + "pudding", + "pull", + "pulp", + "pulse", + "pumpkin", + "punch", + "pupil", + "puppy", + "purchase", + "purity", + "purpose", + "purse", + "push", + "put", + "puzzle", + "pyramid", + "quality", + "quantum", + "quarter", + "question", + "quick", + "quit", + "quiz", + "quote", + "rabbit", + "raccoon", + "race", + "rack", + "radar", + "radio", + "rail", + "rain", + "raise", + "rally", + "ramp", + "ranch", + "random", + "range", + "rapid", + "rare", + "rate", + "rather", + "raven", + "raw", + "razor", + "ready", + "real", + "reason", + "rebel", + "rebuild", + "recall", + "receive", + "recipe", + "record", + "recycle", + "reduce", + "reflect", + "reform", + "refuse", + "region", + "regret", + "regular", + "reject", + "relax", + "release", + "relief", + "rely", + "remain", + "remember", + "remind", + "remove", + "render", + "renew", + "rent", + "reopen", + "repair", + "repeat", + "replace", + "report", + "require", + "rescue", + "resemble", + "resist", + "resource", + "response", + "result", + "retire", + "retreat", + "return", + "reunion", + "reveal", + "review", + "reward", + "rhythm", + "rib", + "ribbon", + "rice", + "rich", + "ride", + "ridge", + "rifle", + "right", + "rigid", + "ring", + "riot", + "ripple", + "risk", + "ritual", + "rival", + "river", + "road", + "roast", + "robot", + "robust", + "rocket", + "romance", + "roof", + "rookie", + "room", + "rose", + "rotate", + "rough", + "round", + "route", + "royal", + "rubber", + "rude", + "rug", + "rule", + "run", + "runway", + "rural", + "sad", + "saddle", + "sadness", + "safe", + "sail", + "salad", + "salmon", + "salon", + "salt", + "salute", + "same", + "sample", + "sand", + "satisfy", + "satoshi", + "sauce", + "sausage", + "save", + "say", + "scale", + "scan", + "scare", + "scatter", + "scene", + "scheme", + "school", + "science", + "scissors", + "scorpion", + "scout", + "scrap", + "screen", + "script", + "scrub", + "sea", + "search", + "season", + "seat", + "second", + "secret", + "section", + "security", + "seed", + "seek", + "segment", + "select", + "sell", + "seminar", + "senior", + "sense", + "sentence", + "series", + "service", + "session", + "settle", + "setup", + "seven", + "shadow", + "shaft", + "shallow", + "share", + "shed", + "shell", + "sheriff", + "shield", + "shift", + "shine", + "ship", + "shiver", + "shock", + "shoe", + "shoot", + "shop", + "short", + "shoulder", + "shove", + "shrimp", + "shrug", + "shuffle", + "shy", + "sibling", + "sick", + "side", + "siege", + "sight", + "sign", + "silent", + "silk", + "silly", + "silver", + "similar", + "simple", + "since", + "sing", + "siren", + "sister", + "situate", + "six", + "size", + "skate", + "sketch", + "ski", + "skill", + "skin", + "skirt", + "skull", + "slab", + "slam", + "sleep", + "slender", + "slice", + "slide", + "slight", + "slim", + "slogan", + "slot", + "slow", + "slush", + "small", + "smart", + "smile", + "smoke", + "smooth", + "snack", + "snake", + "snap", + "sniff", + "snow", + "soap", + "soccer", + "social", + "sock", + "soda", + "soft", + "solar", + "soldier", + "solid", + "solution", + "solve", + "someone", + "song", + "soon", + "sorry", + "sort", + "soul", + "sound", + "soup", + "source", + "south", + "space", + "spare", + "spatial", + "spawn", + "speak", + "special", + "speed", + "spell", + "spend", + "sphere", + "spice", + "spider", + "spike", + "spin", + "spirit", + "split", + "spoil", + "sponsor", + "spoon", + "sport", + "spot", + "spray", + "spread", + "spring", + "spy", + "square", + "squeeze", + "squirrel", + "stable", + "stadium", + "staff", + "stage", + "stairs", + "stamp", + "stand", + "start", + "state", + "stay", + "steak", + "steel", + "stem", + "step", + "stereo", + "stick", + "still", + "sting", + "stock", + "stomach", + "stone", + "stool", + "story", + "stove", + "strategy", + "street", + "strike", + "strong", + "struggle", + "student", + "stuff", + "stumble", + "style", + "subject", + "submit", + "subway", + "success", + "such", + "sudden", + "suffer", + "sugar", + "suggest", + "suit", + "summer", + "sun", + "sunny", + "sunset", + "super", + "supply", + "supreme", + "sure", + "surface", + "surge", + "surprise", + "surround", + "survey", + "suspect", + "sustain", + "swallow", + "swamp", + "swap", + "swarm", + "swear", + "sweet", + "swift", + "swim", + "swing", + "switch", + "sword", + "symbol", + "symptom", + "syrup", + "system", + "table", + "tackle", + "tag", + "tail", + "talent", + "talk", + "tank", + "tape", + "target", + "task", + "taste", + "tattoo", + "taxi", + "teach", + "team", + "tell", + "ten", + "tenant", + "tennis", + "tent", + "term", + "test", + "text", + "thank", + "that", + "theme", + "then", + "theory", + "there", + "they", + "thing", + "this", + "thought", + "three", + "thrive", + "throw", + "thumb", + "thunder", + "ticket", + "tide", + "tiger", + "tilt", + "timber", + "time", + "tiny", + "tip", + "tired", + "tissue", + "title", + "toast", + "tobacco", + "today", + "toddler", + "toe", + "together", + "toilet", + "token", + "tomato", + "tomorrow", + "tone", + "tongue", + "tonight", + "tool", + "tooth", + "top", + "topic", + "topple", + "torch", + "tornado", + "tortoise", + "toss", + "total", + "tourist", + "toward", + "tower", + "town", + "toy", + "track", + "trade", + "traffic", + "tragic", + "train", + "transfer", + "trap", + "trash", + "travel", + "tray", + "treat", + "tree", + "trend", + "trial", + "tribe", + "trick", + "trigger", + "trim", + "trip", + "trophy", + "trouble", + "truck", + "true", + "truly", + "trumpet", + "trust", + "truth", + "try", + "tube", + "tuition", + "tumble", + "tuna", + "tunnel", + "turkey", + "turn", + "turtle", + "twelve", + "twenty", + "twice", + "twin", + "twist", + "two", + "type", + "typical", + "ugly", + "umbrella", + "unable", + "unaware", + "uncle", + "uncover", + "under", + "undo", + "unfair", + "unfold", + "unhappy", + "uniform", + "unique", + "unit", + "universe", + "unknown", + "unlock", + "until", + "unusual", + "unveil", + "update", + "upgrade", + "uphold", + "upon", + "upper", + "upset", + "urban", + "urge", + "usage", + "use", + "used", + "useful", + "useless", + "usual", + "utility", + "vacant", + "vacuum", + "vague", + "valid", + "valley", + "valve", + "van", + "vanish", + "vapor", + "various", + "vast", + "vault", + "vehicle", + "velvet", + "vendor", + "venture", + "venue", + "verb", + "verify", + "version", + "very", + "vessel", + "veteran", + "viable", + "vibrant", + "vicious", + "victory", + "video", + "view", + "village", + "vintage", + "violin", + "virtual", + "virus", + "visa", + "visit", + "visual", + "vital", + "vivid", + "vocal", + "voice", + "void", + "volcano", + "volume", + "vote", + "voyage", + "wage", + "wagon", + "wait", + "walk", + "wall", + "walnut", + "want", + "warfare", + "warm", + "warrior", + "wash", + "wasp", + "waste", + "water", + "wave", + "way", + "wealth", + "weapon", + "wear", + "weasel", + "weather", + "web", + "wedding", + "weekend", + "weird", + "welcome", + "west", + "wet", + "whale", + "what", + "wheat", + "wheel", + "when", + "where", + "whip", + "whisper", + "wide", + "width", + "wife", + "wild", + "will", + "win", + "window", + "wine", + "wing", + "wink", + "winner", + "winter", + "wire", + "wisdom", + "wise", + "wish", + "witness", + "wolf", + "woman", + "wonder", + "wood", + "wool", + "word", + "work", + "world", + "worry", + "worth", + "wrap", + "wreck", + "wrestle", + "wrist", + "write", + "wrong", + "yard", + "year", + "yellow", + "you", + "young", + "youth", + "zebra", + "zero", + "zone", + "zoo" +}; +#endif //WORDLIST_HPP" diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 328daba..1539b36 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -6,6 +6,8 @@ #include "keyfile_singleton.hpp" #include #include +#include "hdkeys.h" +#include "wordlist.hpp" using namespace keychain_app; @@ -456,26 +458,50 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( return keyfile; } -dev::bytes keyfile_singleton::seed(dev::bytes& user_entropy) +std::vector keyfile_singleton::seed(dev::bytes& user_entropy) { - using namespace CryptoPP; - SecByteBlock key(32); - std::string k; + CryptoPP::SecByteBlock ent(16); + CryptoPP::OS_GenerateRandomBlock(false, ent, ent.size()); - OS_GenerateRandomBlock(false, key, k.size()); + auto sha256 = fc_light::sha256::hash( (const char *) ent.begin(), ent.SizeInBytes() ); + char cs = *sha256.data()&0x0f; - HexEncoder hex(new StringSink(k)); - hex.Put(key, key.size()); - hex.MessageEnd(); + std::vector ent_cs(ent.begin(), ent.begin()+ent.SizeInBytes()); + ent_cs.push_back(cs); - dev::bytes seed(32); - auto res = from_hex(k, seed.data(), seed.size()); - seed.resize(res); + size_t ms_len = ent_cs.size()*8/11; - return seed; + std::vector ms; + auto pbyte = ent_cs.data(); + char bit = 0; + for (auto i=0; i>bit)&1; + res = res | (val< mnemonics; + for(auto a : ms) + { + FC_LIGHT_ASSERT (a < wordlist_size); + mnemonics.push_back(wordlist[a]); + } + + return mnemonics; } + bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) { try { diff --git a/libraries/mSIGNA/CMakeLists.txt b/libraries/mSIGNA/CMakeLists.txt new file mode 100644 index 0000000..ddd70f2 --- /dev/null +++ b/libraries/mSIGNA/CMakeLists.txt @@ -0,0 +1,20 @@ +set(CMAKE_CXX_FLAGS "-std=c++14") + +if(MSVC) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /EHsc" ) + # set( CMAKE_VS_PLATFORM_TOOLSET "LLVM-vs2017") +endif() + +if (NOT MSVC) + if ( LIBCXX_BUILD ) + set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -stdlib=libc++" ) + endif() +endif() + +include_directories("${CMAKE_SOURCE_DIR}/libraries/mSIGNA/include") + +file(GLOB MSIGNA_HEADERS "./include/*.h") +file(GLOB MSIGNA_SOURCES "*.cpp" ) + + +add_library( msigna ${MSIGNA_SOURCES} ${MSIGNA_HEADERS} ) diff --git a/libraries/mSIGNA/include/BigInt.h b/libraries/mSIGNA/include/BigInt.h index 2c061cf..c686837 100644 --- a/libraries/mSIGNA/include/BigInt.h +++ b/libraries/mSIGNA/include/BigInt.h @@ -104,7 +104,7 @@ class BigInt const BigInt operator-(BN_ULONG rightOperand) const { return BigInt(*this) -= rightOperand; } const BigInt operator*(BN_ULONG rightOperand) const { return BigInt(*this) *= rightOperand; } const BigInt operator/(BN_ULONG rightOperand) const { return BigInt(*this) /= rightOperand; } - BN_LONG operator%(BN_ULONG rightOperand) const { return BN_mod_word(this->bn, rightOperand); } +// BN_LONG operator%(BN_ULONG rightOperand) const { return BN_mod_word(this->bn, rightOperand); } // Bitshift Operators BigInt& operator<<=(int rhs) { if (!BN_lshift(this->bn, this->bn, rhs)) throw std::runtime_error("BN_lshift error."); return *this; } @@ -163,6 +163,7 @@ class BigInt } void setDec(const std::string& dec) { BN_dec2bn(&this->bn, dec.c_str()); } +/* std::string getInBase(unsigned int base, const char* alphabet) const { BigInt num = *this; @@ -173,6 +174,7 @@ class BigInt } while (!num.isZero()); return inBase; } +*/ void setInBase(const std::string& inBase, unsigned int base, const char* alphabet) { diff --git a/libraries/mSIGNA/secp256k1_openssl.cpp b/libraries/mSIGNA/secp256k1_openssl.cpp index 20608b7..9f11e9f 100644 --- a/libraries/mSIGNA/secp256k1_openssl.cpp +++ b/libraries/mSIGNA/secp256k1_openssl.cpp @@ -315,8 +315,7 @@ void secp256k1_point::init() if (point) EC_POINT_free(point); throw std::runtime_error(std::string("secp256k1_point::init() - ") + err); -} - +}/* bytes_t CoinCrypto::secp256k1_sigToLowS(const bytes_t& signature) { const unsigned char* pvch = (const unsigned char*)&signature[0]; @@ -337,7 +336,7 @@ bytes_t CoinCrypto::secp256k1_sigToLowS(const bytes_t& signature) BN_clear_free(order); throw std::runtime_error("secp256k1_sigToLowS(): BN_bin2bn failed."); } - + if (BN_cmp(sig->s, halforder) > 0) { BN_sub(sig->s, order, sig->s); } BN_clear_free(order); @@ -350,6 +349,9 @@ bytes_t CoinCrypto::secp256k1_sigToLowS(const bytes_t& signature) return bytes_t(buffer, buffer + nSize); } +*/ + + // Signing function bytes_t CoinCrypto::secp256k1_sign(const secp256k1_key& key, const bytes_t& data) From 0190d5db2889984022b66aca45f29e395f8a07df Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Thu, 14 Mar 2019 17:47:15 +0300 Subject: [PATCH 25/65] call gui_mod::entropy from select_key functor --- keychain_lib/include/keychain_lib/keychain_commands.hpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index f27621b..bfc1c50 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -321,7 +321,14 @@ struct keychain_command: keychain_command_base using params_t = void; virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override { - auto public_key = *keychain->select_key(); + auto& keyfiles = keyfile_singleton::instance(); + auto it = keyfiles.begin(); + if ( it==keyfiles.end() ) + { + auto res = keychain->entropy(); + } + + auto public_key = *keychain->select_key(); if(!public_key) FC_LIGHT_THROW_EXCEPTION(fc_light::public_key_not_selected, ""); json_response response(to_hex(public_key.data(), public_key.size).c_str(), id); From c795e0c92a77f09cb0de03bec4293eec7e6543ce Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Fri, 15 Mar 2019 01:59:51 +0300 Subject: [PATCH 26/65] master_key impl --- keychain_cmd_app/cmd_parser.cpp | 16 ++++++++++++++-- keychain_cmd_app/gui_mod.cpp | 6 +++--- keychain_cmd_app/gui_mod.hpp | 2 +- keychain_lib/include/keychain_lib/keychain.hpp | 2 +- .../include/keychain_lib/keychain_commands.hpp | 2 +- .../include/keychain_lib/keyfile_singleton.hpp | 2 ++ keychain_lib/src/keyfile_singleton.cpp | 18 ++++++++++++++++++ 7 files changed, 40 insertions(+), 8 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 9d3ca00..d204b4b 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -118,8 +118,19 @@ int cmd_parser::run(int argc, const char* const argv[]) auto it = keyfiles.begin(); if ( it==keyfiles.end() ) { - auto user_entropy = std::move(*(keychain_ref.entropy())); - auto seed_hex = std::move(keyfiles.seed(user_entropy)); + auto res = keychain_ref.entropy(); + dev::bytes ue; + auto mnemonics = std::move(keyfiles.seed(ue)); + std::string mnemonic_join; + for (auto& a : mnemonics) + mnemonic_join += a; + + dev::bytes salt; + auto key = std::move(keyfiles.pbkdf2(mnemonic_join, salt, 2048, 64 )); + + dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + dev::Secret chain_code(dev::FixedHash<32>((byte * const)key.data()+32, dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + /* std::string keyname = "master_key"; std::string pass = "blank"; keyfiles.create(std::bind(create_new_keyfile, @@ -131,6 +142,7 @@ int cmd_parser::run(int argc, const char* const argv[]) return res; }) ); +*/ } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); diff --git a/keychain_cmd_app/gui_mod.cpp b/keychain_cmd_app/gui_mod.cpp index 7c845ec..bbe9a5e 100644 --- a/keychain_cmd_app/gui_mod.cpp +++ b/keychain_cmd_app/gui_mod.cpp @@ -21,8 +21,8 @@ dev::Public gui_mod_dummy::select_key() const return it->keyinfo.public_key; } -dev::bytes gui_mod_dummy::entropy() const + +bool gui_mod_dummy::entropy() const { - dev::bytes value; - return value; + return true; } \ No newline at end of file diff --git a/keychain_cmd_app/gui_mod.hpp b/keychain_cmd_app/gui_mod.hpp index dae4486..ea518ce 100644 --- a/keychain_cmd_app/gui_mod.hpp +++ b/keychain_cmd_app/gui_mod.hpp @@ -15,7 +15,7 @@ class gui_mod_dummy: public gui_mod_base gui_mod_dummy(); virtual ~gui_mod_dummy(); virtual dev::Public select_key() const override; - virtual dev::bytes entropy() const override; + virtual bool entropy() const override; }; } diff --git a/keychain_lib/include/keychain_lib/keychain.hpp b/keychain_lib/include/keychain_lib/keychain.hpp index cbb4570..f53ae40 100644 --- a/keychain_lib/include/keychain_lib/keychain.hpp +++ b/keychain_lib/include/keychain_lib/keychain.hpp @@ -39,7 +39,7 @@ class gui_mod_base virtual ~gui_mod_base(){} virtual dev::Public select_key() const = 0; - virtual dev::bytes entropy() const = 0; + virtual bool entropy() const = 0; virtual void connect(keychain_base& keychain_) const; }; diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 3f8c920..f27621b 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -161,7 +161,7 @@ class keychain_base virtual std::string operator()(const fc_light::variant& command) = 0; boost::signals2::signal run_secmod_cmd; boost::signals2::signal select_key; - boost::signals2::signal entropy; + boost::signals2::signal entropy; dev::Secret get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 8f85d39..5cd53a9 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -187,6 +187,8 @@ class keyfile_singleton // void flush_logrecords(const prim_key_type& key) const; void flush_all() const; std::vector seed(dev::bytes& ); + std::vector pbkdf2(std::string const& _pass, dev::bytes const& _salt, unsigned _iterations, unsigned _dkLen); + }; using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 1539b36..c645d27 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -6,6 +6,7 @@ #include "keyfile_singleton.hpp" #include #include +#include #include "hdkeys.h" #include "wordlist.hpp" @@ -500,6 +501,23 @@ std::vector keyfile_singleton::seed(dev::bytes& user_entropy) return mnemonics; } +std::vector keyfile_singleton::pbkdf2(std::string const& _pass, dev::bytes const& _salt, unsigned _iterations, unsigned _dkLen) +{ + std::vector ret(_dkLen); + if (CryptoPP::PKCS5_PBKDF2_HMAC().DeriveKey( + (unsigned char *) ret.data(), + _dkLen, + 0, + reinterpret_cast(_pass.data()), + _pass.size(), + _salt.data(), + _salt.size(), + _iterations + ) != _iterations) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Key derivation failed."); + + return ret; +} bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) From 56502875cd340f9f25654a9302a08343589d50e8 Mon Sep 17 00:00:00 2001 From: Avvrik <34011337+Avvrik@users.noreply.github.com> Date: Fri, 15 Mar 2019 12:03:58 +0300 Subject: [PATCH 27/65] Update README.md --- README.md | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 17265ac..5ad028e 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@              [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=A%20good,%20solid%20app%20to%20keep%20your%20keys%20safe.&url=https://keychain.array.io/&via=ProjectArray&hashtags=cybersecurity,private,cryptography,blockchain,app) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-orange.svg)](https://github.com/arrayio/array-io-keychain#contributing-to-the-project) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/arrayio/array-io-keychain/blob/master/LICENSE.md) [![npm version](https://badge.fury.io/js/web3override.svg)](https://badge.fury.io/js/web3override) -

» Download for macOS «

+

» Download for macOS «

» Documentation «

@@ -34,7 +34,7 @@ ## Installation -Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.20/KeyChain.Installer.zip). Windows and Linux installers are coming soon. +Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.21/KeyChain.Installer.zip). Windows and Linux installers are coming soon. *Try out KeyChain on the [demo page](https://arrayio.github.io/array-io-keychain/demo/).* @@ -48,7 +48,7 @@ You can find a comprehensive installation guide for [macOS](https://github.com/a ## Getting started -After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.20/KeyChain.Installer.zip), you can start using it with web3. Just follow these simple steps. +After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.21/KeyChain.Installer.zip), you can start using it with web3. Just follow these simple steps. NB: If you launch KeyChain for the first time, you need to get a public key with the "select_key" command. You can save the public key to local storage. Then you will not need to use "select_key" command again. @@ -110,6 +110,7 @@ There you will find: - [KeyChain Protocol](https://github.com/arrayio/array-io-keychain/wiki/KeyChain-Protocol): full comprehensive descriptions of the KeyChain commands. - [KeyChain sample commands](https://github.com/arrayio/array-io-keychain/wiki/KeyChain-sample-commands): shortcut to using the commands. - [Pipe API](https://github.com/arrayio/array-io-keychain/wiki/Pipe-API): integrating KeyChain through pipe. +- [Restore your keys with master key](https://github.com/arrayio/array-io-keychain/wiki/Restore-your-keys-with-master-key) - [Security](https://github.com/arrayio/array-io-keychain/wiki/Security): why KeyChain is highly secure. - [Troubleshooting](https://github.com/arrayio/array-io-keychain/wiki/Troubleshooting): error handling, log files, debugging. - [Useful reference](https://github.com/arrayio/array-io-keychain/wiki/Useful-reference): external links. From 17b62466b5b90dcf922528c2a168ac7599059c64 Mon Sep 17 00:00:00 2001 From: Avvrik <34011337+Avvrik@users.noreply.github.com> Date: Fri, 15 Mar 2019 14:59:19 +0300 Subject: [PATCH 28/65] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 5ad028e..da6bd35 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,7 @@              [![Tweet](https://img.shields.io/twitter/url/http/shields.io.svg?style=social)](https://twitter.com/intent/tweet?text=A%20good,%20solid%20app%20to%20keep%20your%20keys%20safe.&url=https://keychain.array.io/&via=ProjectArray&hashtags=cybersecurity,private,cryptography,blockchain,app) [![Contributions welcome](https://img.shields.io/badge/contributions-welcome-orange.svg)](https://github.com/arrayio/array-io-keychain#contributing-to-the-project) [![License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/arrayio/array-io-keychain/blob/master/LICENSE.md) [![npm version](https://badge.fury.io/js/web3override.svg)](https://badge.fury.io/js/web3override) -

» Download for macOS «

+

» Download for macOS «

» Documentation «

@@ -34,7 +34,7 @@ ## Installation -Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.21/KeyChain.Installer.zip). Windows and Linux installers are coming soon. +Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.24/KeyChain.Installer.zip). Windows and Linux installers are coming soon. *Try out KeyChain on the [demo page](https://arrayio.github.io/array-io-keychain/demo/).* @@ -48,7 +48,7 @@ You can find a comprehensive installation guide for [macOS](https://github.com/a ## Getting started -After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.21/KeyChain.Installer.zip), you can start using it with web3. Just follow these simple steps. +After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain/releases/download/0.24/KeyChain.Installer.zip), you can start using it with web3. Just follow these simple steps. NB: If you launch KeyChain for the first time, you need to get a public key with the "select_key" command. You can save the public key to local storage. Then you will not need to use "select_key" command again. From 10f74f2a76e1cfd6b5c32b1f5bf7010e7e792ef7 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Fri, 15 Mar 2019 18:48:37 +0300 Subject: [PATCH 29/65] add parse_trx --- .../include/keychain_lib/keychain_commands.hpp | 1 + keychain_lib/src/keychain_commands.cpp | 14 ++++++++++++++ 2 files changed, 15 insertions(+) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index bfc1c50..e21bdf9 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -94,6 +94,7 @@ enum struct sign_te { fc_light::variant create_secmod_signhex_cmd(const std::vector& raw, blockchain_te blockchain, std::string from, int unlock_time, const std::string& keyname, bool no_password); fc_light::variant create_secmod_signhash_cmd(const std::string& raw, std::string from, const std::string& keyname, bool no_password); fc_light::variant create_secmod_unlock_cmd(const std::string& keyname, int unlock_time, bool no_password); +std::string parse_trx(std::string&); class streambuf_derived : public std::basic_streambuf { diff --git a/keychain_lib/src/keychain_commands.cpp b/keychain_lib/src/keychain_commands.cpp index cbd4b75..50ee9af 100644 --- a/keychain_lib/src/keychain_commands.cpp +++ b/keychain_lib/src/keychain_commands.cpp @@ -251,6 +251,20 @@ dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int un return result_secret; } +std::string parse_trx(std::string& trx) +{ + namespace sm_cmd = keychain_app::secmod_commands; + std::vector raw(trx.length()); + auto res = keychain_app::from_hex(trx, raw.data(), raw.size()); + raw.resize(res); + + auto cmd = create_secmod_signhex_cmd(raw, blockchain_te::ethereum, "", 0, "", false); + auto params = cmd.as().params; + auto sing_trx_params = params.as::params_t>(); + auto trx_view = sing_trx_params.trx_view; + return fc_light::json::to_pretty_string(trx_view); +} + } using namespace keychain_app; From 1db61f31cecf0bf6a3b8cd206478b1dee3075480 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Fri, 15 Mar 2019 22:12:29 +0300 Subject: [PATCH 30/65] add keydata_singleton --- keychain_cmd_app/cmd_parser.cpp | 27 ----- keychain_cmd_app/gui_mod.cpp | 3 +- .../keychain_lib/keychain_commands.hpp | 31 +++-- .../keychain_lib/keydata_singleton.cpp | 113 ++++++++++++++++++ .../keychain_lib/keydata_singleton.hpp | 27 +++++ .../keychain_lib/keyfile_singleton.hpp | 2 - keychain_lib/src/keyfile_singleton.cpp | 66 ---------- 7 files changed, 160 insertions(+), 109 deletions(-) create mode 100644 keychain_lib/include/keychain_lib/keydata_singleton.cpp create mode 100644 keychain_lib/include/keychain_lib/keydata_singleton.hpp diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index d204b4b..84b17ce 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -35,7 +35,6 @@ using namespace keychain_app; - cmd_parser::cmd_parser() { //TODO: define program options @@ -117,33 +116,7 @@ int cmd_parser::run(int argc, const char* const argv[]) auto& keyfiles = keyfile_singleton::instance(); auto it = keyfiles.begin(); if ( it==keyfiles.end() ) - { auto res = keychain_ref.entropy(); - dev::bytes ue; - auto mnemonics = std::move(keyfiles.seed(ue)); - std::string mnemonic_join; - for (auto& a : mnemonics) - mnemonic_join += a; - - dev::bytes salt; - auto key = std::move(keyfiles.pbkdf2(mnemonic_join, salt, 2048, 64 )); - - dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); - dev::Secret chain_code(dev::FixedHash<32>((byte * const)key.data()+32, dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); - /* - std::string keyname = "master_key"; - std::string pass = "blank"; - keyfiles.create(std::bind(create_new_keyfile, - keyname, keyname, true, keyfile_format::cipher_etype::aes256, - keyfile_format::curve_etype::secp256k1, - [&pass](const std::string& keyname)->byte_seq_t{ - byte_seq_t res; - std::copy(pass.begin(), pass.end(), std::back_inserter(res)); - return res; - }) -); -*/ - } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); pipeline_parser pipe_line_parser_(std::move(f), fileno(stdin), fileno(stdout)); diff --git a/keychain_cmd_app/gui_mod.cpp b/keychain_cmd_app/gui_mod.cpp index bbe9a5e..8c3a958 100644 --- a/keychain_cmd_app/gui_mod.cpp +++ b/keychain_cmd_app/gui_mod.cpp @@ -1,4 +1,4 @@ -// + // // Created by roman on 5/14/18. // @@ -21,7 +21,6 @@ dev::Public gui_mod_dummy::select_key() const return it->keyinfo.public_key; } - bool gui_mod_dummy::entropy() const { return true; diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index f27621b..1830b29 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -217,7 +217,7 @@ struct json_error { json_error(int id_, fc_light::exception_code_te err_code, const std::string& msg_ = "", const fc_light::variant& trace_ = fc_light::variant()) : id(id_), error(err_code, msg_, trace_){} - + int id; struct error_t { @@ -288,9 +288,9 @@ struct keychain_command: keychain_command_base { keychain_command() : keychain_command_base(command_te::list) {} virtual ~keychain_command() {} - + using params_t = void; - + virtual std::string operator()(keychain_base *keychain, const fc_light::variant ¶ms_variant, int id) const override { json_response response(fc_light::variant(version_info::about()), id); @@ -303,9 +303,9 @@ struct keychain_command: keychain_command_base { keychain_command() : keychain_command_base(command_te::list) {} virtual ~keychain_command() {} - + using params_t = void; - + virtual std::string operator()(keychain_base *keychain, const fc_light::variant ¶ms_variant, int id) const override { json_response response(fc_light::variant(version_info::version()), id); @@ -321,7 +321,14 @@ struct keychain_command: keychain_command_base using params_t = void; virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override { - auto public_key = *keychain->select_key(); + auto& keyfiles = keyfile_singleton::instance(); + auto it = keyfiles.begin(); + if ( it==keyfiles.end() ) + { + auto res = keychain->entropy(); + } + + auto public_key = *keychain->select_key(); if(!public_key) FC_LIGHT_THROW_EXCEPTION(fc_light::public_key_not_selected, ""); json_response response(to_hex(public_key.data(), public_key.size).c_str(), id); @@ -343,7 +350,7 @@ struct keychain_command : keychain_command_base int unlock_time; }; using params_t = params; - + virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override { params_t params; @@ -372,7 +379,7 @@ struct keychain_command : keychain_command_base if (!params.public_key) FC_LIGHT_THROW_EXCEPTION(fc_light::invalid_arg_exception, "public_key is not specified"); - + auto evaluate_from = [¶ms]()->std::string { switch (params.blockchain_type) { @@ -388,16 +395,16 @@ struct keychain_command : keychain_command_base pub_bin_key.insert(pub_bin_key.begin(), 4); auto sha256 = fc_light::sha256::hash( (const char*)pub_bin_key.data(), pub_bin_key.size() ); auto ripemd160 = fc_light::ripemd160::hash( sha256 ); - + std::vector keyhash(ripemd160.data(), ripemd160.data()+ripemd160.data_size()); keyhash.insert(keyhash.begin(), 0); - + sha256 = fc_light::sha256::hash( keyhash.data(), keyhash.size() ); auto checksum = fc_light::sha256::hash( sha256.data(), sha256.data_size() ); - + std::vector addr (checksum.data(), checksum.data()+4 ); addr.insert(addr.begin(), keyhash.begin(), keyhash.end()); - + return fc_light::to_base58(addr.data(), addr.size()); } default: diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.cpp b/keychain_lib/include/keychain_lib/keydata_singleton.cpp new file mode 100644 index 0000000..14dc259 --- /dev/null +++ b/keychain_lib/include/keychain_lib/keydata_singleton.cpp @@ -0,0 +1,113 @@ +// +// Created by user on 3/15/19. +// +#include "keydata_singleton.hpp" +#include +#include +#include +#include "hdkeys.h" +#include "wordlist.hpp" +#include + +using namespace keychain_app; + +keydata_singleton& keydata_singleton::instance() +{ + static keydata_singleton instance; + return instance; +} + +std::string keydata_singleton::seed(dev::bytes& user_entropy) +{ + CryptoPP::SecByteBlock ent(16); + CryptoPP::OS_GenerateRandomBlock(false, ent, ent.size()); + + auto sha256 = fc_light::sha256::hash( (const char *) ent.begin(), ent.SizeInBytes() ); + char cs = *sha256.data()&0x0f; + + std::vector ent_cs(ent.begin(), ent.begin()+ent.SizeInBytes()); + ent_cs.push_back(cs); + + size_t ms_len = ent_cs.size()*8/11; + + std::vector ms; + auto pbyte = ent_cs.data(); + char bit = 0; + for (auto i=0; i>bit)&1; + res = res | (val< mnemonics; + for(auto a : ms) + { + FC_LIGHT_ASSERT (a < wordlist_size); + mnemonics.push_back(wordlist[a]); + } + + std::string res; + for (auto& a:mnemonics) + res +=a + " "; + return res; +} + + +std::vector keydata_singleton::pbkdf2(std::string const& _pass) +{ + unsigned _iterations = 2048; + unsigned _dkLen = 64; + dev::bytes const _salt; + std::vector ret(_dkLen); + if (CryptoPP::PKCS5_PBKDF2_HMAC().DeriveKey( + (unsigned char *) ret.data(), + _dkLen, + 0, + reinterpret_cast(_pass.data()), + _pass.size(), + _salt.data(), + _salt.size(), + _iterations + ) != _iterations) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Key derivation failed."); + + return ret; +} + + +void keydata_singleton::create_masterkey(std::string& mnemonics) +{ + std::vector key = std::move(pbkdf2(mnemonics)); + dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + dev::Secret chain_code(dev::FixedHash<32>((byte * const)key.data()+32, dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + +} + + +void keydata_singleton::create_privatekey() +{ +// Coin::HDkeychain hd(bytes_t(master_key.begin(), master_key.end()), bytes_t(chain_code.begin(), chain_code.end())); +/* + std::string keyname = ""; + std::string pass = "blank"; + keyfiles.create(std::bind(create_new_keyfile, + keyname, keyname, true, keyfile_format::cipher_etype::aes256, + keyfile_format::curve_etype::secp256k1, + [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }) +); +*/ +} \ No newline at end of file diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp new file mode 100644 index 0000000..5820a97 --- /dev/null +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -0,0 +1,27 @@ +// +// Created by user on 3/15/19. +// + +#ifndef KEYCHAINAPP_KEYDATA_SINGLETON_HPP +#define KEYCHAINAPP_KEYDATA_SINGLETON_HPP + +#include + +namespace keychain_app { + +struct keydata_singleton +{ + static keydata_singleton& instance(); + std::string seed(dev::bytes& ); + void create_masterkey(std::string&); + void create_privatekey(); + +private: + keydata_singleton(){} + ~keydata_singleton(){} + std::vector pbkdf2(std::string const& _pass); +}; + +} + +#endif //KEYCHAINAPP_KEYDATA_SINGLETON_HPP diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 5cd53a9..8a27db2 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -186,8 +186,6 @@ class keyfile_singleton void flush_keyfile(const second_key_type& key) const; // void flush_logrecords(const prim_key_type& key) const; void flush_all() const; - std::vector seed(dev::bytes& ); - std::vector pbkdf2(std::string const& _pass, dev::bytes const& _salt, unsigned _iterations, unsigned _dkLen); }; diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index c645d27..eed6765 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -4,11 +4,6 @@ #include "keychain_commands.hpp" #include "keyfile_singleton.hpp" -#include -#include -#include -#include "hdkeys.h" -#include "wordlist.hpp" using namespace keychain_app; @@ -459,67 +454,6 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( return keyfile; } -std::vector keyfile_singleton::seed(dev::bytes& user_entropy) -{ - CryptoPP::SecByteBlock ent(16); - CryptoPP::OS_GenerateRandomBlock(false, ent, ent.size()); - - auto sha256 = fc_light::sha256::hash( (const char *) ent.begin(), ent.SizeInBytes() ); - char cs = *sha256.data()&0x0f; - - std::vector ent_cs(ent.begin(), ent.begin()+ent.SizeInBytes()); - ent_cs.push_back(cs); - - size_t ms_len = ent_cs.size()*8/11; - - std::vector ms; - auto pbyte = ent_cs.data(); - char bit = 0; - for (auto i=0; i>bit)&1; - res = res | (val< mnemonics; - for(auto a : ms) - { - FC_LIGHT_ASSERT (a < wordlist_size); - mnemonics.push_back(wordlist[a]); - } - - return mnemonics; -} - -std::vector keyfile_singleton::pbkdf2(std::string const& _pass, dev::bytes const& _salt, unsigned _iterations, unsigned _dkLen) -{ - std::vector ret(_dkLen); - if (CryptoPP::PKCS5_PBKDF2_HMAC().DeriveKey( - (unsigned char *) ret.data(), - _dkLen, - 0, - reinterpret_cast(_pass.data()), - _pass.size(), - _salt.data(), - _salt.size(), - _iterations - ) != _iterations) - FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Key derivation failed."); - - return ret; -} - - bool keychain_app::remove_unlock(const keyfile_format::keyfile_t& keyfile, get_password_f&& get_passwd) { try { From 2c392ebbd56c3c941646d545a7b6f6b1336d6159 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Sat, 16 Mar 2019 01:31:41 +0300 Subject: [PATCH 31/65] fix merge --- keychain_cmd_app/cmd_parser.cpp | 12 +++++++++++- .../include/keychain_lib/keydata_singleton.hpp | 2 +- .../include/keychain_lib/keyfile_singleton.hpp | 4 +++- .../keychain_lib => src}/keydata_singleton.cpp | 17 ++++++++++++++--- 4 files changed, 29 insertions(+), 6 deletions(-) rename keychain_lib/{include/keychain_lib => src}/keydata_singleton.cpp (80%) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 84b17ce..6b13cf5 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -17,6 +17,8 @@ #include #include +#include + //#include //#include @@ -116,7 +118,15 @@ int cmd_parser::run(int argc, const char* const argv[]) auto& keyfiles = keyfile_singleton::instance(); auto it = keyfiles.begin(); if ( it==keyfiles.end() ) - auto res = keychain_ref.entropy(); + { + auto res = keychain_ref.entropy(); +/* auto& key_data = keydata_singleton::instance(); + dev::bytes ue; + auto mnemonics = std::move(key_data.seed(ue)); + std::string pass("blank"); + key_data.create_masterkey(mnemonics,pass); + key_data.create_privatekey();*/ + } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); pipeline_parser pipe_line_parser_(std::move(f), fileno(stdin), fileno(stdout)); diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index 5820a97..0ca4bf7 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -13,7 +13,7 @@ struct keydata_singleton { static keydata_singleton& instance(); std::string seed(dev::bytes& ); - void create_masterkey(std::string&); + void create_masterkey(std::string&, std::string&); void create_privatekey(); private: diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 8a27db2..3fceffa 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -12,10 +12,12 @@ #include #include #include +#include #include #include "keyfile_parser.hpp" +#include "secmod_protocol.hpp" namespace keychain_app { @@ -189,7 +191,7 @@ class keyfile_singleton }; -using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string +using get_password_create_f = std::function; //NOTE: may incapsulate call to sec module or just return password string keyfile_format::keyfile_t create_new_keyfile( const std::string& keyname, diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp similarity index 80% rename from keychain_lib/include/keychain_lib/keydata_singleton.cpp rename to keychain_lib/src/keydata_singleton.cpp index 14dc259..fe73d24 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -1,13 +1,14 @@ // // Created by user on 3/15/19. // -#include "keydata_singleton.hpp" #include #include #include #include "hdkeys.h" -#include "wordlist.hpp" +#include #include +#include +#include using namespace keychain_app; @@ -85,12 +86,22 @@ std::vector keydata_singleton::pbkdf2(std::string const& _pass) } -void keydata_singleton::create_masterkey(std::string& mnemonics) +void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pass) { std::vector key = std::move(pbkdf2(mnemonics)); dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); dev::Secret chain_code(dev::FixedHash<32>((byte * const)key.data()+32, dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + auto & keyfiles = keyfile_singleton::instance(); + keyfiles.create(std::bind(create_new_keyfile, + "master_key", "master_key", true, keyfile_format::cipher_etype::aes256, + keyfile_format::curve_etype::secp256k1, + [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }) + ); } From 0dcbe8b2c9b59aeadefa3dce2d01017dffac75cb Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Mon, 18 Mar 2019 13:07:08 +0300 Subject: [PATCH 32/65] add chain_code to keyfile --- .../include/keychain_lib/keychain_commands.hpp | 8 ++++---- .../include/keychain_lib/keyfile_parser.hpp | 3 ++- .../include/keychain_lib/private_keymap.hpp | 3 ++- keychain_lib/src/keychain_commands.cpp | 17 ++++++++++++----- keychain_lib/src/private_keymap.cpp | 3 ++- 5 files changed, 22 insertions(+), 12 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 417e0e0..9ca7acc 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -164,7 +164,7 @@ class keychain_base boost::signals2::signal select_key; boost::signals2::signal entropy; - dev::Secret get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); + std::pair get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); protected: keychain_base(); @@ -418,7 +418,7 @@ struct keychain_command : keychain_command_base { return fc_light::json::to_string( create_secmod_signhex_cmd(raw, params.blockchain_type, evaluate_from(), params.unlock_time, keyname, no_password)); - }, secmod_signhex_cmd); + }, secmod_signhex_cmd).first; auto reply = [&keyfiles, ¶ms, &id, &secmod_signhex_cmd](auto& message, const dev::bytes& transaction){ keyfiles.add_log_record(params.public_key, @@ -639,7 +639,7 @@ struct keychain_command : keychain_command_base { return fc_light::json::to_string( create_secmod_signhash_cmd(params.hash, evaluate_from(), keyname, no_password)); - }, secmod_signhash_cmd); + }, secmod_signhash_cmd).first; //NOTE: using vector instead array because move semantic is implemented in the vector std::vector hash(params.hash.length()); @@ -913,7 +913,7 @@ struct keychain_command: keychain_command_base { return fc_light::json::to_string( create_secmod_unlock_cmd(keyname, params.unlock_time, no_password)); - }, secmod_unlock_cmd); + }, secmod_unlock_cmd).first; json_response response(true, id); return fc_light::json::to_string(fc_light::variant(response)); diff --git a/keychain_lib/include/keychain_lib/keyfile_parser.hpp b/keychain_lib/include/keychain_lib/keyfile_parser.hpp index 70b9b29..44c049a 100644 --- a/keychain_lib/include/keychain_lib/keyfile_parser.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_parser.hpp @@ -61,6 +61,7 @@ struct keyfile_t { curve_etype curve_type; fc_light::variant priv_key_data;//either std::string or encrypted_data dev::Public public_key; + fc_light::variant chain_code_data; //either std::string or encrypted_data } keyinfo; }; @@ -93,7 +94,7 @@ FC_LIGHT_REFLECT_ENUM(keychain_app::keyfile_format::curve_etype, (unknown)(secp2 FC_LIGHT_REFLECT(keychain_app::keyfile_format::log_record, (transaction)(sign_time)(blockchain_type)) FC_LIGHT_REFLECT(keychain_app::keyfile_format::signlog_file_t, (filetype)(public_key)(sign_events)) FC_LIGHT_REFLECT(keychain_app::keyfile_format::encrypted_data, (cipher_type)(iv)(enc_data)) -FC_LIGHT_REFLECT(keychain_app::keyfile_format::keyfile_t::keyinfo_t, (encrypted)(curve_type)(priv_key_data)(public_key)) +FC_LIGHT_REFLECT(keychain_app::keyfile_format::keyfile_t::keyinfo_t, (encrypted)(curve_type)(priv_key_data)(public_key)(chain_code_data)) FC_LIGHT_REFLECT(keychain_app::keyfile_format::keyfile_t, (filetype)(keyname)(description)(keychain_version)(creation_time)(keyinfo)) #endif //KEYCHAINAPP_KEY_FILE_PARSER_HPP diff --git a/keychain_lib/include/keychain_lib/private_keymap.hpp b/keychain_lib/include/keychain_lib/private_keymap.hpp index 4e5d4d8..ac681e8 100644 --- a/keychain_lib/include/keychain_lib/private_keymap.hpp +++ b/keychain_lib/include/keychain_lib/private_keymap.hpp @@ -18,9 +18,10 @@ namespace keychain_app { struct private_key_item { - private_key_item(const dev::Secret& secret, int unlock_duration); + private_key_item(const dev::Secret& secret, int unlock_duration, const dev::Secret& chain_code); dev::Public public_key() const; dev::Secret secret; + dev::Secret chain_code; std::chrono::system_clock::time_point unlock_time_point; int unlock_duration; }; diff --git a/keychain_lib/src/keychain_commands.cpp b/keychain_lib/src/keychain_commands.cpp index 50ee9af..2deabb6 100644 --- a/keychain_lib/src/keychain_commands.cpp +++ b/keychain_lib/src/keychain_commands.cpp @@ -179,10 +179,11 @@ void keychain_base::lock_all_priv_keys() key_map.clear(); } -dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, +std::pair keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, keychain_base::create_secmod_cmd_f&& create_cmd_func, std::string& cmd) { dev::Secret result_secret; + dev::Secret chain_code; bool unlocked = false; do { @@ -200,6 +201,7 @@ dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int un } unlocked = true; result_secret = it->secret; + chain_code = it->chain_code; } } while (false); @@ -220,10 +222,12 @@ dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int un if (password.empty()) FC_LIGHT_THROW_EXCEPTION(fc_light::password_input_exception, ""); auto encrypted_data = keyfile.keyinfo.priv_key_data.as(); + auto encrypted_chain_code = keyfile.keyinfo.chain_code_data.as(); auto& encryptor = encryptor_singleton::instance(); result_secret = encryptor.decrypt_private_key(password, encrypted_data); + chain_code = encryptor.decrypt_private_key(password, encrypted_chain_code); if(unlock_time > 0) - key_map.insert(private_key_item(result_secret, unlock_time)); + key_map.insert(private_key_item(result_secret, unlock_time, chain_code)); } break; case secmod_commands::response_te::boolean: @@ -233,9 +237,12 @@ dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int un if (confirm) { if (!unlocked) - result_secret = keyfile.keyinfo.priv_key_data.as(); + { + result_secret = keyfile.keyinfo.priv_key_data.as(); + chain_code = keyfile.keyinfo.chain_code_data.as(); + } if(unlock_time > 0) - key_map.insert(private_key_item(result_secret, unlock_time)); + key_map.insert(private_key_item(result_secret, unlock_time, chain_code)); } else { @@ -248,7 +255,7 @@ dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int un default: break; } - return result_secret; + return std::make_pair(result_secret, chain_code); } std::string parse_trx(std::string& trx) diff --git a/keychain_lib/src/private_keymap.cpp b/keychain_lib/src/private_keymap.cpp index f38b0c1..972c3ea 100644 --- a/keychain_lib/src/private_keymap.cpp +++ b/keychain_lib/src/private_keymap.cpp @@ -8,8 +8,9 @@ namespace keychain_app { -private_key_item::private_key_item(const dev::Secret& secret_, int unlock_duration_) +private_key_item::private_key_item(const dev::Secret& secret_, int unlock_duration_, const dev::Secret& chain_code_) : secret(secret_) + , chain_code(chain_code_) , unlock_time_point (std::chrono::system_clock::now()) , unlock_duration(unlock_duration_) { From d8be0747c7720c9ce5b701a5721e0e216064bb52 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Mon, 18 Mar 2019 18:18:40 +0300 Subject: [PATCH 33/65] sec_mod_linux updata --- .../passentry_cmd/sec_mod_linux.cpp | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/keychain_linux/passentry_cmd/sec_mod_linux.cpp b/keychain_linux/passentry_cmd/sec_mod_linux.cpp index e9a1b9b..46d583a 100644 --- a/keychain_linux/passentry_cmd/sec_mod_linux.cpp +++ b/keychain_linux/passentry_cmd/sec_mod_linux.cpp @@ -29,20 +29,33 @@ std::string sec_mod_linux::exec_cmd(const std::string& json_cmd) const auto map_instance = map_translate_singleton::instance(pass_entry._display); result_pass = pass_entry.fork_gui(map_instance.map, json_cmd); - std::string result; sm_cmd::secmod_response_common response; - if (result_pass.empty()) + + bool no_pass = false; + switch (etype) { + case secmod_commands::events_te::sign_trx: { + auto cmd = parser.params(); + no_pass = cmd.no_password; + } + case secmod_commands::events_te::sign_hash: { + auto cmd = parser.params(); + no_pass = cmd.no_password; + } + case secmod_commands::events_te::unlock: { + auto cmd = parser.params(); + no_pass = cmd.no_password; + } } + if (no_pass) { - response.etype = sm_cmd::response_te::null; - result = fc_light::json::to_pretty_string(response); + response.etype = sm_cmd::response_te::boolean; + response.params = true; } else { response.etype = sm_cmd::response_te::password; response.params = result_pass; - result = fc_light::json::to_pretty_string(response); } - return result; + return fc_light::json::to_pretty_string(response);; } sec_mod_linux::sec_mod_linux() From 5fcfbe91c410872e8c4001b39d534222a66d54a4 Mon Sep 17 00:00:00 2001 From: dtaipov Date: Mon, 18 Mar 2019 18:27:02 +0300 Subject: [PATCH 34/65] demo docs. default value for unlock time added --- docs/demo/index.html | 2 +- docs/index.html | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/demo/index.html b/docs/demo/index.html index 06204ae..03ed14c 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -255,7 +255,7 @@
- +
diff --git a/docs/index.html b/docs/index.html index 03bcd4f..eaae993 100644 --- a/docs/index.html +++ b/docs/index.html @@ -255,7 +255,7 @@
- +
From 28a8104d25096d8ba83da53039ce65eb3f687a4d Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Tue, 19 Mar 2019 17:41:50 +0300 Subject: [PATCH 35/65] fix encode chain_code --- keychain_cmd_app/cmd_parser.cpp | 4 +- .../keychain_lib/keychain_commands.hpp | 2 +- .../keychain_lib/keyfile_singleton.hpp | 5 ++- .../include/keychain_lib/private_keymap.hpp | 4 +- keychain_lib/src/keychain_commands.cpp | 12 ++++-- keychain_lib/src/keydata_singleton.cpp | 24 ++++++++++-- keychain_lib/src/keyfile_singleton.cpp | 38 ++++++++++++++----- keychain_lib/src/private_keymap.cpp | 2 +- .../passentry_cmd/pass_entry_term.cpp | 4 +- .../passentry_cmd/sec_mod_linux.cpp | 6 ++- libraries/mSIGNA/include/secp256k1_openssl.h | 8 ++-- libraries/mSIGNA/secp256k1_openssl.cpp | 10 ++++- 12 files changed, 87 insertions(+), 32 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 6b13cf5..e0d426d 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -120,12 +120,12 @@ int cmd_parser::run(int argc, const char* const argv[]) if ( it==keyfiles.end() ) { auto res = keychain_ref.entropy(); -/* auto& key_data = keydata_singleton::instance(); + auto& key_data = keydata_singleton::instance(); dev::bytes ue; auto mnemonics = std::move(key_data.seed(ue)); std::string pass("blank"); key_data.create_masterkey(mnemonics,pass); - key_data.create_privatekey();*/ +// key_data.create_privatekey(); } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 9ca7acc..054dd03 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -164,7 +164,7 @@ class keychain_base boost::signals2::signal select_key; boost::signals2::signal entropy; - std::pair get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); + std::pair get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); protected: keychain_base(); diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 3fceffa..433ca89 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -199,7 +199,10 @@ keyfile_format::keyfile_t create_new_keyfile( bool encrypted, keyfile_format::cipher_etype cipher, keyfile_format::curve_etype curve, - get_password_create_f&& get_passwd); + get_password_create_f&& get_passwd, + dev::Secret&, + dev::bytes +); using get_password_f = std::function(const std::string&, bool no_password)>; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/include/keychain_lib/private_keymap.hpp b/keychain_lib/include/keychain_lib/private_keymap.hpp index ac681e8..c2e11ae 100644 --- a/keychain_lib/include/keychain_lib/private_keymap.hpp +++ b/keychain_lib/include/keychain_lib/private_keymap.hpp @@ -18,10 +18,10 @@ namespace keychain_app { struct private_key_item { - private_key_item(const dev::Secret& secret, int unlock_duration, const dev::Secret& chain_code); + private_key_item(const dev::Secret& secret, int unlock_duration, const dev::bytes& chain_code); dev::Public public_key() const; dev::Secret secret; - dev::Secret chain_code; + dev::bytes chain_code; std::chrono::system_clock::time_point unlock_time_point; int unlock_duration; }; diff --git a/keychain_lib/src/keychain_commands.cpp b/keychain_lib/src/keychain_commands.cpp index 2deabb6..24cdfc6 100644 --- a/keychain_lib/src/keychain_commands.cpp +++ b/keychain_lib/src/keychain_commands.cpp @@ -179,11 +179,11 @@ void keychain_base::lock_all_priv_keys() key_map.clear(); } -std::pair keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, +std::pair keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, keychain_base::create_secmod_cmd_f&& create_cmd_func, std::string& cmd) { dev::Secret result_secret; - dev::Secret chain_code; + dev::bytes chain_code; bool unlocked = false; do { @@ -225,7 +225,11 @@ std::pair keychain_base::get_private_key(const dev::Pu auto encrypted_chain_code = keyfile.keyinfo.chain_code_data.as(); auto& encryptor = encryptor_singleton::instance(); result_secret = encryptor.decrypt_private_key(password, encrypted_data); - chain_code = encryptor.decrypt_private_key(password, encrypted_chain_code); + if (encrypted_chain_code.enc_data != "") + { + auto secret = encryptor.decrypt_private_key(password, encrypted_chain_code); + chain_code.assign(secret.data(), secret.data()+32); + } if(unlock_time > 0) key_map.insert(private_key_item(result_secret, unlock_time, chain_code)); } @@ -239,7 +243,7 @@ std::pair keychain_base::get_private_key(const dev::Pu if (!unlocked) { result_secret = keyfile.keyinfo.priv_key_data.as(); - chain_code = keyfile.keyinfo.chain_code_data.as(); + chain_code = keyfile.keyinfo.chain_code_data.as(); } if(unlock_time > 0) key_map.insert(private_key_item(result_secret, unlock_time, chain_code)); diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index fe73d24..11b8a4d 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -90,7 +90,7 @@ void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pa { std::vector key = std::move(pbkdf2(mnemonics)); dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); - dev::Secret chain_code(dev::FixedHash<32>((byte * const)key.data()+32, dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + dev::bytes chain_code(key.begin()+32, key.end() ); auto & keyfiles = keyfile_singleton::instance(); keyfiles.create(std::bind(create_new_keyfile, @@ -100,14 +100,32 @@ void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pa byte_seq_t res; std::copy(pass.begin(), pass.end(), std::back_inserter(res)); return res; - }) + }, + master_key, + chain_code) ); + + bytes_t priv_key(master_key.data(), master_key.data()+32); + bytes_t ch_code(chain_code.data(), chain_code.data()+32); + Coin::HDKeychain hd(priv_key, ch_code); + auto child = hd.getChild(0x80000000|1); + + keyfiles.create(std::bind(create_new_keyfile, + "privat_key", "master_key", false, keyfile_format::cipher_etype::aes256, + keyfile_format::curve_etype::secp256k1, + [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }, + dev::Secret(child.privkey()), + dev::bytes()) + ); } void keydata_singleton::create_privatekey() { -// Coin::HDkeychain hd(bytes_t(master_key.begin(), master_key.end()), bytes_t(chain_code.begin(), chain_code.end())); /* std::string keyname = ""; std::string pass = "blank"; diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index eed6765..360153a 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -206,7 +206,8 @@ const keyfile_format::keyfile_t& keyfile_singleton::operator[](size_t index) keydata_load(); bool stop = true; } - return ra_ind[index]; + else + return ra_ind[index]; } while (true); } @@ -222,7 +223,8 @@ const keyfile_format::keyfile_t& keyfile_singleton::operator[](const keyfile_sin keydata_load(); stop = true; } - return *it; + else + return *it; } while (true); } @@ -240,7 +242,8 @@ const keyfile_format::keyfile_t& keyfile_singleton::operator[](const keyfile_sin keydata_load(); stop = true; } - return *it; + else + return *it; } while(true); } @@ -402,10 +405,13 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( bool encrypted, keyfile_format::cipher_etype cipher, keyfile_format::curve_etype curve, - get_password_create_f&& get_passwd) + get_password_create_f&& get_passwd, + dev::Secret& priv_key, + dev::bytes chain_code + ) { keyfile_format::keyfile_t keyfile; - dev::Secret priv_key; +// dev::Secret priv_key; dev::Public pb_hex; dev::h256 hash; std::string filename; @@ -413,10 +419,9 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( { case keyfile_format::curve_etype::secp256k1: { - auto keys = dev::KeyPair::create(); + auto keys = dev::KeyPair(priv_key); pb_hex = keys.pub(); hash = dev::ethash::sha3_ethash(keys.pub()); - priv_key = keys.secret(); filename = hash.hex().substr(0,16); filename += ".json"; } @@ -435,12 +440,27 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( if (passwd.empty()) FC_LIGHT_THROW_EXCEPTION(fc_light::password_input_exception, ""); auto& encryptor = encryptor_singleton::instance(); - auto enc_data = encryptor.encrypt_private_key(cipher, passwd, priv_key); - keyfile.keyinfo.priv_key_data = fc_light::variant(enc_data); + auto enc_priv_key_data = encryptor.encrypt_private_key(cipher, passwd, priv_key); + keyfile.keyinfo.priv_key_data = fc_light::variant(enc_priv_key_data); + + keyfile_format::encrypted_data enc_chain_code_data; + if (chain_code.size()) + { + dev::Secret chain_(dev::FixedHash<32>((byte * const)chain_code.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); + enc_chain_code_data = encryptor.encrypt_private_key(cipher, passwd, chain_); + } + else + { + enc_chain_code_data.cipher_type = keyfile_format::cipher_etype::unknown; + enc_chain_code_data.iv = ""; + enc_chain_code_data.enc_data = ""; + } + keyfile.keyinfo.chain_code_data = fc_light::variant(enc_chain_code_data); keyfile.keyinfo.encrypted = true; } else{ keyfile.keyinfo.priv_key_data = fc_light::variant(priv_key); + keyfile.keyinfo.chain_code_data = fc_light::variant(chain_code); keyfile.keyinfo.encrypted = false; } diff --git a/keychain_lib/src/private_keymap.cpp b/keychain_lib/src/private_keymap.cpp index 972c3ea..1126e3c 100644 --- a/keychain_lib/src/private_keymap.cpp +++ b/keychain_lib/src/private_keymap.cpp @@ -8,7 +8,7 @@ namespace keychain_app { -private_key_item::private_key_item(const dev::Secret& secret_, int unlock_duration_, const dev::Secret& chain_code_) +private_key_item::private_key_item(const dev::Secret& secret_, int unlock_duration_, const dev::bytes& chain_code_) : secret(secret_) , chain_code(chain_code_) , unlock_time_point (std::chrono::system_clock::now()) diff --git a/keychain_linux/passentry_cmd/pass_entry_term.cpp b/keychain_linux/passentry_cmd/pass_entry_term.cpp index dcd4791..f4bf391 100644 --- a/keychain_linux/passentry_cmd/pass_entry_term.cpp +++ b/keychain_linux/passentry_cmd/pass_entry_term.cpp @@ -223,7 +223,7 @@ std::string pass_entry_term::input_password(const KeySym * map, int socket) bool first_key = true; auto gui = polling(socket); std::vector pass_len(2, 0); - ChangeKbProperty(dev_info, kbd_atom, device_enabled_prop, dev_cnt, 0); +// ChangeKbProperty(dev_info, kbd_atom, device_enabled_prop, dev_cnt, 0); capslock = keyState(XK_Caps_Lock); numlock = keyState(XK_Num_Lock); @@ -266,7 +266,7 @@ std::string pass_entry_term::input_password(const KeySym * map, int socket) if ( ev[1].code <= 255) { kbd_id = fd_list[id]; - if (ioctl(kbd_id, EVIOCGRAB, 1) != 0) throw std::runtime_error("cannot get exclusive access to keyboard"); +// if (ioctl(kbd_id, EVIOCGRAB, 1) != 0) throw std::runtime_error("cannot get exclusive access to keyboard"); break; } } diff --git a/keychain_linux/passentry_cmd/sec_mod_linux.cpp b/keychain_linux/passentry_cmd/sec_mod_linux.cpp index 46d583a..086818b 100644 --- a/keychain_linux/passentry_cmd/sec_mod_linux.cpp +++ b/keychain_linux/passentry_cmd/sec_mod_linux.cpp @@ -36,15 +36,19 @@ std::string sec_mod_linux::exec_cmd(const std::string& json_cmd) const case secmod_commands::events_te::sign_trx: { auto cmd = parser.params(); no_pass = cmd.no_password; + break; } case secmod_commands::events_te::sign_hash: { auto cmd = parser.params(); no_pass = cmd.no_password; + break; } case secmod_commands::events_te::unlock: { auto cmd = parser.params(); no_pass = cmd.no_password; - } } + break; + } + } if (no_pass) { response.etype = sm_cmd::response_te::boolean; diff --git a/libraries/mSIGNA/include/secp256k1_openssl.h b/libraries/mSIGNA/include/secp256k1_openssl.h index 808457f..ad16c72 100644 --- a/libraries/mSIGNA/include/secp256k1_openssl.h +++ b/libraries/mSIGNA/include/secp256k1_openssl.h @@ -90,13 +90,13 @@ enum SignatureFlag SIGNATURE_ENFORCE_LOW_S = 0x1, }; -bytes_t secp256k1_sigToLowS(const bytes_t& signature); +//bytes_t secp256k1_sigToLowS(const bytes_t& signature); -bytes_t secp256k1_sign(const secp256k1_key& key, const bytes_t& data); -bool secp256k1_verify(const secp256k1_key& key, const bytes_t& data, const bytes_t& signature, int flags = 0); +//bytes_t secp256k1_sign(const secp256k1_key& key, const bytes_t& data); +//bool secp256k1_verify(const secp256k1_key& key, const bytes_t& data, const bytes_t& signature, int flags = 0); bytes_t secp256k1_rfc6979_k(const secp256k1_key& key, const bytes_t& data); -bytes_t secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes_t& data); +//bytes_t secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes_t& data); } diff --git a/libraries/mSIGNA/secp256k1_openssl.cpp b/libraries/mSIGNA/secp256k1_openssl.cpp index 9f11e9f..71b3e59 100644 --- a/libraries/mSIGNA/secp256k1_openssl.cpp +++ b/libraries/mSIGNA/secp256k1_openssl.cpp @@ -353,6 +353,7 @@ bytes_t CoinCrypto::secp256k1_sigToLowS(const bytes_t& signature) +/* // Signing function bytes_t CoinCrypto::secp256k1_sign(const secp256k1_key& key, const bytes_t& data) { @@ -363,7 +364,9 @@ bytes_t CoinCrypto::secp256k1_sign(const secp256k1_key& key, const bytes_t& data } return secp256k1_sigToLowS(bytes_t(signature, signature + nSize)); } +*/ +/* // Verification function bool CoinCrypto::secp256k1_verify(const secp256k1_key& key, const bytes_t& data, const bytes_t& signature, int flags) { @@ -376,6 +379,7 @@ bool CoinCrypto::secp256k1_verify(const secp256k1_key& key, const bytes_t& data, if (rval == -1) throw std::runtime_error("secp256k1_verify(): ECDSA_verify error."); return (rval == 1); } +*/ bytes_t CoinCrypto::secp256k1_rfc6979_k(const secp256k1_key& key, const bytes_t& data) { @@ -393,9 +397,10 @@ bytes_t CoinCrypto::secp256k1_rfc6979_k(const secp256k1_key& key, const bytes_t& } +/* bytes_t CoinCrypto::secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes_t& data) { - bytes_t k = secp256k1_rfc6979_k(key, data); + bytes_t k = secp256k1_rfc6979_k(key, data); BIGNUM* bn = BN_bin2bn(&k[0], k.size(), NULL); if (!bn) throw std::runtime_error("secp256k1_sign_rfc6979() : BN_bin2bn failed for k."); @@ -457,4 +462,5 @@ bytes_t CoinCrypto::secp256k1_sign_rfc6979(const secp256k1_key& key, const bytes return secp256k1_sigToLowS(bytes_t(signature, signature + nSize)); } - +*/ + From eedda961bcc61c2a3639de6f62ef12b5fc19eb2c Mon Sep 17 00:00:00 2001 From: dtaipov Date: Tue, 19 Mar 2019 17:55:39 +0300 Subject: [PATCH 36/65] demo docs. input styles changed so placeholder value can be noticed --- docs/demo/index.html | 49 +++++++++++++++++--------------------------- docs/index.html | 49 +++++++++++++++++--------------------------- 2 files changed, 38 insertions(+), 60 deletions(-) diff --git a/docs/demo/index.html b/docs/demo/index.html index 03ed14c..70f4acf 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -35,20 +35,17 @@ text-rendering: optimizeLegibility; color: white; } - .page_title { color: rgb(85, 85, 85); font-weight: bold; margin-bottom: 15px; } - .page { display: none; } .page-active { display: block; } - .container { display: grid; grid-template-columns: 1fr 500px 1fr; @@ -104,31 +101,26 @@ grid-template-rows: 200px 200px 50px auto; grid-column-gap: 65px; } - .menu { grid-column: 1; grid-row: 1 / 3; display: grid; margin-left: -60px; } - .form { grid-column: 2 / 4; grid-row: 1; } - .right_menu { grid-column: 4; grid-row: 1 / 3; display: grid; } - .run_request { grid-column: 2; grid-row: 3; justify-self: end; } - .btn { border-radius: 2px; background-image: -moz-linear-gradient( -90deg, rgb(32,135,184) 0%, rgb(16,120,169) 47%, rgb(0,104,153) 100%); @@ -140,15 +132,12 @@ font-weight: normal; padding: 4px 6px 4px 6px; } - .btn_run_request { text-align: center; } - .gap { grid-column: 1 / 4; } - .warning_bottom { background-image: -moz-linear-gradient( -90deg, rgb(32,135,184) 0%, rgb(16,120,169) 47%, rgb(0,104,153) 100%); background-image: -webkit-linear-gradient( -90deg, rgb(32,135,184) 0%, rgb(16,120,169) 47%, rgb(0,104,153) 100%); @@ -159,12 +148,10 @@ color: white; grid-column: 1 / 4; } - .warning_bottom_divider { background-color: rgb(209, 18, 80); grid-column: 1 / 4; } - .modal { display: none; position: fixed; @@ -178,7 +165,6 @@ background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4); } - .modal-content { text-align: center; font-size: 1.8rem; @@ -188,16 +174,19 @@ padding: 20px; border: 1px solid #888; } - .form-label { color: #006899; display: inline-block; width: 100px; } - .form-input { - color: #b8b8b8; - border: none transparent; + border-radius: 2px; + border-style:solid; + border-width:1px; + width: 200px; + } + textarea { + border-radius: 2px; } @@ -251,30 +240,30 @@
Unlock
- +
- +
Sign transaction
- +
- +
- +
- +
@@ -283,15 +272,15 @@
Sign hash
- +
- +
- +
@@ -367,7 +356,7 @@ const hash = window.location.hash.substr(1); const el = document.getElementById('page_' + hash); - const inputs = el.getElementsByClassName('param_field'); + const inputs = el.getElementsByClassName('form-input'); const params = {}; for (let i=0; i @@ -251,30 +240,30 @@
Unlock
- +
- +
Sign transaction
- +
- +
- +
- +
@@ -283,15 +272,15 @@
Sign hash
- +
- +
- +
@@ -367,7 +356,7 @@ const hash = window.location.hash.substr(1); const el = document.getElementById('page_' + hash); - const inputs = el.getElementsByClassName('param_field'); + const inputs = el.getElementsByClassName('form-input'); const params = {}; for (let i=0; i Date: Fri, 22 Mar 2019 16:04:47 +0300 Subject: [PATCH 37/65] add key_path to sql --- keychain_cmd_app/cmd_parser.cpp | 24 +++- .../keychain_lib/keydata_singleton.hpp | 72 +++++++++- .../keychain_lib/keyfile_singleton.hpp | 4 +- .../include/keychain_lib/sql_singleton.hpp | 4 +- keychain_lib/src/keydata_singleton.cpp | 126 +++++++++++++----- keychain_lib/src/keyfile_singleton.cpp | 10 +- keychain_lib/src/sql_singleton.cpp | 58 +++++--- 7 files changed, 231 insertions(+), 67 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index e0d426d..6c77b34 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -122,10 +122,30 @@ int cmd_parser::run(int argc, const char* const argv[]) auto res = keychain_ref.entropy(); auto& key_data = keydata_singleton::instance(); dev::bytes ue; - auto mnemonics = std::move(key_data.seed(ue)); + std::string pass("blank"); +// std::string level("{\"root\": \"m\",\"purpose\": 0, \"coin_type\": 0, \"account\": 0, \"change\": 0, \"address_index\": 0}"); + keydata::path_levels_t path; + path.root="m"; + path.purpose=0; + path.coin_type=0; + path.account=0; + path.change=0; + path.address_index=0; + + keydata::create_t cmd; + cmd.keyname = "superkey"; + cmd.description = ""; + cmd.encrypted = false; + cmd.cipher = keyfile_format::cipher_etype::aes256; + cmd.curve = keyfile_format::curve_etype::secp256k1; + cmd.password = pass; + cmd.path = fc_light::variant(path); + auto variant = fc_light::variant(cmd); + + auto mnemonics = std::move(key_data.seed(ue)); key_data.create_masterkey(mnemonics,pass); -// key_data.create_privatekey(); + key_data.derive_key(pass, variant); } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index 0ca4bf7..b55c6f8 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -6,6 +6,16 @@ #define KEYCHAINAPP_KEYDATA_SINGLETON_HPP #include +#include +#include +#include +#include +#include +#include +#include +#include +#include "keyfile_singleton.hpp" + namespace keychain_app { @@ -14,7 +24,8 @@ struct keydata_singleton static keydata_singleton& instance(); std::string seed(dev::bytes& ); void create_masterkey(std::string&, std::string&); - void create_privatekey(); + std::pair get_master_key(get_password_create_f&& ); + void derive_key(std::string&, fc_light::variant& ); private: keydata_singleton(){} @@ -22,6 +33,65 @@ struct keydata_singleton std::vector pbkdf2(std::string const& _pass); }; +namespace keydata +{ + +struct path_levels_t +{ + std::string root; + int purpose; + int coin_type; + int account; + int change; + int address_index; +}; + +enum struct levels_te +{ + null, + root, + purpose, + coin_type, + account, + change, + address_index, + last +}; + +struct create_t +{ + std::string keyname; + std::string description; + bool encrypted; + keyfile_format::cipher_etype cipher; + keyfile_format::curve_etype curve; + std::string password; + fc_light::variant path; +}; + +namespace hana = boost::hana; +constexpr auto level_static_list = + hana::make_range( + hana::int_c(levels_te::purpose)>, + hana::int_c(levels_te::last)>); +} + } +FC_LIGHT_REFLECT_ENUM( + keychain_app::keydata::levels_te, + (null) + (root) + (purpose) + (coin_type) + (account) + (change) + (address_index) + (last) +) + +FC_LIGHT_REFLECT(keychain_app::keydata::path_levels_t, (root)(purpose)(coin_type)(account)(change)(address_index)) +FC_LIGHT_REFLECT(keychain_app::keydata::create_t, (keyname)(description)(encrypted)(cipher)(curve)(password)(path)) + + #endif //KEYCHAINAPP_KEYDATA_SINGLETON_HPP diff --git a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp index 433ca89..7d4a1d0 100644 --- a/keychain_lib/include/keychain_lib/keyfile_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keyfile_singleton.hpp @@ -200,8 +200,8 @@ keyfile_format::keyfile_t create_new_keyfile( keyfile_format::cipher_etype cipher, keyfile_format::curve_etype curve, get_password_create_f&& get_passwd, - dev::Secret&, - dev::bytes + dev::bytes&, + dev::bytes& ); using get_password_f = std::function(const std::string&, bool no_password)>; //NOTE: may incapsulate call to sec module or just return password string diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 0d469c3..2be03ad 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -7,17 +7,19 @@ #include #include "keychain_commands.hpp" #include "keyfile_singleton.hpp" +#include "keydata_singleton.hpp" struct sql_singleton { static sql_singleton& instance(); const std::vector select_log(const dev::Public& ); int insert_log(const dev::Public&, const keychain_app::keyfile_format::log_record& ); + int insert_path(const std::string&, const keychain_app::keydata::path_levels_t& ); private: sql_singleton(); ~sql_singleton(); - + void execute(const char *); sqlite3 * db; }; diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index 11b8a4d..7b23b68 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -8,7 +8,10 @@ #include #include #include -#include +#include +#include +#include "eth_types_conversion.hpp" +#include "sql_singleton.hpp" using namespace keychain_app; @@ -88,9 +91,12 @@ std::vector keydata_singleton::pbkdf2(std::string const& _pass) void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pass) { - std::vector key = std::move(pbkdf2(mnemonics)); - dev::Secret master_key(dev::FixedHash<32>((byte * const)key.data(), dev::FixedHash<32>::ConstructFromPointerType::ConstructFromPointer)); - dev::bytes chain_code(key.begin()+32, key.end() ); + std::regex re(" +"); + std::string mnemonics_ = std::regex_replace(mnemonics, re, ""); + + std::vector key = std::move(pbkdf2(mnemonics_)); + dev::bytes priv_key(key.begin(), key.begin()+32); + dev::bytes chain_code(key.begin()+32, key.end()); auto & keyfiles = keyfile_singleton::instance(); keyfiles.create(std::bind(create_new_keyfile, @@ -101,42 +107,88 @@ void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pa std::copy(pass.begin(), pass.end(), std::back_inserter(res)); return res; }, - master_key, - chain_code) - ); + priv_key, + chain_code + )); +} - bytes_t priv_key(master_key.data(), master_key.data()+32); - bytes_t ch_code(chain_code.data(), chain_code.data()+32); - Coin::HDKeychain hd(priv_key, ch_code); - auto child = hd.getChild(0x80000000|1); +void keydata_singleton::derive_key(std::string& pass, fc_light::variant& params) +{ + using namespace keydata; - keyfiles.create(std::bind(create_new_keyfile, - "privat_key", "master_key", false, keyfile_format::cipher_etype::aes256, - keyfile_format::curve_etype::secp256k1, - [&pass](const std::string& keyname)->byte_seq_t{ - byte_seq_t res; - std::copy(pass.begin(), pass.end(), std::back_inserter(res)); - return res; - }, - dev::Secret(child.privkey()), - dev::bytes()) - ); + auto password = [&pass](const std::string& keyname)->byte_seq_t{ + byte_seq_t res; + std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + return res; + }; + + auto params_ = params.as(); + auto path = params_.path.as(); + + FC_LIGHT_ASSERT(path.root == "m"); + + auto & keyfiles = keyfile_singleton::instance(); + auto secret = get_master_key(password); + dev::bytes priv_key(secret.first.data(), secret.first.data()+32); + + Coin::HDKeychain hd(priv_key, secret.second); + boost::hana::for_each( level_static_list, + [&](auto a) + { + using a_type = decltype(a); + constexpr auto level = static_cast(a_type::value); + int value = 0; + switch (level) + { + case(levels_te::purpose): {value=path.purpose; break;} + case(levels_te::coin_type): {value=path.coin_type; break;} + case(levels_te::change): {value=path.change; break;} + case(levels_te::address_index):{value=path.address_index;} + } + hd = hd.getChild(0x80000000|value); + if (level == levels_te::address_index) { + keyfiles.create(std::bind(create_new_keyfile, + params_.keyname, params_.description, params_.encrypted, + params_.cipher, params_.curve, + password, + hd.privkey(), + hd.chain_code() + )); + auto& sql = sql_singleton::instance(); + sql.insert_path(params_.keyname, path); + } + }); } -void keydata_singleton::create_privatekey() +std::pair keydata_singleton::get_master_key( get_password_create_f&& get_passwd) { -/* - std::string keyname = ""; - std::string pass = "blank"; - keyfiles.create(std::bind(create_new_keyfile, - keyname, keyname, true, keyfile_format::cipher_etype::aes256, - keyfile_format::curve_etype::secp256k1, - [&pass](const std::string& keyname)->byte_seq_t{ - byte_seq_t res; - std::copy(pass.begin(), pass.end(), std::back_inserter(res)); - return res; - }) -); -*/ -} \ No newline at end of file + dev::Secret priv_key; + dev::bytes chain_code; + std::string keyname= "master_key"; + + auto& keyfiles = keyfile_singleton::instance(); + auto& keyfile = keyfiles[keyname]; + + if (keyfile.keyinfo.encrypted) + { + auto passwd = get_passwd(keyname);//operation canceled exception need to be thrown into get_password functor + auto encrypted_data = keyfile.keyinfo.priv_key_data.as(); + auto encrypted_chain_code = keyfile.keyinfo.chain_code_data.as(); + auto& encryptor = encryptor_singleton::instance(); + priv_key = encryptor.decrypt_private_key(passwd, encrypted_data); + if (encrypted_chain_code.enc_data != "") + { + auto secret = encryptor.decrypt_private_key(passwd, encrypted_chain_code); + chain_code.assign(secret.data(), secret.data()+32); + } + } + else + { + priv_key = keyfile.keyinfo.priv_key_data.as(); + chain_code = keyfile.keyinfo.chain_code_data.as(); + } + return std::make_pair(priv_key, chain_code); +} + + diff --git a/keychain_lib/src/keyfile_singleton.cpp b/keychain_lib/src/keyfile_singleton.cpp index 360153a..e2b9c2f 100644 --- a/keychain_lib/src/keyfile_singleton.cpp +++ b/keychain_lib/src/keyfile_singleton.cpp @@ -406,8 +406,8 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( keyfile_format::cipher_etype cipher, keyfile_format::curve_etype curve, get_password_create_f&& get_passwd, - dev::Secret& priv_key, - dev::bytes chain_code + dev::bytes& priv_key, + dev::bytes& chain_code ) { keyfile_format::keyfile_t keyfile; @@ -415,11 +415,13 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( dev::Public pb_hex; dev::h256 hash; std::string filename; + auto priv_key_ = dev::Secret(dev::bytesConstRef(priv_key.data(), priv_key.size())); + switch (curve) { case keyfile_format::curve_etype::secp256k1: { - auto keys = dev::KeyPair(priv_key); + auto keys = dev::KeyPair(priv_key_); pb_hex = keys.pub(); hash = dev::ethash::sha3_ethash(keys.pub()); filename = hash.hex().substr(0,16); @@ -440,7 +442,7 @@ keyfile_format::keyfile_t keychain_app::create_new_keyfile( if (passwd.empty()) FC_LIGHT_THROW_EXCEPTION(fc_light::password_input_exception, ""); auto& encryptor = encryptor_singleton::instance(); - auto enc_priv_key_data = encryptor.encrypt_private_key(cipher, passwd, priv_key); + auto enc_priv_key_data = encryptor.encrypt_private_key(cipher, passwd, priv_key_); keyfile.keyinfo.priv_key_data = fc_light::variant(enc_priv_key_data); keyfile_format::encrypted_data enc_chain_code_data; diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index 8d5f1d8..a5f49e1 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -24,22 +24,36 @@ sql_singleton::sql_singleton() FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Can not create sql directory, path = ${directory}", ("directory", sql_dir.string())); } - sqlite3_stmt * stmt; - const char * statement = "create table if not exists signlog (public_key text not null, " - "trx text not null, sign_time text not null, blockchain_type text not null)"; sql_dir += "/data.db"; if (sqlite3_open_v2(sql_dir.c_str(), &db, SQLITE_OPEN_FULLMUTEX|SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE, 0) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_open"); - auto res = sqlite3_prepare_v2(db, statement, -1, &stmt, NULL); - if ( res != SQLITE_OK ) + const char * signlog = "create table if not exists signlog (public_key text not null, " + "trx text not null, sign_time text not null, blockchain_type text not null)"; + const char * keypath = "create table if not exists keypath (keyname text not null, root text not null, " + "purpose integer not null, coin_type integer not null, " + "account integer not null, change integer not null, " + "address_index integer not null," + "UNIQUE(keyname, root, purpose, coin_type, account, change, address_index))"; + execute(signlog); + execute(keypath); +}; + + +void sql_singleton::execute(const char * statement) +{ + sqlite3_stmt * stmt; + + if ( sqlite3_prepare_v2(db, statement, -1, &stmt, NULL) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); - sqlite3_step(stmt); + if (sqlite3_step(stmt) != SQLITE_DONE) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_step"); + if (sqlite3_finalize(stmt) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); -}; +} sql_singleton::~sql_singleton() { @@ -58,8 +72,7 @@ const std::vector sql_singleton::selec std::vector records; const char * statement = "select trx, sign_time, blockchain_type from signlog where public_key=?"; - auto res = sqlite3_prepare_v2(db, statement, -1, &stmt, NULL); - if ( res != SQLITE_OK ) + if ( sqlite3_prepare_v2(db, statement, -1, &stmt, NULL) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); std::string hex = pkey.hex(); @@ -67,8 +80,7 @@ const std::vector sql_singleton::selec while(true) { - res = sqlite3_step(stmt); - if (res == SQLITE_ROW) + if (sqlite3_step(stmt) == SQLITE_ROW) { std::string trx((const char *) sqlite3_column_text(stmt, 0)); std::string time((const char *) sqlite3_column_text(stmt, 1)); @@ -103,17 +115,23 @@ int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfi " values('"+pkey.hex()+"', '"+ keychain_app::to_hex(record.transaction.data(), record.transaction.size())+"', '"+ time+"', '"+type+ "')"; + execute(statement.c_str()); - auto res = sqlite3_prepare_v2(db, statement.c_str(), -1, &stmt, NULL); - if ( res != SQLITE_OK ) - FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); - - res = sqlite3_step(stmt); - if (res != SQLITE_DONE) - FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_step"); + return 0; +} - if (sqlite3_finalize(stmt) != SQLITE_OK ) - FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); +int sql_singleton::insert_path(const std::string& keyname, const keychain_app::keydata::path_levels_t& path ) +{ + sqlite3_stmt * stmt; + std::string statement = "insert or replace into keypath (keyname, root, purpose, coin_type, account, change, address_index )" + " values('"+keyname+"', '"+ + path.root + "', '" + + std::to_string(path.purpose)+"', '" + + std::to_string(path.coin_type)+"', '"+ + std::to_string(path.account )+ "', '" + + std::to_string(path.change)+"', '" + + std::to_string(path.address_index)+ "')"; + execute(statement.c_str()); return 0; } \ No newline at end of file From e9887cd781e26ed9a9b8bff88b7ee0e269a243e9 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Fri, 22 Mar 2019 17:10:16 +0300 Subject: [PATCH 38/65] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index da6bd35..2113634 100644 --- a/README.md +++ b/README.md @@ -13,7 +13,7 @@

» Download for macOS «

-

» Documentation «

+

» Documentation «

» Website «

From 58133771339fbc9ed32900837e2961d4987cb6ae Mon Sep 17 00:00:00 2001 From: Dmitry Date: Fri, 22 Mar 2019 17:12:39 +0300 Subject: [PATCH 39/65] Update README.md --- README.md | 1 - 1 file changed, 1 deletion(-) diff --git a/README.md b/README.md index 2113634..b9e6dd7 100644 --- a/README.md +++ b/README.md @@ -69,7 +69,6 @@ const Module = require('web3override'); const keyInstance = await Module.Keychain.create(); const data = await keyInstance.selectKey(); const key = data.result; - await keyInstance.term(); web3.eth.accounts.signTransaction = Module.web3Override(web3).signTransaction; // now we use web3 with keychain From ad66d20d212b66af77d3ea20aae1ec3a6b334290 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Fri, 22 Mar 2019 17:16:28 +0300 Subject: [PATCH 40/65] Update README.md --- README.md | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index b9e6dd7..f04e133 100644 --- a/README.md +++ b/README.md @@ -60,16 +60,16 @@ npm i --save web3override Require it ```javascript -const Module = require('web3override'); +const { Keychain, web3Override } = require('keychain.js'); ``` 2. Now use an overridden web3 function ```javascript - const keyInstance = await Module.Keychain.create(); - const data = await keyInstance.selectKey(); + const keychain = await Keychain.create(); + const data = await keychain.selectKey(); const key = data.result; - web3.eth.accounts.signTransaction = Module.web3Override(web3).signTransaction; + web3.eth.accounts.signTransaction = web3Override(web3).signTransaction; // now we use web3 with keychain await web3.eth.accounts.signTransaction(transactionParams, key); From 7675b2a3ddc503dfb2210371a44e7290b4840299 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Fri, 22 Mar 2019 17:17:45 +0300 Subject: [PATCH 41/65] Update README.md --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index f04e133..4346161 100644 --- a/README.md +++ b/README.md @@ -52,10 +52,10 @@ After you have installed [KeyChain](https://github.com/arrayio/array-io-keychain NB: If you launch KeyChain for the first time, you need to get a public key with the "select_key" command. You can save the public key to local storage. Then you will not need to use "select_key" command again. -1. Install `web3override` library from this [source](https://www.npmjs.com/package/web3override). +1. Install `keychain.js` library from this [source](https://www.npmjs.com/package/keychain.js). ``` -npm i --save web3override +npm i --save keychain.js ``` Require it From 3f284092544198d8b805d5e24d251ba26628f4c8 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Sun, 24 Mar 2019 12:31:40 +0300 Subject: [PATCH 42/65] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4346161..7fb93b7 100644 --- a/README.md +++ b/README.md @@ -55,7 +55,7 @@ NB: If you launch KeyChain for the first time, you need to get a public key with 1. Install `keychain.js` library from this [source](https://www.npmjs.com/package/keychain.js). ``` -npm i --save keychain.js +npm i keychain.js ``` Require it From 922e5477089bdf2024b6d520ca4c428b061c2994 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Mon, 25 Mar 2019 20:31:38 +0300 Subject: [PATCH 43/65] restore impl --- keychain_cmd_app/cmd_parser.cpp | 5 +- .../keychain_lib/keychain_commands.hpp | 12 +-- .../keychain_lib/keydata_singleton.hpp | 18 +++- .../include/keychain_lib/sql_singleton.hpp | 2 +- keychain_lib/src/keychain_commands.cpp | 4 +- keychain_lib/src/keydata_singleton.cpp | 96 +++++++++++++++---- keychain_lib/src/sql_singleton.cpp | 20 +++- .../passentry_cmd/pass_entry_term.cpp | 4 +- 8 files changed, 126 insertions(+), 35 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index 6c77b34..dd5c3e2 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -141,11 +141,12 @@ int cmd_parser::run(int argc, const char* const argv[]) cmd.curve = keyfile_format::curve_etype::secp256k1; cmd.password = pass; cmd.path = fc_light::variant(path); - auto variant = fc_light::variant(cmd); +// auto variant = fc_light::variant(cmd); + auto json = fc_light::json::to_string(fc_light::variant(cmd)); auto mnemonics = std::move(key_data.seed(ue)); key_data.create_masterkey(mnemonics,pass); - key_data.derive_key(pass, variant); + key_data.derive_key(pass, json); } keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 054dd03..5cd31aa 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -164,7 +164,7 @@ class keychain_base boost::signals2::signal select_key; boost::signals2::signal entropy; - std::pair get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); + dev::Secret get_private_key(const dev::Public& public_key, int unlock_time, create_secmod_cmd_f&& f, std::string& cmd); void lock_all_priv_keys(); protected: keychain_base(); @@ -188,8 +188,8 @@ fc_light::variant open_keyfile(const char_t* filename) while(true) { fin.getline(pbuf, std::distance(it, read_buf.end())); - if (fin.eof() || !fin.good()) - break; + if (fin.eof() || !fin.good()) + break; pbuf += fin.gcount() - 1; it += fin.gcount() - 1; read_count += fin.gcount() - 1; @@ -418,7 +418,7 @@ struct keychain_command : keychain_command_base { return fc_light::json::to_string( create_secmod_signhex_cmd(raw, params.blockchain_type, evaluate_from(), params.unlock_time, keyname, no_password)); - }, secmod_signhex_cmd).first; + }, secmod_signhex_cmd); auto reply = [&keyfiles, ¶ms, &id, &secmod_signhex_cmd](auto& message, const dev::bytes& transaction){ keyfiles.add_log_record(params.public_key, @@ -639,7 +639,7 @@ struct keychain_command : keychain_command_base { return fc_light::json::to_string( create_secmod_signhash_cmd(params.hash, evaluate_from(), keyname, no_password)); - }, secmod_signhash_cmd).first; + }, secmod_signhash_cmd); //NOTE: using vector instead array because move semantic is implemented in the vector std::vector hash(params.hash.length()); @@ -913,7 +913,7 @@ struct keychain_command: keychain_command_base { return fc_light::json::to_string( create_secmod_unlock_cmd(keyname, params.unlock_time, no_password)); - }, secmod_unlock_cmd).first; + }, secmod_unlock_cmd); json_response response(true, id); return fc_light::json::to_string(fc_light::variant(response)); diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index b55c6f8..953b333 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -24,10 +24,11 @@ struct keydata_singleton static keydata_singleton& instance(); std::string seed(dev::bytes& ); void create_masterkey(std::string&, std::string&); - std::pair get_master_key(get_password_create_f&& ); - void derive_key(std::string&, fc_light::variant& ); + void derive_key(std::string&, std::string& ); + void restore(std::ifstream&, std::string&, std::string& ); private: + std::pair get_master_key(get_password_create_f&& ); keydata_singleton(){} ~keydata_singleton(){} std::vector pbkdf2(std::string const& _pass); @@ -38,6 +39,8 @@ namespace keydata struct path_levels_t { + path_levels_t(){} + std::string root; int purpose; int coin_type; @@ -46,6 +49,15 @@ struct path_levels_t int address_index; }; + +struct backup_t +{ + backup_t(){} + backup_t(std::string &keyname_, fc_light::variant params_): keyname(keyname_), params(params_){} + std::string keyname; + fc_light::variant params; +}; + enum struct levels_te { null, @@ -60,6 +72,7 @@ enum struct levels_te struct create_t { + create_t(){}; std::string keyname; std::string description; bool encrypted; @@ -92,6 +105,7 @@ FC_LIGHT_REFLECT_ENUM( FC_LIGHT_REFLECT(keychain_app::keydata::path_levels_t, (root)(purpose)(coin_type)(account)(change)(address_index)) FC_LIGHT_REFLECT(keychain_app::keydata::create_t, (keyname)(description)(encrypted)(cipher)(curve)(password)(path)) +FC_LIGHT_REFLECT(keychain_app::keydata::backup_t, (keyname)(params)) #endif //KEYCHAINAPP_KEYDATA_SINGLETON_HPP diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 2be03ad..6a0ecfa 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -14,7 +14,7 @@ struct sql_singleton static sql_singleton& instance(); const std::vector select_log(const dev::Public& ); int insert_log(const dev::Public&, const keychain_app::keyfile_format::log_record& ); - int insert_path(const std::string&, const keychain_app::keydata::path_levels_t& ); + int insert_path(const keychain_app::keydata::backup_t&); private: sql_singleton(); diff --git a/keychain_lib/src/keychain_commands.cpp b/keychain_lib/src/keychain_commands.cpp index 24cdfc6..3e1d9de 100644 --- a/keychain_lib/src/keychain_commands.cpp +++ b/keychain_lib/src/keychain_commands.cpp @@ -179,7 +179,7 @@ void keychain_base::lock_all_priv_keys() key_map.clear(); } -std::pair keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, +dev::Secret keychain_base::get_private_key(const dev::Public& public_key, int unlock_time, keychain_base::create_secmod_cmd_f&& create_cmd_func, std::string& cmd) { dev::Secret result_secret; @@ -259,7 +259,7 @@ std::pair keychain_base::get_private_key(const dev::Pub default: break; } - return std::make_pair(result_secret, chain_code); + return result_secret; } std::string parse_trx(std::string& trx) diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index 7b23b68..5cb574a 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -12,6 +12,7 @@ #include #include "eth_types_conversion.hpp" #include "sql_singleton.hpp" +#include "keychain_logger.hpp" using namespace keychain_app; @@ -110,20 +111,31 @@ void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pa priv_key, chain_code )); + auto& log = logger_singleton::instance(); + BOOST_LOG_SEV(log.lg, info) << "create master key"; } -void keydata_singleton::derive_key(std::string& pass, fc_light::variant& params) +void keydata_singleton::derive_key(std::string& masterkey_pass, std::string& json) { using namespace keydata; + auto& log = logger_singleton::instance(); - auto password = [&pass](const std::string& keyname)->byte_seq_t{ + auto password = [&masterkey_pass](const std::string& keyname)->byte_seq_t{ byte_seq_t res; - std::copy(pass.begin(), pass.end(), std::back_inserter(res)); + std::copy(masterkey_pass.begin(), masterkey_pass.end(), std::back_inserter(res)); return res; }; - auto params_ = params.as(); - auto path = params_.path.as(); + auto params = fc_light::json::from_string(json); + create_t params_; + path_levels_t path; + try { + params_ = params.as(); + path = params_.path.as(); + } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} + FC_LIGHT_ASSERT(path.root == "m"); @@ -155,7 +167,10 @@ void keydata_singleton::derive_key(std::string& pass, fc_light::variant& params) hd.chain_code() )); auto& sql = sql_singleton::instance(); - sql.insert_path(params_.keyname, path); + backup_t backup(params_.keyname, params_.path); + sql.insert_path(backup); +// auto json = fc_light::json::to_string(backup); +// BOOST_LOG_SEV(log.lg, info) << "derive key: " << json; } }); } @@ -173,22 +188,71 @@ std::pair keydata_singleton::get_master_key( get_passwo if (keyfile.keyinfo.encrypted) { auto passwd = get_passwd(keyname);//operation canceled exception need to be thrown into get_password functor - auto encrypted_data = keyfile.keyinfo.priv_key_data.as(); - auto encrypted_chain_code = keyfile.keyinfo.chain_code_data.as(); - auto& encryptor = encryptor_singleton::instance(); - priv_key = encryptor.decrypt_private_key(passwd, encrypted_data); - if (encrypted_chain_code.enc_data != "") - { - auto secret = encryptor.decrypt_private_key(passwd, encrypted_chain_code); - chain_code.assign(secret.data(), secret.data()+32); + try { + auto encrypted_data = keyfile.keyinfo.priv_key_data.as(); + auto encrypted_chain_code = keyfile.keyinfo.chain_code_data.as(); + auto& encryptor = encryptor_singleton::instance(); + priv_key = encryptor.decrypt_private_key(passwd, encrypted_data); + if (encrypted_chain_code.enc_data != "") + { + auto secret = encryptor.decrypt_private_key(passwd, encrypted_chain_code); + chain_code.assign(secret.data(), secret.data()+32); + } } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} } else { - priv_key = keyfile.keyinfo.priv_key_data.as(); - chain_code = keyfile.keyinfo.chain_code_data.as(); + try { + priv_key = keyfile.keyinfo.priv_key_data.as(); + chain_code = keyfile.keyinfo.chain_code_data.as(); + } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} } return std::make_pair(priv_key, chain_code); } +void keydata_singleton::restore(std::ifstream& file, std::string& mnemonics, std::string& masterkey_pass) +{ + using namespace keydata; + auto& log = logger_singleton::instance(); + BOOST_LOG_SEV(log.lg, info) << "restore keydata from backup"; + + const int buf_size = 1000; + char buf[buf_size]; + std::vector json; + while(true) { + if (file.eof() || !file.good()) + break; + file.getline(buf, buf_size); + json.push_back(std::string(buf, buf_size)); + BOOST_LOG_SEV(log.lg, info) << "bakup path: " << json.back(); + } + + create_masterkey(mnemonics, masterkey_pass); + + for (auto &a: json) + { + auto variant = fc_light::json::from_string(a); + backup_t backup; + try { + backup = variant.as(); + } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} + + create_t params; + params.keyname = backup.keyname; + params.description = ""; + params.encrypted = false; + params.cipher = keyfile_format::cipher_etype::aes256; + params.curve = keyfile_format::curve_etype::secp256k1; + params.path = backup.params; + + auto params_json = fc_light::json::to_string(params); + derive_key(masterkey_pass, params_json); + } +} diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index a5f49e1..3328d90 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -90,8 +90,13 @@ const std::vector sql_singleton::selec rec.transaction.resize(trx.length()); auto len = keychain_app::from_hex(trx, rec.transaction.data(), rec.transaction.size() ); rec.transaction.resize(len); - rec.sign_time = fc_light::variant(time).as(); - rec.blockchain_type = fc_light::variant(chain).as(); + try { + rec.sign_time = fc_light::variant(time).as(); + rec.blockchain_type = fc_light::variant(chain).as(); + } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} + records.push_back(rec); } else break; @@ -121,11 +126,18 @@ int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfi } -int sql_singleton::insert_path(const std::string& keyname, const keychain_app::keydata::path_levels_t& path ) +int sql_singleton::insert_path(const keychain_app::keydata::backup_t& backup ) { sqlite3_stmt * stmt; + keychain_app::keydata::path_levels_t path; + try { + path = backup.params.as(); + } + catch (const std::exception &e) {throw std::runtime_error(e.what());} + catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} + std::string statement = "insert or replace into keypath (keyname, root, purpose, coin_type, account, change, address_index )" - " values('"+keyname+"', '"+ + " values('"+backup.keyname+"', '"+ path.root + "', '" + std::to_string(path.purpose)+"', '" + std::to_string(path.coin_type)+"', '"+ diff --git a/keychain_linux/passentry_cmd/pass_entry_term.cpp b/keychain_linux/passentry_cmd/pass_entry_term.cpp index f4bf391..dcd4791 100644 --- a/keychain_linux/passentry_cmd/pass_entry_term.cpp +++ b/keychain_linux/passentry_cmd/pass_entry_term.cpp @@ -223,7 +223,7 @@ std::string pass_entry_term::input_password(const KeySym * map, int socket) bool first_key = true; auto gui = polling(socket); std::vector pass_len(2, 0); -// ChangeKbProperty(dev_info, kbd_atom, device_enabled_prop, dev_cnt, 0); + ChangeKbProperty(dev_info, kbd_atom, device_enabled_prop, dev_cnt, 0); capslock = keyState(XK_Caps_Lock); numlock = keyState(XK_Num_Lock); @@ -266,7 +266,7 @@ std::string pass_entry_term::input_password(const KeySym * map, int socket) if ( ev[1].code <= 255) { kbd_id = fd_list[id]; -// if (ioctl(kbd_id, EVIOCGRAB, 1) != 0) throw std::runtime_error("cannot get exclusive access to keyboard"); + if (ioctl(kbd_id, EVIOCGRAB, 1) != 0) throw std::runtime_error("cannot get exclusive access to keyboard"); break; } } From 3318d19304a3d78c7071d4bc1d46a128f1fedfff Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Mon, 25 Mar 2019 20:59:06 +0300 Subject: [PATCH 44/65] restore update --- .../keychain_lib/keydata_singleton.hpp | 3 ++- keychain_lib/src/keydata_singleton.cpp | 23 +++++++++++++++---- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index 953b333..5feaa95 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -25,7 +25,8 @@ struct keydata_singleton std::string seed(dev::bytes& ); void create_masterkey(std::string&, std::string&); void derive_key(std::string&, std::string& ); - void restore(std::ifstream&, std::string&, std::string& ); + void restore(const char *, std::string&, std::string& ); + void backup(const char * ); private: std::pair get_master_key(get_password_create_f&& ); diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index 5cb574a..ef237f1 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -214,21 +214,27 @@ std::pair keydata_singleton::get_master_key( get_passwo return std::make_pair(priv_key, chain_code); } -void keydata_singleton::restore(std::ifstream& file, std::string& mnemonics, std::string& masterkey_pass) +void keydata_singleton::restore(const char * filename, std::string& mnemonics, std::string& masterkey_pass) { using namespace keydata; + + auto file = std::ifstream(filename); + if(!file.is_open()) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, + "Cannot open restore file ${filename}", ("filename", filename)); + auto& log = logger_singleton::instance(); - BOOST_LOG_SEV(log.lg, info) << "restore keydata from backup"; + BOOST_LOG_SEV(log.lg, info) << "restore keydata"; const int buf_size = 1000; char buf[buf_size]; std::vector json; while(true) { + file.getline(buf, buf_size); if (file.eof() || !file.good()) break; - file.getline(buf, buf_size); json.push_back(std::string(buf, buf_size)); - BOOST_LOG_SEV(log.lg, info) << "bakup path: " << json.back(); + BOOST_LOG_SEV(log.lg, info) << "restore path: " << json.back(); } create_masterkey(mnemonics, masterkey_pass); @@ -256,3 +262,12 @@ void keydata_singleton::restore(std::ifstream& file, std::string& mnemonics, std } } + +void keydata_singleton::backup(const char * filename) +{ + auto file = std::ofstream(filename); + if (!file.is_open()) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Cannot open backup file (${filename})", ("filename", filename)); +// file << fc_light::json::to_pretty_string(keyfile_data) << std::endl; + +} \ No newline at end of file From 9eec247c2f6a686525cba61ed682d77086612666 Mon Sep 17 00:00:00 2001 From: dtaipov Date: Tue, 26 Mar 2019 15:13:45 +0300 Subject: [PATCH 45/65] demo docs. find opposite button in a different way to select button on hash changing --- docs/demo/index.html | 61 +++++++++++++++++++++++++------------------- docs/index.html | 61 +++++++++++++++++++++++++------------------- 2 files changed, 70 insertions(+), 52 deletions(-) diff --git a/docs/demo/index.html b/docs/demo/index.html index 70f4acf..e4172cc 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -184,6 +184,7 @@ border-style:solid; border-width:1px; width: 200px; + padding: 3px; } textarea { border-radius: 2px; @@ -208,7 +209,7 @@
Test the WebSocket commands of KeyChain
- Read more: KeyChain Documentation + Read more: KeyChain Documentation
@@ -221,13 +222,13 @@
@@ -291,13 +292,13 @@
- - - - - - - + + + + + + +
@@ -330,6 +331,18 @@ document.getElementById('error').style.display = 'block'; }; + function buttonEnter(button) { + button.classList.add('btn_transform'); + const oppositeElement = getOppositeElementId(button); + oppositeElement.classList.add('btn_transform'); + } + + function buttonLeave(button) { + button.classList.remove('btn_transform'); + const oppositeElement = getOppositeElementId(button); + oppositeElement.classList.remove('btn_transform'); + } + function onHash(runRequestParam) { if(!window.location.hash) { return; @@ -343,6 +356,8 @@ document.getElementsByClassName('page-active')[0].classList.remove('page-active'); } el.classList.add('page-active'); + // const button = document.querySelector('.btn-command[data-hash=' + hash + ']'); + // buttonEnter(document.getElementById(hash)); const request = fieldsToJson(); document.getElementById('request').value = JSON.stringify(request, undefined, 2); @@ -419,23 +434,17 @@ const buttons = document.getElementsByClassName('btn_command'); for (let i=0; i
Test the WebSocket commands of KeyChain
- Read more: KeyChain Documentation + Read more: KeyChain Documentation
@@ -221,13 +222,13 @@
@@ -291,13 +292,13 @@
- - - - - - - + + + + + + +
@@ -330,6 +331,18 @@ document.getElementById('error').style.display = 'block'; }; + function buttonEnter(button) { + button.classList.add('btn_transform'); + const oppositeElement = getOppositeElementId(button); + oppositeElement.classList.add('btn_transform'); + } + + function buttonLeave(button) { + button.classList.remove('btn_transform'); + const oppositeElement = getOppositeElementId(button); + oppositeElement.classList.remove('btn_transform'); + } + function onHash(runRequestParam) { if(!window.location.hash) { return; @@ -343,6 +356,8 @@ document.getElementsByClassName('page-active')[0].classList.remove('page-active'); } el.classList.add('page-active'); + // const button = document.querySelector('.btn-command[data-hash=' + hash + ']'); + // buttonEnter(document.getElementById(hash)); const request = fieldsToJson(); document.getElementById('request').value = JSON.stringify(request, undefined, 2); @@ -419,23 +434,17 @@ const buttons = document.getElementsByClassName('btn_command'); for (let i=0; i Date: Tue, 26 Mar 2019 15:23:00 +0300 Subject: [PATCH 46/65] keydata::backup() impl --- .../keychain_lib/keydata_singleton.hpp | 6 +- .../include/keychain_lib/sql_singleton.hpp | 12 +++- keychain_lib/src/keydata_singleton.cpp | 16 +++-- keychain_lib/src/sql_singleton.cpp | 60 +++++++++++++++---- 4 files changed, 74 insertions(+), 20 deletions(-) diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index 5feaa95..09cb11d 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -54,9 +54,9 @@ struct path_levels_t struct backup_t { backup_t(){} - backup_t(std::string &keyname_, fc_light::variant params_): keyname(keyname_), params(params_){} + backup_t(std::string &keyname_, fc_light::variant path_): keyname(keyname_), path(path_){} std::string keyname; - fc_light::variant params; + fc_light::variant path; }; enum struct levels_te @@ -106,7 +106,7 @@ FC_LIGHT_REFLECT_ENUM( FC_LIGHT_REFLECT(keychain_app::keydata::path_levels_t, (root)(purpose)(coin_type)(account)(change)(address_index)) FC_LIGHT_REFLECT(keychain_app::keydata::create_t, (keyname)(description)(encrypted)(cipher)(curve)(password)(path)) -FC_LIGHT_REFLECT(keychain_app::keydata::backup_t, (keyname)(params)) +FC_LIGHT_REFLECT(keychain_app::keydata::backup_t, (keyname)(path)) #endif //KEYCHAINAPP_KEYDATA_SINGLETON_HPP diff --git a/keychain_lib/include/keychain_lib/sql_singleton.hpp b/keychain_lib/include/keychain_lib/sql_singleton.hpp index 6a0ecfa..4214fd2 100644 --- a/keychain_lib/include/keychain_lib/sql_singleton.hpp +++ b/keychain_lib/include/keychain_lib/sql_singleton.hpp @@ -9,12 +9,16 @@ #include "keyfile_singleton.hpp" #include "keydata_singleton.hpp" +namespace keychain_app +{ + struct sql_singleton { static sql_singleton& instance(); - const std::vector select_log(const dev::Public& ); - int insert_log(const dev::Public&, const keychain_app::keyfile_format::log_record& ); - int insert_path(const keychain_app::keydata::backup_t&); + const std::vector select_log(const dev::Public& ); + int insert_log(const dev::Public&, const keyfile_format::log_record& ); + int insert_path(const keydata::backup_t&); + const std::vector select_path(); private: sql_singleton(); @@ -23,4 +27,6 @@ struct sql_singleton sqlite3 * db; }; +} + #endif //KEYCHAINAPP_SQL_SINGLETON_HPP diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index ef237f1..64061fb 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -169,8 +169,8 @@ void keydata_singleton::derive_key(std::string& masterkey_pass, std::string& jso auto& sql = sql_singleton::instance(); backup_t backup(params_.keyname, params_.path); sql.insert_path(backup); -// auto json = fc_light::json::to_string(backup); -// BOOST_LOG_SEV(log.lg, info) << "derive key: " << json; + auto json = fc_light::json::to_string(backup); + BOOST_LOG_SEV(log.lg, info) << "derive key: " << json; } }); } @@ -255,7 +255,7 @@ void keydata_singleton::restore(const char * filename, std::string& mnemonics, s params.encrypted = false; params.cipher = keyfile_format::cipher_etype::aes256; params.curve = keyfile_format::curve_etype::secp256k1; - params.path = backup.params; + params.path = backup.path; auto params_json = fc_light::json::to_string(params); derive_key(masterkey_pass, params_json); @@ -268,6 +268,14 @@ void keydata_singleton::backup(const char * filename) auto file = std::ofstream(filename); if (!file.is_open()) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "Cannot open backup file (${filename})", ("filename", filename)); -// file << fc_light::json::to_pretty_string(keyfile_data) << std::endl; + + auto& log = logger_singleton::instance(); + BOOST_LOG_SEV(log.lg, info) << "backup keydata"; + + auto& sql = sql_singleton::instance(); + auto backup_list = std::move(sql.select_path()); + for (auto& a : backup_list) + file << fc_light::json::to_pretty_string(a) << std::endl; + } \ No newline at end of file diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index 3328d90..bfdf151 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -7,6 +7,8 @@ namespace bfs = boost::filesystem; +using namespace keychain_app; + sql_singleton::sql_singleton() { #if defined(macintosh) || defined(__APPLE__) || defined(__APPLE_CC__) @@ -66,10 +68,10 @@ sql_singleton& sql_singleton::instance() return instance; } -const std::vector sql_singleton::select_log(const dev::Public& pkey) +const std::vector sql_singleton::select_log(const dev::Public& pkey) { sqlite3_stmt * stmt; - std::vector records; + std::vector records; const char * statement = "select trx, sign_time, blockchain_type from signlog where public_key=?"; if ( sqlite3_prepare_v2(db, statement, -1, &stmt, NULL) != SQLITE_OK ) @@ -86,13 +88,13 @@ const std::vector sql_singleton::selec std::string time((const char *) sqlite3_column_text(stmt, 1)); std::string chain((const char *) sqlite3_column_text(stmt, 2)); - keychain_app::keyfile_format::log_record rec; + keyfile_format::log_record rec; rec.transaction.resize(trx.length()); - auto len = keychain_app::from_hex(trx, rec.transaction.data(), rec.transaction.size() ); + auto len = from_hex(trx, rec.transaction.data(), rec.transaction.size() ); rec.transaction.resize(len); try { rec.sign_time = fc_light::variant(time).as(); - rec.blockchain_type = fc_light::variant(chain).as(); + rec.blockchain_type = fc_light::variant(chain).as(); } catch (const std::exception &e) {throw std::runtime_error(e.what());} catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} @@ -108,7 +110,45 @@ const std::vector sql_singleton::selec return records; } -int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfile_format::log_record& record) + +const std::vector sql_singleton::select_path() +{ + sqlite3_stmt * stmt; + std::vector records; + const char * statement = "select keyname, root, purpose, coin_type, account, change, address_index"; + + if ( sqlite3_prepare_v2(db, statement, -1, &stmt, NULL) != SQLITE_OK ) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); + + while(true) + { + if (sqlite3_step(stmt) == SQLITE_ROW) + { + keydata::backup_t backup; + keydata::path_levels_t path; + + backup.keyname = std::string((const char *) sqlite3_column_text(stmt, 0)); + path.root = std::string((const char *) sqlite3_column_text(stmt, 1)); + path.purpose = std::stoi(std::string((const char *) sqlite3_column_text(stmt, 2))); + path.coin_type = std::stoi(std::string((const char *) sqlite3_column_text(stmt, 3))); + path.account = std::stoi(std::string((const char *) sqlite3_column_text(stmt, 4))); + path.change = std::stoi(std::string((const char *) sqlite3_column_text(stmt, 5))); + path.address_index = std::stoi(std::string((const char *) sqlite3_column_text(stmt,6))); + backup.path = fc_light::variant(path); + + records.push_back(backup); + } + else break; + } + + if (sqlite3_finalize(stmt) != SQLITE_OK ) + FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_finalize"); + + return records; +} + + +int sql_singleton::insert_log(const dev::Public& pkey, const keyfile_format::log_record& record) { sqlite3_stmt * stmt; fc_light::variant vtime(record.sign_time); @@ -118,7 +158,7 @@ int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfi std::string statement = "insert into signlog (public_key, trx, sign_time, blockchain_type)" " values('"+pkey.hex()+"', '"+ - keychain_app::to_hex(record.transaction.data(), record.transaction.size())+"', '"+ + to_hex(record.transaction.data(), record.transaction.size())+"', '"+ time+"', '"+type+ "')"; execute(statement.c_str()); @@ -126,12 +166,12 @@ int sql_singleton::insert_log(const dev::Public& pkey, const keychain_app::keyfi } -int sql_singleton::insert_path(const keychain_app::keydata::backup_t& backup ) +int sql_singleton::insert_path(const keydata::backup_t& backup ) { sqlite3_stmt * stmt; - keychain_app::keydata::path_levels_t path; + keydata::path_levels_t path; try { - path = backup.params.as(); + path = backup.path.as(); } catch (const std::exception &e) {throw std::runtime_error(e.what());} catch (const fc_light::exception &e) {throw std::runtime_error(e.what());} From 4b13585bd8783b016528fade96d810d66b4adb2b Mon Sep 17 00:00:00 2001 From: dtaipov Date: Tue, 26 Mar 2019 16:12:26 +0300 Subject: [PATCH 47/65] demo docs. select correspondent with a hash button --- docs/demo/index.html | 10 ++++++++-- docs/index.html | 10 ++++++++-- 2 files changed, 16 insertions(+), 4 deletions(-) diff --git a/docs/demo/index.html b/docs/demo/index.html index e4172cc..5f7cbe6 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -338,6 +338,9 @@ } function buttonLeave(button) { + if ("#" + button.dataset.hash === window.location.hash) { + return; + } button.classList.remove('btn_transform'); const oppositeElement = getOppositeElementId(button); oppositeElement.classList.remove('btn_transform'); @@ -356,8 +359,11 @@ document.getElementsByClassName('page-active')[0].classList.remove('page-active'); } el.classList.add('page-active'); - // const button = document.querySelector('.btn-command[data-hash=' + hash + ']'); - // buttonEnter(document.getElementById(hash)); + document.querySelectorAll('.btn_transform').forEach(function(button) { + button.classList.remove('btn_transform') + }); + const button = document.querySelector('[data-hash=' + hash + '][data-left="1"]'); + buttonEnter(button); const request = fieldsToJson(); document.getElementById('request').value = JSON.stringify(request, undefined, 2); diff --git a/docs/index.html b/docs/index.html index 51d5b6f..ea1aa10 100644 --- a/docs/index.html +++ b/docs/index.html @@ -338,6 +338,9 @@ } function buttonLeave(button) { + if ("#" + button.dataset.hash === window.location.hash) { + return; + } button.classList.remove('btn_transform'); const oppositeElement = getOppositeElementId(button); oppositeElement.classList.remove('btn_transform'); @@ -356,8 +359,11 @@ document.getElementsByClassName('page-active')[0].classList.remove('page-active'); } el.classList.add('page-active'); - // const button = document.querySelector('.btn-command[data-hash=' + hash + ']'); - // buttonEnter(document.getElementById(hash)); + document.querySelectorAll('.btn_transform').forEach(function(button) { + button.classList.remove('btn_transform') + }); + const button = document.querySelector('[data-hash=' + hash + '][data-left="1"]'); + buttonEnter(button); const request = fieldsToJson(); document.getElementById('request').value = JSON.stringify(request, undefined, 2); From bfcf79cb03c481b6b250d81bbcb3de095646f6eb Mon Sep 17 00:00:00 2001 From: dtaipov Date: Tue, 26 Mar 2019 16:25:44 +0300 Subject: [PATCH 48/65] demo docs. a button deselects smoothly (styles fixed) --- docs/demo/index.html | 3 +++ docs/index.html | 3 +++ 2 files changed, 6 insertions(+) diff --git a/docs/demo/index.html b/docs/demo/index.html index 5f7cbe6..6bd7edf 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -17,6 +17,9 @@ a:visited { text-decoration: none; } + .btn_command { + transition-duration: 0.5s; + } .btn_transform { transform: translateX(30px); transition-duration: 0.5s; diff --git a/docs/index.html b/docs/index.html index ea1aa10..d411635 100644 --- a/docs/index.html +++ b/docs/index.html @@ -17,6 +17,9 @@ a:visited { text-decoration: none; } + .btn_command { + transition-duration: 0.5s; + } .btn_transform { transform: translateX(30px); transition-duration: 0.5s; From add9824cc0642f812c6fff07f20705f62eee4b65 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Tue, 26 Mar 2019 16:37:19 +0300 Subject: [PATCH 49/65] remove keydata_singleton --- keychain_cmd_app/cmd_parser.cpp | 33 ++----------------- .../keychain_lib/keychain_commands.hpp | 16 ++------- .../keychain_lib/keydata_singleton.hpp | 28 +++++----------- keychain_lib/src/keydata_singleton.cpp | 27 ++++++--------- keychain_lib/src/sql_singleton.cpp | 2 +- 5 files changed, 25 insertions(+), 81 deletions(-) diff --git a/keychain_cmd_app/cmd_parser.cpp b/keychain_cmd_app/cmd_parser.cpp index dd5c3e2..9c3ac24 100644 --- a/keychain_cmd_app/cmd_parser.cpp +++ b/keychain_cmd_app/cmd_parser.cpp @@ -115,39 +115,12 @@ int cmd_parser::run(int argc, const char* const argv[]) sec_mod->connect(keychain_ref); gui_mod->connect(keychain_ref); + auto& keyfiles = keyfile_singleton::instance(); auto it = keyfiles.begin(); if ( it==keyfiles.end() ) - { - auto res = keychain_ref.entropy(); - auto& key_data = keydata_singleton::instance(); - dev::bytes ue; - - std::string pass("blank"); -// std::string level("{\"root\": \"m\",\"purpose\": 0, \"coin_type\": 0, \"account\": 0, \"change\": 0, \"address_index\": 0}"); - keydata::path_levels_t path; - path.root="m"; - path.purpose=0; - path.coin_type=0; - path.account=0; - path.change=0; - path.address_index=0; - - keydata::create_t cmd; - cmd.keyname = "superkey"; - cmd.description = ""; - cmd.encrypted = false; - cmd.cipher = keyfile_format::cipher_etype::aes256; - cmd.curve = keyfile_format::curve_etype::secp256k1; - cmd.password = pass; - cmd.path = fc_light::variant(path); -// auto variant = fc_light::variant(cmd); - auto json = fc_light::json::to_string(fc_light::variant(cmd)); - - auto mnemonics = std::move(key_data.seed(ue)); - key_data.create_masterkey(mnemonics,pass); - key_data.derive_key(pass, json); - } + auto res = keychain_ref.entropy(); + keychain_invoke_f f = std::bind(&keychain_base::operator(), &keychain_ref, std::placeholders::_1); pipeline_parser pipe_line_parser_(std::move(f), fileno(stdin), fileno(stdout)); diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index 5cd31aa..6de7247 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -834,15 +834,7 @@ struct keychain_command: keychain_command_base using params_t = params; virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override { - auto param = params_variant.as(); - std::vector entropy; - entropy.resize(param.entropy.length()); - auto res = from_hex(param.entropy, entropy.data(), entropy.size()); - entropy.resize(res); - //TODO: need to impl - std::string seed_phrase = "witch collapse practice feed shame open despair creek road again ice least"; - json_response response(seed_phrase, id); - return fc_light::json::to_string(fc_light::variant(response)); + FC_LIGHT_THROW_EXCEPTION(fc_light::command_depreciated, ""); } }; @@ -856,11 +848,7 @@ struct keychain_command: keychain_command_base using params_t = params; virtual std::string operator()(keychain_base* keychain, const fc_light::variant& params_variant, int id) const override { - auto param = params_variant.as(); - //TODO: need to impl - std::string private_key = "5fda7b741910b05738c5e0ca8961cf7a9c2f3afe8dfcae8d57df5f01690f2a02"; - json_response response(private_key, id); - return fc_light::json::to_string(fc_light::variant(response)); + FC_LIGHT_THROW_EXCEPTION(fc_light::command_depreciated, ""); } }; diff --git a/keychain_lib/include/keychain_lib/keydata_singleton.hpp b/keychain_lib/include/keychain_lib/keydata_singleton.hpp index 09cb11d..0f8e1a3 100644 --- a/keychain_lib/include/keychain_lib/keydata_singleton.hpp +++ b/keychain_lib/include/keychain_lib/keydata_singleton.hpp @@ -16,28 +16,20 @@ #include #include "keyfile_singleton.hpp" - namespace keychain_app { -struct keydata_singleton -{ - static keydata_singleton& instance(); - std::string seed(dev::bytes& ); - void create_masterkey(std::string&, std::string&); - void derive_key(std::string&, std::string& ); - void restore(const char *, std::string&, std::string& ); - void backup(const char * ); - -private: - std::pair get_master_key(get_password_create_f&& ); - keydata_singleton(){} - ~keydata_singleton(){} - std::vector pbkdf2(std::string const& _pass); -}; - namespace keydata { +std::string seed(dev::bytes& ); +void derive_masterkey(std::string&, std::string&); +void derive_key(std::string&, std::string& ); +void restore(const char *, std::string&, std::string& ); +void backup(const char * ); +std::pair get_master_key(get_password_create_f&& ); +std::vector pbkdf2(std::string const& _pass); + + struct path_levels_t { path_levels_t(){} @@ -50,7 +42,6 @@ struct path_levels_t int address_index; }; - struct backup_t { backup_t(){} @@ -108,5 +99,4 @@ FC_LIGHT_REFLECT(keychain_app::keydata::path_levels_t, (root)(purpose)(coin_type FC_LIGHT_REFLECT(keychain_app::keydata::create_t, (keyname)(description)(encrypted)(cipher)(curve)(password)(path)) FC_LIGHT_REFLECT(keychain_app::keydata::backup_t, (keyname)(path)) - #endif //KEYCHAINAPP_KEYDATA_SINGLETON_HPP diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index 64061fb..84267a2 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -16,13 +16,7 @@ using namespace keychain_app; -keydata_singleton& keydata_singleton::instance() -{ - static keydata_singleton instance; - return instance; -} - -std::string keydata_singleton::seed(dev::bytes& user_entropy) +std::string keydata::seed(dev::bytes& user_entropy) { CryptoPP::SecByteBlock ent(16); CryptoPP::OS_GenerateRandomBlock(false, ent, ent.size()); @@ -68,7 +62,7 @@ std::string keydata_singleton::seed(dev::bytes& user_entropy) } -std::vector keydata_singleton::pbkdf2(std::string const& _pass) +std::vector keydata::pbkdf2(std::string const& _pass) { unsigned _iterations = 2048; unsigned _dkLen = 64; @@ -90,7 +84,7 @@ std::vector keydata_singleton::pbkdf2(std::string const& _pass) } -void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pass) +void keydata::derive_masterkey(std::string& mnemonics, std::string& pass) { std::regex re(" +"); std::string mnemonics_ = std::regex_replace(mnemonics, re, ""); @@ -115,7 +109,7 @@ void keydata_singleton::create_masterkey(std::string& mnemonics, std::string& pa BOOST_LOG_SEV(log.lg, info) << "create master key"; } -void keydata_singleton::derive_key(std::string& masterkey_pass, std::string& json) +void keydata::derive_key(std::string& masterkey_pass, std::string& json) { using namespace keydata; auto& log = logger_singleton::instance(); @@ -176,7 +170,7 @@ void keydata_singleton::derive_key(std::string& masterkey_pass, std::string& jso } -std::pair keydata_singleton::get_master_key( get_password_create_f&& get_passwd) +std::pair keydata::get_master_key( get_password_create_f&& get_passwd) { dev::Secret priv_key; dev::bytes chain_code; @@ -214,7 +208,8 @@ std::pair keydata_singleton::get_master_key( get_passwo return std::make_pair(priv_key, chain_code); } -void keydata_singleton::restore(const char * filename, std::string& mnemonics, std::string& masterkey_pass) + +void keydata::restore(const char * filename, std::string& mnemonics, std::string& masterkey_pass) { using namespace keydata; @@ -237,7 +232,7 @@ void keydata_singleton::restore(const char * filename, std::string& mnemonics, s BOOST_LOG_SEV(log.lg, info) << "restore path: " << json.back(); } - create_masterkey(mnemonics, masterkey_pass); + derive_masterkey(mnemonics, masterkey_pass); for (auto &a: json) { @@ -263,7 +258,7 @@ void keydata_singleton::restore(const char * filename, std::string& mnemonics, s } -void keydata_singleton::backup(const char * filename) +void keydata::backup(const char * filename) { auto file = std::ofstream(filename); if (!file.is_open()) @@ -275,7 +270,5 @@ void keydata_singleton::backup(const char * filename) auto& sql = sql_singleton::instance(); auto backup_list = std::move(sql.select_path()); for (auto& a : backup_list) - file << fc_light::json::to_pretty_string(a) << std::endl; - - + file << fc_light::json::to_string(a) << std::endl; } \ No newline at end of file diff --git a/keychain_lib/src/sql_singleton.cpp b/keychain_lib/src/sql_singleton.cpp index bfdf151..da98fb9 100644 --- a/keychain_lib/src/sql_singleton.cpp +++ b/keychain_lib/src/sql_singleton.cpp @@ -115,7 +115,7 @@ const std::vector sql_singleton::select_path() { sqlite3_stmt * stmt; std::vector records; - const char * statement = "select keyname, root, purpose, coin_type, account, change, address_index"; + const char * statement = "select keyname, root, purpose, coin_type, account, change, address_index from keypath"; if ( sqlite3_prepare_v2(db, statement, -1, &stmt, NULL) != SQLITE_OK ) FC_LIGHT_THROW_EXCEPTION(fc_light::internal_error_exception, "sqlite3_prepare_v2"); From 8fdcc2d01504b5edbe531925953b05132cd54315 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Tue, 26 Mar 2019 18:28:07 +0300 Subject: [PATCH 50/65] fix log restore --- keychain_lib/src/keydata_singleton.cpp | 2 +- keychain_linux/passentry_cmd/pass_entry_term.cpp | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/keychain_lib/src/keydata_singleton.cpp b/keychain_lib/src/keydata_singleton.cpp index 84267a2..6027735 100644 --- a/keychain_lib/src/keydata_singleton.cpp +++ b/keychain_lib/src/keydata_singleton.cpp @@ -228,7 +228,7 @@ void keydata::restore(const char * filename, std::string& mnemonics, std::string file.getline(buf, buf_size); if (file.eof() || !file.good()) break; - json.push_back(std::string(buf, buf_size)); + json.push_back(std::string(buf, file.gcount()-1)); BOOST_LOG_SEV(log.lg, info) << "restore path: " << json.back(); } diff --git a/keychain_linux/passentry_cmd/pass_entry_term.cpp b/keychain_linux/passentry_cmd/pass_entry_term.cpp index dcd4791..7fe7555 100644 --- a/keychain_linux/passentry_cmd/pass_entry_term.cpp +++ b/keychain_linux/passentry_cmd/pass_entry_term.cpp @@ -152,10 +152,12 @@ std::list pass_entry_term::parse_device_file() const int buf_size = 1000; char buf[buf_size]; - while(!f_dev.eof()) + while(true) { f_dev.getline(buf, buf_size); - std::string line(buf); + if (f_dev.eof() || !f_dev.good()) + break; + std::string line(buf, f_dev.gcount()-1); std::regex rx("H: Handlers=.*kbd.* event[0-9]+"); std::regex_match(line.begin(), line.end(), rx); if (std::regex_search(line.begin(), line.end(), rx) ) From b87c78ea57771b3c4a04841c6bacddcd1c59402d Mon Sep 17 00:00:00 2001 From: dtaipov Date: Fri, 29 Mar 2019 12:01:04 +0300 Subject: [PATCH 51/65] demo docs. keychain.js delivered from jsdelivr --- docs/bundle.js | 28715 ------------------ docs/demo/index.html | 16 +- docs/eth_signer/index.html | 46 +- docs/index.html | 16 +- docs/{keychain.js => keychainWithoutNPM.js} | 0 docs/src/index.js | 1 - 6 files changed, 33 insertions(+), 28761 deletions(-) delete mode 100644 docs/bundle.js rename docs/{keychain.js => keychainWithoutNPM.js} (100%) delete mode 100644 docs/src/index.js diff --git a/docs/bundle.js b/docs/bundle.js deleted file mode 100644 index 24ab675..0000000 --- a/docs/bundle.js +++ /dev/null @@ -1,28715 +0,0 @@ -(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= 255) throw new TypeError('Alphabet too long') - - const BASE_MAP = new Uint8Array(256) - BASE_MAP.fill(255) - - for (let i = 0; i < ALPHABET.length; i++) { - const x = ALPHABET.charAt(i) - const xc = x.charCodeAt(0) - - if (BASE_MAP[xc] !== 255) throw new TypeError(x + ' is ambiguous') - BASE_MAP[xc] = i - } - - const BASE = ALPHABET.length - const LEADER = ALPHABET.charAt(0) - const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up - const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up - - function encode (source) { - if (!Buffer.isBuffer(source)) throw new TypeError('Expected Buffer') - if (source.length === 0) return '' - - // Skip & count leading zeroes. - let zeroes = 0 - let length = 0 - let pbegin = 0 - const pend = source.length - - while (pbegin !== pend && source[pbegin] === 0) { - pbegin++ - zeroes++ - } - - // Allocate enough space in big-endian base58 representation. - const size = ((pend - pbegin) * iFACTOR + 1) >>> 0 - const b58 = new Uint8Array(size) - - // Process the bytes. - while (pbegin !== pend) { - let carry = source[pbegin] - - // Apply "b58 = b58 * 256 + ch". - let i = 0 - for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) { - carry += (256 * b58[it]) >>> 0 - b58[it] = (carry % BASE) >>> 0 - carry = (carry / BASE) >>> 0 - } - - if (carry !== 0) throw new Error('Non-zero carry') - length = i - pbegin++ - } - - // Skip leading zeroes in base58 result. - let it = size - length - while (it !== size && b58[it] === 0) { - it++ - } - - // Translate the result into a string. - let str = LEADER.repeat(zeroes) - for (; it < size; ++it) str += ALPHABET.charAt(b58[it]) - - return str - } - - function decodeUnsafe (source) { - if (typeof source !== 'string') throw new TypeError('Expected String') - if (source.length === 0) return Buffer.alloc(0) - - let psz = 0 - - // Skip leading spaces. - if (source[psz] === ' ') return - - // Skip and count leading '1's. - let zeroes = 0 - let length = 0 - while (source[psz] === LEADER) { - zeroes++ - psz++ - } - - // Allocate enough space in big-endian base256 representation. - const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up. - const b256 = new Uint8Array(size) - - // Process the characters. - while (source[psz]) { - // Decode character - let carry = BASE_MAP[source.charCodeAt(psz)] - - // Invalid character - if (carry === 255) return - - let i = 0 - for (let it = size - 1; (carry !== 0 || i < length) && (it !== -1); it--, i++) { - carry += (BASE * b256[it]) >>> 0 - b256[it] = (carry % 256) >>> 0 - carry = (carry / 256) >>> 0 - } - - if (carry !== 0) throw new Error('Non-zero carry') - length = i - psz++ - } - - // Skip trailing spaces. - if (source[psz] === ' ') return - - // Skip leading zeroes in b256. - let it = size - length - while (it !== size && b256[it] === 0) { - it++ - } - - const vch = Buffer.allocUnsafe(zeroes + (size - it)) - vch.fill(0x00, 0, zeroes) - - let j = zeroes - while (it !== size) { - vch[j++] = b256[it++] - } - - return vch - } - - function decode (string) { - const buffer = decodeUnsafe(string) - if (buffer) return buffer - - throw new Error('Non-base' + BASE + ' character') - } - - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } -} - -},{"safe-buffer":117}],3:[function(require,module,exports){ -'use strict' -var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l' - -// pre-compute lookup table -var ALPHABET_MAP = {} -for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z -} - -function polymodStep (pre) { - var b = pre >> 25 - return ((pre & 0x1FFFFFF) << 5) ^ - (-((b >> 0) & 1) & 0x3b6a57b2) ^ - (-((b >> 1) & 1) & 0x26508e6d) ^ - (-((b >> 2) & 1) & 0x1ea119fa) ^ - (-((b >> 3) & 1) & 0x3d4233dd) ^ - (-((b >> 4) & 1) & 0x2a1462b3) -} - -function prefixChk (prefix) { - var chk = 1 - for (var i = 0; i < prefix.length; ++i) { - var c = prefix.charCodeAt(i) - if (c < 33 || c > 126) throw new Error('Invalid prefix (' + prefix + ')') - - chk = polymodStep(chk) ^ (c >> 5) - } - chk = polymodStep(chk) - - for (i = 0; i < prefix.length; ++i) { - var v = prefix.charCodeAt(i) - chk = polymodStep(chk) ^ (v & 0x1f) - } - return chk -} - -function encode (prefix, words, LIMIT) { - LIMIT = LIMIT || 90 - if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') - - prefix = prefix.toLowerCase() - - // determine chk mod - var chk = prefixChk(prefix) - var result = prefix + '1' - for (var i = 0; i < words.length; ++i) { - var x = words[i] - if ((x >> 5) !== 0) throw new Error('Non 5-bit word') - - chk = polymodStep(chk) ^ x - result += ALPHABET.charAt(x) - } - - for (i = 0; i < 6; ++i) { - chk = polymodStep(chk) - } - chk ^= 1 - - for (i = 0; i < 6; ++i) { - var v = (chk >> ((5 - i) * 5)) & 0x1f - result += ALPHABET.charAt(v) - } - - return result -} - -function decode (str, LIMIT) { - LIMIT = LIMIT || 90 - if (str.length < 8) throw new TypeError(str + ' too short') - if (str.length > LIMIT) throw new TypeError('Exceeds length limit') - - // don't allow mixed case - var lowered = str.toLowerCase() - var uppered = str.toUpperCase() - if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str) - str = lowered - - var split = str.lastIndexOf('1') - if (split === -1) throw new Error('No separator character for ' + str) - if (split === 0) throw new Error('Missing prefix for ' + str) - - var prefix = str.slice(0, split) - var wordChars = str.slice(split + 1) - if (wordChars.length < 6) throw new Error('Data too short') - - var chk = prefixChk(prefix) - var words = [] - for (var i = 0; i < wordChars.length; ++i) { - var c = wordChars.charAt(i) - var v = ALPHABET_MAP[c] - if (v === undefined) throw new Error('Unknown character ' + c) - chk = polymodStep(chk) ^ v - - // not in the checksum? - if (i + 6 >= wordChars.length) continue - words.push(v) - } - - if (chk !== 1) throw new Error('Invalid checksum for ' + str) - return { prefix: prefix, words: words } -} - -function convert (data, inBits, outBits, pad) { - var value = 0 - var bits = 0 - var maxV = (1 << outBits) - 1 - - var result = [] - for (var i = 0; i < data.length; ++i) { - value = (value << inBits) | data[i] - bits += inBits - - while (bits >= outBits) { - bits -= outBits - result.push((value >> bits) & maxV) - } - } - - if (pad) { - if (bits > 0) { - result.push((value << (outBits - bits)) & maxV) - } - } else { - if (bits >= inBits) throw new Error('Excess padding') - if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding') - } - - return result -} - -function toWords (bytes) { - return convert(bytes, 8, 5, true) -} - -function fromWords (words) { - return convert(words, 5, 8, false) -} - -module.exports = { - decode: decode, - encode: encode, - toWords: toWords, - fromWords: fromWords -} - -},{}],4:[function(require,module,exports){ -// (public) Constructor -function BigInteger(a, b, c) { - if (!(this instanceof BigInteger)) - return new BigInteger(a, b, c) - - if (a != null) { - if ("number" == typeof a) this.fromNumber(a, b, c) - else if (b == null && "string" != typeof a) this.fromString(a, 256) - else this.fromString(a, b) - } -} - -var proto = BigInteger.prototype - -// duck-typed isBigInteger -proto.__bigi = require('../package.json').version -BigInteger.isBigInteger = function (obj, check_ver) { - return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) -} - -// Bits per digit -var dbits - -// am: Compute w_j += (x*this_i), propagate carries, -// c is initial carry, returns final carry. -// c < 3*dvalue, x < 2*dvalue, this_i < dvalue -// We need to select the fastest one that works in this environment. - -// am1: use a single mult and divide to get the high bits, -// max digit bits should be 26 because -// max internal value = 2*dvalue^2-2*dvalue (< 2^53) -function am1(i, x, w, j, c, n) { - while (--n >= 0) { - var v = x * this[i++] + w[j] + c - c = Math.floor(v / 0x4000000) - w[j++] = v & 0x3ffffff - } - return c -} -// am2 avoids a big mult-and-extract completely. -// Max digit bits should be <= 30 because we do bitwise ops -// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) -function am2(i, x, w, j, c, n) { - var xl = x & 0x7fff, - xh = x >> 15 - while (--n >= 0) { - var l = this[i] & 0x7fff - var h = this[i++] >> 15 - var m = xh * l + h * xl - l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) - c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) - w[j++] = l & 0x3fffffff - } - return c -} -// Alternately, set max digit bits to 28 since some -// browsers slow down when dealing with 32-bit numbers. -function am3(i, x, w, j, c, n) { - var xl = x & 0x3fff, - xh = x >> 14 - while (--n >= 0) { - var l = this[i] & 0x3fff - var h = this[i++] >> 14 - var m = xh * l + h * xl - l = xl * l + ((m & 0x3fff) << 14) + w[j] + c - c = (l >> 28) + (m >> 14) + xh * h - w[j++] = l & 0xfffffff - } - return c -} - -// wtf? -BigInteger.prototype.am = am1 -dbits = 26 - -BigInteger.prototype.DB = dbits -BigInteger.prototype.DM = ((1 << dbits) - 1) -var DV = BigInteger.prototype.DV = (1 << dbits) - -var BI_FP = 52 -BigInteger.prototype.FV = Math.pow(2, BI_FP) -BigInteger.prototype.F1 = BI_FP - dbits -BigInteger.prototype.F2 = 2 * dbits - BI_FP - -// Digit conversions -var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" -var BI_RC = new Array() -var rr, vv -rr = "0".charCodeAt(0) -for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv -rr = "a".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv -rr = "A".charCodeAt(0) -for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv - -function int2char(n) { - return BI_RM.charAt(n) -} - -function intAt(s, i) { - var c = BI_RC[s.charCodeAt(i)] - return (c == null) ? -1 : c -} - -// (protected) copy this to r -function bnpCopyTo(r) { - for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] - r.t = this.t - r.s = this.s -} - -// (protected) set from integer value x, -DV <= x < DV -function bnpFromInt(x) { - this.t = 1 - this.s = (x < 0) ? -1 : 0 - if (x > 0) this[0] = x - else if (x < -1) this[0] = x + DV - else this.t = 0 -} - -// return bigint initialized to value -function nbv(i) { - var r = new BigInteger() - r.fromInt(i) - return r -} - -// (protected) set from string and radix -function bnpFromString(s, b) { - var self = this - - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 256) k = 8; // byte array - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else { - self.fromRadix(s, b) - return - } - self.t = 0 - self.s = 0 - var i = s.length, - mi = false, - sh = 0 - while (--i >= 0) { - var x = (k == 8) ? s[i] & 0xff : intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-") mi = true - continue - } - mi = false - if (sh == 0) - self[self.t++] = x - else if (sh + k > self.DB) { - self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh - self[self.t++] = (x >> (self.DB - sh)) - } else - self[self.t - 1] |= x << sh - sh += k - if (sh >= self.DB) sh -= self.DB - } - if (k == 8 && (s[0] & 0x80) != 0) { - self.s = -1 - if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh - } - self.clamp() - if (mi) BigInteger.ZERO.subTo(self, self) -} - -// (protected) clamp off excess high words -function bnpClamp() { - var c = this.s & this.DM - while (this.t > 0 && this[this.t - 1] == c)--this.t -} - -// (public) return string representation in given radix -function bnToString(b) { - var self = this - if (self.s < 0) return "-" + self.negate() - .toString(b) - var k - if (b == 16) k = 4 - else if (b == 8) k = 3 - else if (b == 2) k = 1 - else if (b == 32) k = 5 - else if (b == 4) k = 2 - else return self.toRadix(b) - var km = (1 << k) - 1, - d, m = false, - r = "", - i = self.t - var p = self.DB - (i * self.DB) % k - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) > 0) { - m = true - r = int2char(d) - } - while (i >= 0) { - if (p < k) { - d = (self[i] & ((1 << p) - 1)) << (k - p) - d |= self[--i] >> (p += self.DB - k) - } else { - d = (self[i] >> (p -= k)) & km - if (p <= 0) { - p += self.DB - --i - } - } - if (d > 0) m = true - if (m) r += int2char(d) - } - } - return m ? r : "0" -} - -// (public) -this -function bnNegate() { - var r = new BigInteger() - BigInteger.ZERO.subTo(this, r) - return r -} - -// (public) |this| -function bnAbs() { - return (this.s < 0) ? this.negate() : this -} - -// (public) return + if this > a, - if this < a, 0 if equal -function bnCompareTo(a) { - var r = this.s - a.s - if (r != 0) return r - var i = this.t - r = i - a.t - if (r != 0) return (this.s < 0) ? -r : r - while (--i >= 0) - if ((r = this[i] - a[i]) != 0) return r - return 0 -} - -// returns bit length of the integer x -function nbits(x) { - var r = 1, - t - if ((t = x >>> 16) != 0) { - x = t - r += 16 - } - if ((t = x >> 8) != 0) { - x = t - r += 8 - } - if ((t = x >> 4) != 0) { - x = t - r += 4 - } - if ((t = x >> 2) != 0) { - x = t - r += 2 - } - if ((t = x >> 1) != 0) { - x = t - r += 1 - } - return r -} - -// (public) return the number of bits in "this" -function bnBitLength() { - if (this.t <= 0) return 0 - return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) -} - -// (public) return the number of bytes in "this" -function bnByteLength() { - return this.bitLength() >> 3 -} - -// (protected) r = this << n*DB -function bnpDLShiftTo(n, r) { - var i - for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] - for (i = n - 1; i >= 0; --i) r[i] = 0 - r.t = this.t + n - r.s = this.s -} - -// (protected) r = this >> n*DB -function bnpDRShiftTo(n, r) { - for (var i = n; i < this.t; ++i) r[i - n] = this[i] - r.t = Math.max(this.t - n, 0) - r.s = this.s -} - -// (protected) r = this << n -function bnpLShiftTo(n, r) { - var self = this - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << cbs) - 1 - var ds = Math.floor(n / self.DB), - c = (self.s << bs) & self.DM, - i - for (i = self.t - 1; i >= 0; --i) { - r[i + ds + 1] = (self[i] >> cbs) | c - c = (self[i] & bm) << bs - } - for (i = ds - 1; i >= 0; --i) r[i] = 0 - r[ds] = c - r.t = self.t + ds + 1 - r.s = self.s - r.clamp() -} - -// (protected) r = this >> n -function bnpRShiftTo(n, r) { - var self = this - r.s = self.s - var ds = Math.floor(n / self.DB) - if (ds >= self.t) { - r.t = 0 - return - } - var bs = n % self.DB - var cbs = self.DB - bs - var bm = (1 << bs) - 1 - r[0] = self[ds] >> bs - for (var i = ds + 1; i < self.t; ++i) { - r[i - ds - 1] |= (self[i] & bm) << cbs - r[i - ds] = self[i] >> bs - } - if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs - r.t = self.t - ds - r.clamp() -} - -// (protected) r = this - a -function bnpSubTo(a, r) { - var self = this - var i = 0, - c = 0, - m = Math.min(a.t, self.t) - while (i < m) { - c += self[i] - a[i] - r[i++] = c & self.DM - c >>= self.DB - } - if (a.t < self.t) { - c -= a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c -= a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c -= a.s - } - r.s = (c < 0) ? -1 : 0 - if (c < -1) r[i++] = self.DV + c - else if (c > 0) r[i++] = c - r.t = i - r.clamp() -} - -// (protected) r = this * a, r != this,a (HAC 14.12) -// "this" should be the larger one if appropriate. -function bnpMultiplyTo(a, r) { - var x = this.abs(), - y = a.abs() - var i = x.t - r.t = i + y.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) - r.s = 0 - r.clamp() - if (this.s != a.s) BigInteger.ZERO.subTo(r, r) -} - -// (protected) r = this^2, r != this (HAC 14.16) -function bnpSquareTo(r) { - var x = this.abs() - var i = r.t = 2 * x.t - while (--i >= 0) r[i] = 0 - for (i = 0; i < x.t - 1; ++i) { - var c = x.am(i, x[i], r, 2 * i, 0, 1) - if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { - r[i + x.t] -= x.DV - r[i + x.t + 1] = 1 - } - } - if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) - r.s = 0 - r.clamp() -} - -// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) -// r != q, this != m. q or r may be null. -function bnpDivRemTo(m, q, r) { - var self = this - var pm = m.abs() - if (pm.t <= 0) return - var pt = self.abs() - if (pt.t < pm.t) { - if (q != null) q.fromInt(0) - if (r != null) self.copyTo(r) - return - } - if (r == null) r = new BigInteger() - var y = new BigInteger(), - ts = self.s, - ms = m.s - var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus - if (nsh > 0) { - pm.lShiftTo(nsh, y) - pt.lShiftTo(nsh, r) - } else { - pm.copyTo(y) - pt.copyTo(r) - } - var ys = y.t - var y0 = y[ys - 1] - if (y0 == 0) return - var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) - var d1 = self.FV / yt, - d2 = (1 << self.F1) / yt, - e = 1 << self.F2 - var i = r.t, - j = i - ys, - t = (q == null) ? new BigInteger() : q - y.dlShiftTo(j, t) - if (r.compareTo(t) >= 0) { - r[r.t++] = 1 - r.subTo(t, r) - } - BigInteger.ONE.dlShiftTo(ys, t) - t.subTo(y, y); // "negative" y so we can replace sub with am later - while (y.t < ys) y[y.t++] = 0 - while (--j >= 0) { - // Estimate quotient digit - var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) - if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out - y.dlShiftTo(j, t) - r.subTo(t, r) - while (r[i] < --qd) r.subTo(t, r) - } - } - if (q != null) { - r.drShiftTo(ys, q) - if (ts != ms) BigInteger.ZERO.subTo(q, q) - } - r.t = ys - r.clamp() - if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder - if (ts < 0) BigInteger.ZERO.subTo(r, r) -} - -// (public) this mod a -function bnMod(a) { - var r = new BigInteger() - this.abs() - .divRemTo(a, null, r) - if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) - return r -} - -// Modular reduction using "classic" algorithm -function Classic(m) { - this.m = m -} - -function cConvert(x) { - if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) - else return x -} - -function cRevert(x) { - return x -} - -function cReduce(x) { - x.divRemTo(this.m, null, x) -} - -function cMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -function cSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -Classic.prototype.convert = cConvert -Classic.prototype.revert = cRevert -Classic.prototype.reduce = cReduce -Classic.prototype.mulTo = cMulTo -Classic.prototype.sqrTo = cSqrTo - -// (protected) return "-1/this % 2^DB"; useful for Mont. reduction -// justification: -// xy == 1 (mod m) -// xy = 1+km -// xy(2-xy) = (1+km)(1-km) -// x[y(2-xy)] = 1-k^2m^2 -// x[y(2-xy)] == 1 (mod m^2) -// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 -// should reduce x and y(2-xy) by m^2 at each step to keep size bounded. -// JS multiply "overflows" differently from C/C++, so care is needed here. -function bnpInvDigit() { - if (this.t < 1) return 0 - var x = this[0] - if ((x & 1) == 0) return 0 - var y = x & 3; // y == 1/x mod 2^2 - y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 - y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 - y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 - // last step - calculate inverse mod DV directly - // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints - y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits - // we really want the negative inverse, and -DV < y < DV - return (y > 0) ? this.DV - y : -y -} - -// Montgomery reduction -function Montgomery(m) { - this.m = m - this.mp = m.invDigit() - this.mpl = this.mp & 0x7fff - this.mph = this.mp >> 15 - this.um = (1 << (m.DB - 15)) - 1 - this.mt2 = 2 * m.t -} - -// xR mod m -function montConvert(x) { - var r = new BigInteger() - x.abs() - .dlShiftTo(this.m.t, r) - r.divRemTo(this.m, null, r) - if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) - return r -} - -// x/R mod m -function montRevert(x) { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r -} - -// x = x/R mod m (HAC 14.32) -function montReduce(x) { - while (x.t <= this.mt2) // pad x so am has enough room later - x[x.t++] = 0 - for (var i = 0; i < this.m.t; ++i) { - // faster way of calculating u0 = x[i]*mp mod DV - var j = x[i] & 0x7fff - var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM - // use am to combine the multiply-shift-add into one call - j = i + this.m.t - x[j] += this.m.am(0, u0, x, i, 0, this.m.t) - // propagate carry - while (x[j] >= x.DV) { - x[j] -= x.DV - x[++j]++ - } - } - x.clamp() - x.drShiftTo(this.m.t, x) - if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) -} - -// r = "x^2/R mod m"; x != r -function montSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = "xy/R mod m"; x,y != r -function montMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Montgomery.prototype.convert = montConvert -Montgomery.prototype.revert = montRevert -Montgomery.prototype.reduce = montReduce -Montgomery.prototype.mulTo = montMulTo -Montgomery.prototype.sqrTo = montSqrTo - -// (protected) true iff this is even -function bnpIsEven() { - return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 -} - -// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) -function bnpExp(e, z) { - if (e > 0xffffffff || e < 1) return BigInteger.ONE - var r = new BigInteger(), - r2 = new BigInteger(), - g = z.convert(this), - i = nbits(e) - 1 - g.copyTo(r) - while (--i >= 0) { - z.sqrTo(r, r2) - if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) - else { - var t = r - r = r2 - r2 = t - } - } - return z.revert(r) -} - -// (public) this^e % m, 0 <= e < 2^32 -function bnModPowInt(e, m) { - var z - if (e < 256 || m.isEven()) z = new Classic(m) - else z = new Montgomery(m) - return this.exp(e, z) -} - -// protected -proto.copyTo = bnpCopyTo -proto.fromInt = bnpFromInt -proto.fromString = bnpFromString -proto.clamp = bnpClamp -proto.dlShiftTo = bnpDLShiftTo -proto.drShiftTo = bnpDRShiftTo -proto.lShiftTo = bnpLShiftTo -proto.rShiftTo = bnpRShiftTo -proto.subTo = bnpSubTo -proto.multiplyTo = bnpMultiplyTo -proto.squareTo = bnpSquareTo -proto.divRemTo = bnpDivRemTo -proto.invDigit = bnpInvDigit -proto.isEven = bnpIsEven -proto.exp = bnpExp - -// public -proto.toString = bnToString -proto.negate = bnNegate -proto.abs = bnAbs -proto.compareTo = bnCompareTo -proto.bitLength = bnBitLength -proto.byteLength = bnByteLength -proto.mod = bnMod -proto.modPowInt = bnModPowInt - -// (public) -function bnClone() { - var r = new BigInteger() - this.copyTo(r) - return r -} - -// (public) return value as integer -function bnIntValue() { - if (this.s < 0) { - if (this.t == 1) return this[0] - this.DV - else if (this.t == 0) return -1 - } else if (this.t == 1) return this[0] - else if (this.t == 0) return 0 - // assumes 16 < DB < 32 - return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] -} - -// (public) return value as byte -function bnByteValue() { - return (this.t == 0) ? this.s : (this[0] << 24) >> 24 -} - -// (public) return value as short (assumes DB>=16) -function bnShortValue() { - return (this.t == 0) ? this.s : (this[0] << 16) >> 16 -} - -// (protected) return x s.t. r^x < DV -function bnpChunkSize(r) { - return Math.floor(Math.LN2 * this.DB / Math.log(r)) -} - -// (public) 0 if this == 0, 1 if this > 0 -function bnSigNum() { - if (this.s < 0) return -1 - else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 - else return 1 -} - -// (protected) convert to radix string -function bnpToRadix(b) { - if (b == null) b = 10 - if (this.signum() == 0 || b < 2 || b > 36) return "0" - var cs = this.chunkSize(b) - var a = Math.pow(b, cs) - var d = nbv(a), - y = new BigInteger(), - z = new BigInteger(), - r = "" - this.divRemTo(d, y, z) - while (y.signum() > 0) { - r = (a + z.intValue()) - .toString(b) - .substr(1) + r - y.divRemTo(d, y, z) - } - return z.intValue() - .toString(b) + r -} - -// (protected) convert from radix string -function bnpFromRadix(s, b) { - var self = this - self.fromInt(0) - if (b == null) b = 10 - var cs = self.chunkSize(b) - var d = Math.pow(b, cs), - mi = false, - j = 0, - w = 0 - for (var i = 0; i < s.length; ++i) { - var x = intAt(s, i) - if (x < 0) { - if (s.charAt(i) == "-" && self.signum() == 0) mi = true - continue - } - w = b * w + x - if (++j >= cs) { - self.dMultiply(d) - self.dAddOffset(w, 0) - j = 0 - w = 0 - } - } - if (j > 0) { - self.dMultiply(Math.pow(b, j)) - self.dAddOffset(w, 0) - } - if (mi) BigInteger.ZERO.subTo(self, self) -} - -// (protected) alternate constructor -function bnpFromNumber(a, b, c) { - var self = this - if ("number" == typeof b) { - // new BigInteger(int,int,RNG) - if (a < 2) self.fromInt(1) - else { - self.fromNumber(a, c) - if (!self.testBit(a - 1)) // force MSB set - self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) - if (self.isEven()) self.dAddOffset(1, 0); // force odd - while (!self.isProbablePrime(b)) { - self.dAddOffset(2, 0) - if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) - } - } - } else { - // new BigInteger(int,RNG) - var x = new Array(), - t = a & 7 - x.length = (a >> 3) + 1 - b.nextBytes(x) - if (t > 0) x[0] &= ((1 << t) - 1) - else x[0] = 0 - self.fromString(x, 256) - } -} - -// (public) convert to bigendian byte array -function bnToByteArray() { - var self = this - var i = self.t, - r = new Array() - r[0] = self.s - var p = self.DB - (i * self.DB) % 8, - d, k = 0 - if (i-- > 0) { - if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) - r[k++] = d | (self.s << (self.DB - p)) - while (i >= 0) { - if (p < 8) { - d = (self[i] & ((1 << p) - 1)) << (8 - p) - d |= self[--i] >> (p += self.DB - 8) - } else { - d = (self[i] >> (p -= 8)) & 0xff - if (p <= 0) { - p += self.DB - --i - } - } - if ((d & 0x80) != 0) d |= -256 - if (k === 0 && (self.s & 0x80) != (d & 0x80))++k - if (k > 0 || d != self.s) r[k++] = d - } - } - return r -} - -function bnEquals(a) { - return (this.compareTo(a) == 0) -} - -function bnMin(a) { - return (this.compareTo(a) < 0) ? this : a -} - -function bnMax(a) { - return (this.compareTo(a) > 0) ? this : a -} - -// (protected) r = this op a (bitwise) -function bnpBitwiseTo(a, op, r) { - var self = this - var i, f, m = Math.min(a.t, self.t) - for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) - if (a.t < self.t) { - f = a.s & self.DM - for (i = m; i < self.t; ++i) r[i] = op(self[i], f) - r.t = self.t - } else { - f = self.s & self.DM - for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) - r.t = a.t - } - r.s = op(self.s, a.s) - r.clamp() -} - -// (public) this & a -function op_and(x, y) { - return x & y -} - -function bnAnd(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_and, r) - return r -} - -// (public) this | a -function op_or(x, y) { - return x | y -} - -function bnOr(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_or, r) - return r -} - -// (public) this ^ a -function op_xor(x, y) { - return x ^ y -} - -function bnXor(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_xor, r) - return r -} - -// (public) this & ~a -function op_andnot(x, y) { - return x & ~y -} - -function bnAndNot(a) { - var r = new BigInteger() - this.bitwiseTo(a, op_andnot, r) - return r -} - -// (public) ~this -function bnNot() { - var r = new BigInteger() - for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] - r.t = this.t - r.s = ~this.s - return r -} - -// (public) this << n -function bnShiftLeft(n) { - var r = new BigInteger() - if (n < 0) this.rShiftTo(-n, r) - else this.lShiftTo(n, r) - return r -} - -// (public) this >> n -function bnShiftRight(n) { - var r = new BigInteger() - if (n < 0) this.lShiftTo(-n, r) - else this.rShiftTo(n, r) - return r -} - -// return index of lowest 1-bit in x, x < 2^31 -function lbit(x) { - if (x == 0) return -1 - var r = 0 - if ((x & 0xffff) == 0) { - x >>= 16 - r += 16 - } - if ((x & 0xff) == 0) { - x >>= 8 - r += 8 - } - if ((x & 0xf) == 0) { - x >>= 4 - r += 4 - } - if ((x & 3) == 0) { - x >>= 2 - r += 2 - } - if ((x & 1) == 0)++r - return r -} - -// (public) returns index of lowest 1-bit (or -1 if none) -function bnGetLowestSetBit() { - for (var i = 0; i < this.t; ++i) - if (this[i] != 0) return i * this.DB + lbit(this[i]) - if (this.s < 0) return this.t * this.DB - return -1 -} - -// return number of 1 bits in x -function cbit(x) { - var r = 0 - while (x != 0) { - x &= x - 1 - ++r - } - return r -} - -// (public) return number of set bits -function bnBitCount() { - var r = 0, - x = this.s & this.DM - for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) - return r -} - -// (public) true iff nth bit is set -function bnTestBit(n) { - var j = Math.floor(n / this.DB) - if (j >= this.t) return (this.s != 0) - return ((this[j] & (1 << (n % this.DB))) != 0) -} - -// (protected) this op (1<>= self.DB - } - if (a.t < self.t) { - c += a.s - while (i < self.t) { - c += self[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += self.s - } else { - c += self.s - while (i < a.t) { - c += a[i] - r[i++] = c & self.DM - c >>= self.DB - } - c += a.s - } - r.s = (c < 0) ? -1 : 0 - if (c > 0) r[i++] = c - else if (c < -1) r[i++] = self.DV + c - r.t = i - r.clamp() -} - -// (public) this + a -function bnAdd(a) { - var r = new BigInteger() - this.addTo(a, r) - return r -} - -// (public) this - a -function bnSubtract(a) { - var r = new BigInteger() - this.subTo(a, r) - return r -} - -// (public) this * a -function bnMultiply(a) { - var r = new BigInteger() - this.multiplyTo(a, r) - return r -} - -// (public) this^2 -function bnSquare() { - var r = new BigInteger() - this.squareTo(r) - return r -} - -// (public) this / a -function bnDivide(a) { - var r = new BigInteger() - this.divRemTo(a, r, null) - return r -} - -// (public) this % a -function bnRemainder(a) { - var r = new BigInteger() - this.divRemTo(a, null, r) - return r -} - -// (public) [this/a,this%a] -function bnDivideAndRemainder(a) { - var q = new BigInteger(), - r = new BigInteger() - this.divRemTo(a, q, r) - return new Array(q, r) -} - -// (protected) this *= n, this >= 0, 1 < n < DV -function bnpDMultiply(n) { - this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) - ++this.t - this.clamp() -} - -// (protected) this += n << w words, this >= 0 -function bnpDAddOffset(n, w) { - if (n == 0) return - while (this.t <= w) this[this.t++] = 0 - this[w] += n - while (this[w] >= this.DV) { - this[w] -= this.DV - if (++w >= this.t) this[this.t++] = 0 - ++this[w] - } -} - -// A "null" reducer -function NullExp() {} - -function nNop(x) { - return x -} - -function nMulTo(x, y, r) { - x.multiplyTo(y, r) -} - -function nSqrTo(x, r) { - x.squareTo(r) -} - -NullExp.prototype.convert = nNop -NullExp.prototype.revert = nNop -NullExp.prototype.mulTo = nMulTo -NullExp.prototype.sqrTo = nSqrTo - -// (public) this^e -function bnPow(e) { - return this.exp(e, new NullExp()) -} - -// (protected) r = lower n words of "this * a", a.t <= n -// "this" should be the larger one if appropriate. -function bnpMultiplyLowerTo(a, n, r) { - var i = Math.min(this.t + a.t, n) - r.s = 0; // assumes a,this >= 0 - r.t = i - while (i > 0) r[--i] = 0 - var j - for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) - for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) - r.clamp() -} - -// (protected) r = "this * a" without lower n words, n > 0 -// "this" should be the larger one if appropriate. -function bnpMultiplyUpperTo(a, n, r) { - --n - var i = r.t = this.t + a.t - n - r.s = 0; // assumes a,this >= 0 - while (--i >= 0) r[i] = 0 - for (i = Math.max(n - this.t, 0); i < a.t; ++i) - r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) - r.clamp() - r.drShiftTo(1, r) -} - -// Barrett modular reduction -function Barrett(m) { - // setup Barrett - this.r2 = new BigInteger() - this.q3 = new BigInteger() - BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) - this.mu = this.r2.divide(m) - this.m = m -} - -function barrettConvert(x) { - if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) - else if (x.compareTo(this.m) < 0) return x - else { - var r = new BigInteger() - x.copyTo(r) - this.reduce(r) - return r - } -} - -function barrettRevert(x) { - return x -} - -// x = x mod m (HAC 14.42) -function barrettReduce(x) { - var self = this - x.drShiftTo(self.m.t - 1, self.r2) - if (x.t > self.m.t + 1) { - x.t = self.m.t + 1 - x.clamp() - } - self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) - self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) - while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) - x.subTo(self.r2, x) - while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) -} - -// r = x^2 mod m; x != r -function barrettSqrTo(x, r) { - x.squareTo(r) - this.reduce(r) -} - -// r = x*y mod m; x,y != r -function barrettMulTo(x, y, r) { - x.multiplyTo(y, r) - this.reduce(r) -} - -Barrett.prototype.convert = barrettConvert -Barrett.prototype.revert = barrettRevert -Barrett.prototype.reduce = barrettReduce -Barrett.prototype.mulTo = barrettMulTo -Barrett.prototype.sqrTo = barrettSqrTo - -// (public) this^e % m (HAC 14.85) -function bnModPow(e, m) { - var i = e.bitLength(), - k, r = nbv(1), - z - if (i <= 0) return r - else if (i < 18) k = 1 - else if (i < 48) k = 3 - else if (i < 144) k = 4 - else if (i < 768) k = 5 - else k = 6 - if (i < 8) - z = new Classic(m) - else if (m.isEven()) - z = new Barrett(m) - else - z = new Montgomery(m) - - // precomputation - var g = new Array(), - n = 3, - k1 = k - 1, - km = (1 << k) - 1 - g[1] = z.convert(this) - if (k > 1) { - var g2 = new BigInteger() - z.sqrTo(g[1], g2) - while (n <= km) { - g[n] = new BigInteger() - z.mulTo(g2, g[n - 2], g[n]) - n += 2 - } - } - - var j = e.t - 1, - w, is1 = true, - r2 = new BigInteger(), - t - i = nbits(e[j]) - 1 - while (j >= 0) { - if (i >= k1) w = (e[j] >> (i - k1)) & km - else { - w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) - if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) - } - - n = k - while ((w & 1) == 0) { - w >>= 1 - --n - } - if ((i -= n) < 0) { - i += this.DB - --j - } - if (is1) { // ret == 1, don't bother squaring or multiplying it - g[w].copyTo(r) - is1 = false - } else { - while (n > 1) { - z.sqrTo(r, r2) - z.sqrTo(r2, r) - n -= 2 - } - if (n > 0) z.sqrTo(r, r2) - else { - t = r - r = r2 - r2 = t - } - z.mulTo(r2, g[w], r) - } - - while (j >= 0 && (e[j] & (1 << i)) == 0) { - z.sqrTo(r, r2) - t = r - r = r2 - r2 = t - if (--i < 0) { - i = this.DB - 1 - --j - } - } - } - return z.revert(r) -} - -// (public) gcd(this,a) (HAC 14.54) -function bnGCD(a) { - var x = (this.s < 0) ? this.negate() : this.clone() - var y = (a.s < 0) ? a.negate() : a.clone() - if (x.compareTo(y) < 0) { - var t = x - x = y - y = t - } - var i = x.getLowestSetBit(), - g = y.getLowestSetBit() - if (g < 0) return x - if (i < g) g = i - if (g > 0) { - x.rShiftTo(g, x) - y.rShiftTo(g, y) - } - while (x.signum() > 0) { - if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) - if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) - if (x.compareTo(y) >= 0) { - x.subTo(y, x) - x.rShiftTo(1, x) - } else { - y.subTo(x, y) - y.rShiftTo(1, y) - } - } - if (g > 0) y.lShiftTo(g, y) - return y -} - -// (protected) this % n, n < 2^26 -function bnpModInt(n) { - if (n <= 0) return 0 - var d = this.DV % n, - r = (this.s < 0) ? n - 1 : 0 - if (this.t > 0) - if (d == 0) r = this[0] % n - else - for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n - return r -} - -// (public) 1/this % m (HAC 14.61) -function bnModInverse(m) { - var ac = m.isEven() - if (this.signum() === 0) throw new Error('division by zero') - if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO - var u = m.clone(), - v = this.clone() - var a = nbv(1), - b = nbv(0), - c = nbv(0), - d = nbv(1) - while (u.signum() != 0) { - while (u.isEven()) { - u.rShiftTo(1, u) - if (ac) { - if (!a.isEven() || !b.isEven()) { - a.addTo(this, a) - b.subTo(m, b) - } - a.rShiftTo(1, a) - } else if (!b.isEven()) b.subTo(m, b) - b.rShiftTo(1, b) - } - while (v.isEven()) { - v.rShiftTo(1, v) - if (ac) { - if (!c.isEven() || !d.isEven()) { - c.addTo(this, c) - d.subTo(m, d) - } - c.rShiftTo(1, c) - } else if (!d.isEven()) d.subTo(m, d) - d.rShiftTo(1, d) - } - if (u.compareTo(v) >= 0) { - u.subTo(v, u) - if (ac) a.subTo(c, a) - b.subTo(d, b) - } else { - v.subTo(u, v) - if (ac) c.subTo(a, c) - d.subTo(b, d) - } - } - if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO - while (d.compareTo(m) >= 0) d.subTo(m, d) - while (d.signum() < 0) d.addTo(m, d) - return d -} - -var lowprimes = [ - 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, - 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, - 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, - 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, - 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, - 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, - 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, - 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, - 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, - 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, - 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 -] - -var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] - -// (public) test primality with certainty >= 1-.5^t -function bnIsProbablePrime(t) { - var i, x = this.abs() - if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { - for (i = 0; i < lowprimes.length; ++i) - if (x[0] == lowprimes[i]) return true - return false - } - if (x.isEven()) return false - i = 1 - while (i < lowprimes.length) { - var m = lowprimes[i], - j = i + 1 - while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] - m = x.modInt(m) - while (i < j) if (m % lowprimes[i++] == 0) return false - } - return x.millerRabin(t) -} - -// (protected) true if probably prime (HAC 4.24, Miller-Rabin) -function bnpMillerRabin(t) { - var n1 = this.subtract(BigInteger.ONE) - var k = n1.getLowestSetBit() - if (k <= 0) return false - var r = n1.shiftRight(k) - t = (t + 1) >> 1 - if (t > lowprimes.length) t = lowprimes.length - var a = new BigInteger(null) - var j, bases = [] - for (var i = 0; i < t; ++i) { - for (;;) { - j = lowprimes[Math.floor(Math.random() * lowprimes.length)] - if (bases.indexOf(j) == -1) break - } - bases.push(j) - a.fromInt(j) - var y = a.modPow(r, this) - if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { - var j = 1 - while (j++ < k && y.compareTo(n1) != 0) { - y = y.modPowInt(2, this) - if (y.compareTo(BigInteger.ONE) == 0) return false - } - if (y.compareTo(n1) != 0) return false - } - } - return true -} - -// protected -proto.chunkSize = bnpChunkSize -proto.toRadix = bnpToRadix -proto.fromRadix = bnpFromRadix -proto.fromNumber = bnpFromNumber -proto.bitwiseTo = bnpBitwiseTo -proto.changeBit = bnpChangeBit -proto.addTo = bnpAddTo -proto.dMultiply = bnpDMultiply -proto.dAddOffset = bnpDAddOffset -proto.multiplyLowerTo = bnpMultiplyLowerTo -proto.multiplyUpperTo = bnpMultiplyUpperTo -proto.modInt = bnpModInt -proto.millerRabin = bnpMillerRabin - -// public -proto.clone = bnClone -proto.intValue = bnIntValue -proto.byteValue = bnByteValue -proto.shortValue = bnShortValue -proto.signum = bnSigNum -proto.toByteArray = bnToByteArray -proto.equals = bnEquals -proto.min = bnMin -proto.max = bnMax -proto.and = bnAnd -proto.or = bnOr -proto.xor = bnXor -proto.andNot = bnAndNot -proto.not = bnNot -proto.shiftLeft = bnShiftLeft -proto.shiftRight = bnShiftRight -proto.getLowestSetBit = bnGetLowestSetBit -proto.bitCount = bnBitCount -proto.testBit = bnTestBit -proto.setBit = bnSetBit -proto.clearBit = bnClearBit -proto.flipBit = bnFlipBit -proto.add = bnAdd -proto.subtract = bnSubtract -proto.multiply = bnMultiply -proto.divide = bnDivide -proto.remainder = bnRemainder -proto.divideAndRemainder = bnDivideAndRemainder -proto.modPow = bnModPow -proto.modInverse = bnModInverse -proto.pow = bnPow -proto.gcd = bnGCD -proto.isProbablePrime = bnIsProbablePrime - -// JSBN-specific extension -proto.square = bnSquare - -// constants -BigInteger.ZERO = nbv(0) -BigInteger.ONE = nbv(1) -BigInteger.valueOf = nbv - -module.exports = BigInteger - -},{"../package.json":7}],5:[function(require,module,exports){ -(function (Buffer){ -// FIXME: Kind of a weird way to throw exceptions, consider removing -var assert = require('assert') -var BigInteger = require('./bigi') - -/** - * Turns a byte array into a big integer. - * - * This function will interpret a byte array as a big integer in big - * endian notation. - */ -BigInteger.fromByteArrayUnsigned = function(byteArray) { - // BigInteger expects a DER integer conformant byte array - if (byteArray[0] & 0x80) { - return new BigInteger([0].concat(byteArray)) - } - - return new BigInteger(byteArray) -} - -/** - * Returns a byte array representation of the big integer. - * - * This returns the absolute of the contained value in big endian - * form. A value of zero results in an empty array. - */ -BigInteger.prototype.toByteArrayUnsigned = function() { - var byteArray = this.toByteArray() - return byteArray[0] === 0 ? byteArray.slice(1) : byteArray -} - -BigInteger.fromDERInteger = function(byteArray) { - return new BigInteger(byteArray) -} - -/* - * Converts BigInteger to a DER integer representation. - * - * The format for this value uses the most significant bit as a sign - * bit. If the most significant bit is already set and the integer is - * positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 -*/ -BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray - -BigInteger.fromBuffer = function(buffer) { - // BigInteger expects a DER integer conformant byte array - if (buffer[0] & 0x80) { - var byteArray = Array.prototype.slice.call(buffer) - - return new BigInteger([0].concat(byteArray)) - } - - return new BigInteger(buffer) -} - -BigInteger.fromHex = function(hex) { - if (hex === '') return BigInteger.ZERO - - assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string') - assert.equal(hex.length % 2, 0, 'Incomplete hex') - return new BigInteger(hex, 16) -} - -BigInteger.prototype.toBuffer = function(size) { - var byteArray = this.toByteArrayUnsigned() - var zeros = [] - - var padding = size - byteArray.length - while (zeros.length < padding) zeros.push(0) - - return new Buffer(zeros.concat(byteArray)) -} - -BigInteger.prototype.toHex = function(size) { - return this.toBuffer(size).toString('hex') -} - -}).call(this,require("buffer").Buffer) -},{"./bigi":4,"assert":143,"buffer":149}],6:[function(require,module,exports){ -var BigInteger = require('./bigi') - -//addons -require('./convert') - -module.exports = BigInteger -},{"./bigi":4,"./convert":5}],7:[function(require,module,exports){ -module.exports={ - "_from": "bigi@^1.4.0", - "_id": "bigi@1.4.2", - "_inBundle": false, - "_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=", - "_location": "/bigi", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "bigi@^1.4.0", - "name": "bigi", - "escapedName": "bigi", - "rawSpec": "^1.4.0", - "saveSpec": null, - "fetchSpec": "^1.4.0" - }, - "_requiredBy": [ - "/bitcoinjs-lib", - "/ecurve" - ], - "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz", - "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825", - "_spec": "bigi@^1.4.0", - "_where": "/Users/pidgin/projects/array-io-keychain/docs/src/node_modules/bitcoinjs-lib", - "bugs": { - "url": "https://github.com/cryptocoinjs/bigi/issues" - }, - "bundleDependencies": false, - "dependencies": {}, - "deprecated": false, - "description": "Big integers.", - "devDependencies": { - "coveralls": "^2.11.2", - "istanbul": "^0.3.5", - "jshint": "^2.5.1", - "mocha": "^2.1.0", - "mochify": "^2.1.0" - }, - "homepage": "https://github.com/cryptocoinjs/bigi#readme", - "keywords": [ - "cryptography", - "math", - "bitcoin", - "arbitrary", - "precision", - "arithmetic", - "big", - "integer", - "int", - "number", - "biginteger", - "bigint", - "bignumber", - "decimal", - "float" - ], - "main": "./lib/index.js", - "name": "bigi", - "repository": { - "url": "git+https://github.com/cryptocoinjs/bigi.git", - "type": "git" - }, - "scripts": { - "browser-test": "mochify --wd -R spec", - "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js", - "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info", - "jshint": "jshint --config jshint.json lib/*.js ; true", - "test": "_mocha -- test/*.js", - "unit": "mocha" - }, - "testling": { - "files": "test/*.js", - "harness": "mocha", - "browsers": [ - "ie/9..latest", - "firefox/latest", - "chrome/latest", - "safari/6.0..latest", - "iphone/6.0..latest", - "android-browser/4.2..latest" - ] - }, - "version": "1.4.2" -} - -},{}],8:[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 - -var Buffer = require('safe-buffer').Buffer - -function check (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false - - var lenR = buffer[3] - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false - - var lenS = buffer[5 + lenR] - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false - - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true -} - -function decode (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - - var lenR = buffer[3] - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - - var lenS = buffer[5 + lenR] - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } -} - -/* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 -*/ -function encode (r, s) { - var lenR = r.length - var lenS = s.length - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer.allocUnsafe(6 + lenR + lenS) - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30 - signature[1] = signature.length - 2 - signature[2] = 0x02 - signature[3] = r.length - r.copy(signature, 4) - signature[4 + lenR] = 0x02 - signature[5 + lenR] = s.length - s.copy(signature, 6 + lenR) - - return signature -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"safe-buffer":117}],9:[function(require,module,exports){ -module.exports={ - "OP_FALSE": 0, - "OP_0": 0, - "OP_PUSHDATA1": 76, - "OP_PUSHDATA2": 77, - "OP_PUSHDATA4": 78, - "OP_1NEGATE": 79, - "OP_RESERVED": 80, - "OP_TRUE": 81, - "OP_1": 81, - "OP_2": 82, - "OP_3": 83, - "OP_4": 84, - "OP_5": 85, - "OP_6": 86, - "OP_7": 87, - "OP_8": 88, - "OP_9": 89, - "OP_10": 90, - "OP_11": 91, - "OP_12": 92, - "OP_13": 93, - "OP_14": 94, - "OP_15": 95, - "OP_16": 96, - - "OP_NOP": 97, - "OP_VER": 98, - "OP_IF": 99, - "OP_NOTIF": 100, - "OP_VERIF": 101, - "OP_VERNOTIF": 102, - "OP_ELSE": 103, - "OP_ENDIF": 104, - "OP_VERIFY": 105, - "OP_RETURN": 106, - - "OP_TOALTSTACK": 107, - "OP_FROMALTSTACK": 108, - "OP_2DROP": 109, - "OP_2DUP": 110, - "OP_3DUP": 111, - "OP_2OVER": 112, - "OP_2ROT": 113, - "OP_2SWAP": 114, - "OP_IFDUP": 115, - "OP_DEPTH": 116, - "OP_DROP": 117, - "OP_DUP": 118, - "OP_NIP": 119, - "OP_OVER": 120, - "OP_PICK": 121, - "OP_ROLL": 122, - "OP_ROT": 123, - "OP_SWAP": 124, - "OP_TUCK": 125, - - "OP_CAT": 126, - "OP_SUBSTR": 127, - "OP_LEFT": 128, - "OP_RIGHT": 129, - "OP_SIZE": 130, - - "OP_INVERT": 131, - "OP_AND": 132, - "OP_OR": 133, - "OP_XOR": 134, - "OP_EQUAL": 135, - "OP_EQUALVERIFY": 136, - "OP_RESERVED1": 137, - "OP_RESERVED2": 138, - - "OP_1ADD": 139, - "OP_1SUB": 140, - "OP_2MUL": 141, - "OP_2DIV": 142, - "OP_NEGATE": 143, - "OP_ABS": 144, - "OP_NOT": 145, - "OP_0NOTEQUAL": 146, - "OP_ADD": 147, - "OP_SUB": 148, - "OP_MUL": 149, - "OP_DIV": 150, - "OP_MOD": 151, - "OP_LSHIFT": 152, - "OP_RSHIFT": 153, - - "OP_BOOLAND": 154, - "OP_BOOLOR": 155, - "OP_NUMEQUAL": 156, - "OP_NUMEQUALVERIFY": 157, - "OP_NUMNOTEQUAL": 158, - "OP_LESSTHAN": 159, - "OP_GREATERTHAN": 160, - "OP_LESSTHANOREQUAL": 161, - "OP_GREATERTHANOREQUAL": 162, - "OP_MIN": 163, - "OP_MAX": 164, - - "OP_WITHIN": 165, - - "OP_RIPEMD160": 166, - "OP_SHA1": 167, - "OP_SHA256": 168, - "OP_HASH160": 169, - "OP_HASH256": 170, - "OP_CODESEPARATOR": 171, - "OP_CHECKSIG": 172, - "OP_CHECKSIGVERIFY": 173, - "OP_CHECKMULTISIG": 174, - "OP_CHECKMULTISIGVERIFY": 175, - - "OP_NOP1": 176, - - "OP_NOP2": 177, - "OP_CHECKLOCKTIMEVERIFY": 177, - - "OP_NOP3": 178, - "OP_CHECKSEQUENCEVERIFY": 178, - - "OP_NOP4": 179, - "OP_NOP5": 180, - "OP_NOP6": 181, - "OP_NOP7": 182, - "OP_NOP8": 183, - "OP_NOP9": 184, - "OP_NOP10": 185, - - "OP_PUBKEYHASH": 253, - "OP_PUBKEY": 254, - "OP_INVALIDOPCODE": 255 -} - -},{}],10:[function(require,module,exports){ -var OPS = require('./index.json') - -var map = {} -for (var op in OPS) { - var code = OPS[op] - map[code] = op -} - -module.exports = map - -},{"./index.json":9}],11:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bech32 = require('bech32') -var bs58check = require('bs58check') -var bscript = require('./script') -var btemplates = require('./templates') -var networks = require('./networks') -var typeforce = require('typeforce') -var types = require('./types') - -function fromBase58Check (address) { - var payload = bs58check.decode(address) - - // TODO: 4.0.0, move to "toOutputScript" - if (payload.length < 21) throw new TypeError(address + ' is too short') - if (payload.length > 21) throw new TypeError(address + ' is too long') - - var version = payload.readUInt8(0) - var hash = payload.slice(1) - - return { version: version, hash: hash } -} - -function fromBech32 (address) { - var result = bech32.decode(address) - var data = bech32.fromWords(result.words.slice(1)) - - return { - version: result.words[0], - prefix: result.prefix, - data: Buffer.from(data) - } -} - -function toBase58Check (hash, version) { - typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments) - - var payload = Buffer.allocUnsafe(21) - payload.writeUInt8(version, 0) - hash.copy(payload, 1) - - return bs58check.encode(payload) -} - -function toBech32 (data, version, prefix) { - var words = bech32.toWords(data) - words.unshift(version) - - return bech32.encode(prefix, words) -} - -function fromOutputScript (outputScript, network) { - network = network || networks.bitcoin - - if (btemplates.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash) - if (btemplates.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash) - if (btemplates.witnessPubKeyHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 22), 0, network.bech32) - if (btemplates.witnessScriptHash.output.check(outputScript)) return toBech32(bscript.compile(outputScript).slice(2, 34), 0, network.bech32) - - throw new Error(bscript.toASM(outputScript) + ' has no matching Address') -} - -function toOutputScript (address, network) { - network = network || networks.bitcoin - - var decode - try { - decode = fromBase58Check(address) - } catch (e) {} - - if (decode) { - if (decode.version === network.pubKeyHash) return btemplates.pubKeyHash.output.encode(decode.hash) - if (decode.version === network.scriptHash) return btemplates.scriptHash.output.encode(decode.hash) - } else { - try { - decode = fromBech32(address) - } catch (e) {} - - if (decode) { - if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix') - if (decode.version === 0) { - if (decode.data.length === 20) return btemplates.witnessPubKeyHash.output.encode(decode.data) - if (decode.data.length === 32) return btemplates.witnessScriptHash.output.encode(decode.data) - } - } - } - - throw new Error(address + ' has no matching Script') -} - -module.exports = { - fromBase58Check: fromBase58Check, - fromBech32: fromBech32, - fromOutputScript: fromOutputScript, - toBase58Check: toBase58Check, - toBech32: toBech32, - toOutputScript: toOutputScript -} - -},{"./networks":20,"./script":21,"./templates":23,"./types":47,"bech32":3,"bs58check":52,"safe-buffer":117,"typeforce":135}],12:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bcrypto = require('./crypto') -var fastMerkleRoot = require('merkle-lib/fastRoot') -var typeforce = require('typeforce') -var types = require('./types') -var varuint = require('varuint-bitcoin') - -var Transaction = require('./transaction') - -function Block () { - this.version = 1 - this.prevHash = null - this.merkleRoot = null - this.timestamp = 0 - this.bits = 0 - this.nonce = 0 -} - -Block.fromBuffer = function (buffer) { - if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)') - - var offset = 0 - function readSlice (n) { - offset += n - return buffer.slice(offset - n, offset) - } - - function readUInt32 () { - var i = buffer.readUInt32LE(offset) - offset += 4 - return i - } - - function readInt32 () { - var i = buffer.readInt32LE(offset) - offset += 4 - return i - } - - var block = new Block() - block.version = readInt32() - block.prevHash = readSlice(32) - block.merkleRoot = readSlice(32) - block.timestamp = readUInt32() - block.bits = readUInt32() - block.nonce = readUInt32() - - if (buffer.length === 80) return block - - function readVarInt () { - var vi = varuint.decode(buffer, offset) - offset += varuint.decode.bytes - return vi - } - - function readTransaction () { - var tx = Transaction.fromBuffer(buffer.slice(offset), true) - offset += tx.byteLength() - return tx - } - - var nTransactions = readVarInt() - block.transactions = [] - - for (var i = 0; i < nTransactions; ++i) { - var tx = readTransaction() - block.transactions.push(tx) - } - - return block -} - -Block.prototype.byteLength = function (headersOnly) { - if (headersOnly || !this.transactions) return 80 - - return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) { - return a + x.byteLength() - }, 0) -} - -Block.fromHex = function (hex) { - return Block.fromBuffer(Buffer.from(hex, 'hex')) -} - -Block.prototype.getHash = function () { - return bcrypto.hash256(this.toBuffer(true)) -} - -Block.prototype.getId = function () { - return this.getHash().reverse().toString('hex') -} - -Block.prototype.getUTCDate = function () { - var date = new Date(0) // epoch - date.setUTCSeconds(this.timestamp) - - return date -} - -// TODO: buffer, offset compatibility -Block.prototype.toBuffer = function (headersOnly) { - var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)) - - var offset = 0 - function writeSlice (slice) { - slice.copy(buffer, offset) - offset += slice.length - } - - function writeInt32 (i) { - buffer.writeInt32LE(i, offset) - offset += 4 - } - function writeUInt32 (i) { - buffer.writeUInt32LE(i, offset) - offset += 4 - } - - writeInt32(this.version) - writeSlice(this.prevHash) - writeSlice(this.merkleRoot) - writeUInt32(this.timestamp) - writeUInt32(this.bits) - writeUInt32(this.nonce) - - if (headersOnly || !this.transactions) return buffer - - varuint.encode(this.transactions.length, buffer, offset) - offset += varuint.encode.bytes - - this.transactions.forEach(function (tx) { - var txSize = tx.byteLength() // TODO: extract from toBuffer? - tx.toBuffer(buffer, offset) - offset += txSize - }) - - return buffer -} - -Block.prototype.toHex = function (headersOnly) { - return this.toBuffer(headersOnly).toString('hex') -} - -Block.calculateTarget = function (bits) { - var exponent = ((bits & 0xff000000) >> 24) - 3 - var mantissa = bits & 0x007fffff - var target = Buffer.alloc(32, 0) - target.writeUInt32BE(mantissa, 28 - exponent) - return target -} - -Block.calculateMerkleRoot = function (transactions) { - typeforce([{ getHash: types.Function }], transactions) - if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions') - - var hashes = transactions.map(function (transaction) { - return transaction.getHash() - }) - - return fastMerkleRoot(hashes, bcrypto.hash256) -} - -Block.prototype.checkMerkleRoot = function () { - if (!this.transactions) return false - - var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions) - return this.merkleRoot.compare(actualMerkleRoot) === 0 -} - -Block.prototype.checkProofOfWork = function () { - var hash = this.getHash().reverse() - var target = Block.calculateTarget(this.bits) - - return hash.compare(target) <= 0 -} - -module.exports = Block - -},{"./crypto":14,"./transaction":45,"./types":47,"merkle-lib/fastRoot":110,"safe-buffer":117,"typeforce":135,"varuint-bitcoin":137}],13:[function(require,module,exports){ -var pushdata = require('pushdata-bitcoin') -var varuint = require('varuint-bitcoin') - -// https://github.com/feross/buffer/blob/master/index.js#L1127 -function verifuint (value, max) { - if (typeof value !== 'number') throw new Error('cannot write a non-number as a number') - if (value < 0) throw new Error('specified a negative value for writing an unsigned value') - if (value > max) throw new Error('RangeError: value out of range') - if (Math.floor(value) !== value) throw new Error('value has a fractional component') -} - -function readUInt64LE (buffer, offset) { - var a = buffer.readUInt32LE(offset) - var b = buffer.readUInt32LE(offset + 4) - b *= 0x100000000 - - verifuint(b + a, 0x001fffffffffffff) - - return b + a -} - -function writeUInt64LE (buffer, value, offset) { - verifuint(value, 0x001fffffffffffff) - - buffer.writeInt32LE(value & -1, offset) - buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4) - return offset + 8 -} - -// TODO: remove in 4.0.0? -function readVarInt (buffer, offset) { - var result = varuint.decode(buffer, offset) - - return { - number: result, - size: varuint.decode.bytes - } -} - -// TODO: remove in 4.0.0? -function writeVarInt (buffer, number, offset) { - varuint.encode(number, buffer, offset) - return varuint.encode.bytes -} - -module.exports = { - pushDataSize: pushdata.encodingLength, - readPushDataInt: pushdata.decode, - readUInt64LE: readUInt64LE, - readVarInt: readVarInt, - varIntBuffer: varuint.encode, - varIntSize: varuint.encodingLength, - writePushDataInt: pushdata.encode, - writeUInt64LE: writeUInt64LE, - writeVarInt: writeVarInt -} - -},{"pushdata-bitcoin":113,"varuint-bitcoin":137}],14:[function(require,module,exports){ -var createHash = require('create-hash') - -function ripemd160 (buffer) { - return createHash('rmd160').update(buffer).digest() -} - -function sha1 (buffer) { - return createHash('sha1').update(buffer).digest() -} - -function sha256 (buffer) { - return createHash('sha256').update(buffer).digest() -} - -function hash160 (buffer) { - return ripemd160(sha256(buffer)) -} - -function hash256 (buffer) { - return sha256(sha256(buffer)) -} - -module.exports = { - hash160: hash160, - hash256: hash256, - ripemd160: ripemd160, - sha1: sha1, - sha256: sha256 -} - -},{"create-hash":54}],15:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var createHmac = require('create-hmac') -var typeforce = require('typeforce') -var types = require('./types') - -var BigInteger = require('bigi') -var ECSignature = require('./ecsignature') - -var ZERO = Buffer.alloc(1, 0) -var ONE = Buffer.alloc(1, 1) - -var ecurve = require('ecurve') -var secp256k1 = ecurve.getCurveByName('secp256k1') - -// https://tools.ietf.org/html/rfc6979#section-3.2 -function deterministicGenerateK (hash, x, checkSig) { - typeforce(types.tuple( - types.Hash256bit, - types.Buffer256bit, - types.Function - ), arguments) - - // Step A, ignored as hash already provided - // Step B - // Step C - var k = Buffer.alloc(32, 0) - var v = Buffer.alloc(32, 1) - - // Step D - k = createHmac('sha256', k) - .update(v) - .update(ZERO) - .update(x) - .update(hash) - .digest() - - // Step E - v = createHmac('sha256', k).update(v).digest() - - // Step F - k = createHmac('sha256', k) - .update(v) - .update(ONE) - .update(x) - .update(hash) - .digest() - - // Step G - v = createHmac('sha256', k).update(v).digest() - - // Step H1/H2a, ignored as tlen === qlen (256 bit) - // Step H2b - v = createHmac('sha256', k).update(v).digest() - - var T = BigInteger.fromBuffer(v) - - // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA - while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) { - k = createHmac('sha256', k) - .update(v) - .update(ZERO) - .digest() - - v = createHmac('sha256', k).update(v).digest() - - // Step H1/H2a, again, ignored as tlen === qlen (256 bit) - // Step H2b again - v = createHmac('sha256', k).update(v).digest() - T = BigInteger.fromBuffer(v) - } - - return T -} - -var N_OVER_TWO = secp256k1.n.shiftRight(1) - -function sign (hash, d) { - typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments) - - var x = d.toBuffer(32) - var e = BigInteger.fromBuffer(hash) - var n = secp256k1.n - var G = secp256k1.G - - var r, s - deterministicGenerateK(hash, x, function (k) { - var Q = G.multiply(k) - - if (secp256k1.isInfinity(Q)) return false - - r = Q.affineX.mod(n) - if (r.signum() === 0) return false - - s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n) - if (s.signum() === 0) return false - - return true - }) - - // enforce low S values, see bip62: 'low s values in signatures' - if (s.compareTo(N_OVER_TWO) > 0) { - s = n.subtract(s) - } - - return new ECSignature(r, s) -} - -function verify (hash, signature, Q) { - typeforce(types.tuple( - types.Hash256bit, - types.ECSignature, - types.ECPoint - ), arguments) - - var n = secp256k1.n - var G = secp256k1.G - - var r = signature.r - var s = signature.s - - // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] - if (r.signum() <= 0 || r.compareTo(n) >= 0) return false - if (s.signum() <= 0 || s.compareTo(n) >= 0) return false - - // 1.4.2 H = Hash(M), already done by the user - // 1.4.3 e = H - var e = BigInteger.fromBuffer(hash) - - // Compute s^-1 - var sInv = s.modInverse(n) - - // 1.4.4 Compute u1 = es^−1 mod n - // u2 = rs^−1 mod n - var u1 = e.multiply(sInv).mod(n) - var u2 = r.multiply(sInv).mod(n) - - // 1.4.5 Compute R = (xR, yR) - // R = u1G + u2Q - var R = G.multiplyTwo(u1, Q, u2) - - // 1.4.5 (cont.) Enforce R is not at infinity - if (secp256k1.isInfinity(R)) return false - - // 1.4.6 Convert the field element R.x to an integer - var xR = R.affineX - - // 1.4.7 Set v = xR mod n - var v = xR.mod(n) - - // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" - return v.equals(r) -} - -module.exports = { - deterministicGenerateK: deterministicGenerateK, - sign: sign, - verify: verify, - - // TODO: remove - __curve: secp256k1 -} - -},{"./ecsignature":17,"./types":47,"bigi":6,"create-hmac":56,"ecurve":60,"safe-buffer":117,"typeforce":135}],16:[function(require,module,exports){ -var baddress = require('./address') -var bcrypto = require('./crypto') -var ecdsa = require('./ecdsa') -var randomBytes = require('randombytes') -var typeforce = require('typeforce') -var types = require('./types') -var wif = require('wif') - -var NETWORKS = require('./networks') -var BigInteger = require('bigi') - -var ecurve = require('ecurve') -var secp256k1 = ecdsa.__curve - -function ECPair (d, Q, options) { - if (options) { - typeforce({ - compressed: types.maybe(types.Boolean), - network: types.maybe(types.Network) - }, options) - } - - options = options || {} - - if (d) { - if (d.signum() <= 0) throw new Error('Private key must be greater than 0') - if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order') - if (Q) throw new TypeError('Unexpected publicKey parameter') - - this.d = d - } else { - typeforce(types.ECPoint, Q) - - this.__Q = Q - } - - this.compressed = options.compressed === undefined ? true : options.compressed - this.network = options.network || NETWORKS.bitcoin -} - -Object.defineProperty(ECPair.prototype, 'Q', { - get: function () { - if (!this.__Q && this.d) { - this.__Q = secp256k1.G.multiply(this.d) - } - - return this.__Q - } -}) - -ECPair.fromPublicKeyBuffer = function (buffer, network) { - var Q = ecurve.Point.decodeFrom(secp256k1, buffer) - - return new ECPair(null, Q, { - compressed: Q.compressed, - network: network - }) -} - -ECPair.fromWIF = function (string, network) { - var decoded = wif.decode(string) - var version = decoded.version - - // list of networks? - if (types.Array(network)) { - network = network.filter(function (x) { - return version === x.wif - }).pop() - - if (!network) throw new Error('Unknown network version') - - // otherwise, assume a network object (or default to bitcoin) - } else { - network = network || NETWORKS.bitcoin - - if (version !== network.wif) throw new Error('Invalid network version') - } - - var d = BigInteger.fromBuffer(decoded.privateKey) - - return new ECPair(d, null, { - compressed: decoded.compressed, - network: network - }) -} - -ECPair.makeRandom = function (options) { - options = options || {} - - var rng = options.rng || randomBytes - - var d - do { - var buffer = rng(32) - typeforce(types.Buffer256bit, buffer) - - d = BigInteger.fromBuffer(buffer) - } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0) - - return new ECPair(d, null, options) -} - -ECPair.prototype.getAddress = function () { - return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash) -} - -ECPair.prototype.getNetwork = function () { - return this.network -} - -ECPair.prototype.getPublicKeyBuffer = function () { - return this.Q.getEncoded(this.compressed) -} - -ECPair.prototype.sign = function (hash) { - if (!this.d) throw new Error('Missing private key') - - return ecdsa.sign(hash, this.d) -} - -ECPair.prototype.toWIF = function () { - if (!this.d) throw new Error('Missing private key') - - return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed) -} - -ECPair.prototype.verify = function (hash, signature) { - return ecdsa.verify(hash, signature, this.Q) -} - -module.exports = ECPair - -},{"./address":11,"./crypto":14,"./ecdsa":15,"./networks":20,"./types":47,"bigi":6,"ecurve":60,"randombytes":114,"typeforce":135,"wif":142}],17:[function(require,module,exports){ -(function (Buffer){ -var bip66 = require('bip66') -var typeforce = require('typeforce') -var types = require('./types') - -var BigInteger = require('bigi') - -function ECSignature (r, s) { - typeforce(types.tuple(types.BigInt, types.BigInt), arguments) - - this.r = r - this.s = s -} - -ECSignature.parseCompact = function (buffer) { - typeforce(types.BufferN(65), buffer) - - var flagByte = buffer.readUInt8(0) - 27 - if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter') - - var compressed = !!(flagByte & 4) - var recoveryParam = flagByte & 3 - var signature = ECSignature.fromRSBuffer(buffer.slice(1)) - - return { - compressed: compressed, - i: recoveryParam, - signature: signature - } -} - -ECSignature.fromRSBuffer = function (buffer) { - typeforce(types.BufferN(64), buffer) - - var r = BigInteger.fromBuffer(buffer.slice(0, 32)) - var s = BigInteger.fromBuffer(buffer.slice(32, 64)) - return new ECSignature(r, s) -} - -ECSignature.fromDER = function (buffer) { - var decode = bip66.decode(buffer) - var r = BigInteger.fromDERInteger(decode.r) - var s = BigInteger.fromDERInteger(decode.s) - - return new ECSignature(r, s) -} - -// BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) -ECSignature.parseScriptSignature = function (buffer) { - var hashType = buffer.readUInt8(buffer.length - 1) - var hashTypeMod = hashType & ~0x80 - - if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType) - - return { - signature: ECSignature.fromDER(buffer.slice(0, -1)), - hashType: hashType - } -} - -ECSignature.prototype.toCompact = function (i, compressed) { - if (compressed) { - i += 4 - } - - i += 27 - - var buffer = Buffer.alloc(65) - buffer.writeUInt8(i, 0) - this.toRSBuffer(buffer, 1) - return buffer -} - -ECSignature.prototype.toDER = function () { - var r = Buffer.from(this.r.toDERInteger()) - var s = Buffer.from(this.s.toDERInteger()) - - return bip66.encode(r, s) -} - -ECSignature.prototype.toRSBuffer = function (buffer, offset) { - buffer = buffer || Buffer.alloc(64) - this.r.toBuffer(32).copy(buffer, offset) - this.s.toBuffer(32).copy(buffer, offset + 32) - return buffer -} - -ECSignature.prototype.toScriptSignature = function (hashType) { - var hashTypeMod = hashType & ~0x80 - if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType) - - var hashTypeBuffer = Buffer.alloc(1) - hashTypeBuffer.writeUInt8(hashType, 0) - - return Buffer.concat([this.toDER(), hashTypeBuffer]) -} - -module.exports = ECSignature - -}).call(this,require("buffer").Buffer) -},{"./types":47,"bigi":6,"bip66":8,"buffer":149,"typeforce":135}],18:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var base58check = require('bs58check') -var bcrypto = require('./crypto') -var createHmac = require('create-hmac') -var typeforce = require('typeforce') -var types = require('./types') -var NETWORKS = require('./networks') - -var BigInteger = require('bigi') -var ECPair = require('./ecpair') - -var ecurve = require('ecurve') -var curve = ecurve.getCurveByName('secp256k1') - -function HDNode (keyPair, chainCode) { - typeforce(types.tuple('ECPair', types.Buffer256bit), arguments) - - if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs') - - this.keyPair = keyPair - this.chainCode = chainCode - this.depth = 0 - this.index = 0 - this.parentFingerprint = 0x00000000 -} - -HDNode.HIGHEST_BIT = 0x80000000 -HDNode.LENGTH = 78 -HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8') - -HDNode.fromSeedBuffer = function (seed, network) { - typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments) - - if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits') - if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits') - - var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest() - var IL = I.slice(0, 32) - var IR = I.slice(32) - - // In case IL is 0 or >= n, the master key is invalid - // This is handled by the ECPair constructor - var pIL = BigInteger.fromBuffer(IL) - var keyPair = new ECPair(pIL, null, { - network: network - }) - - return new HDNode(keyPair, IR) -} - -HDNode.fromSeedHex = function (hex, network) { - return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network) -} - -HDNode.fromBase58 = function (string, networks) { - var buffer = base58check.decode(string) - if (buffer.length !== 78) throw new Error('Invalid buffer length') - - // 4 bytes: version bytes - var version = buffer.readUInt32BE(0) - var network - - // list of networks? - if (Array.isArray(networks)) { - network = networks.filter(function (x) { - return version === x.bip32.private || - version === x.bip32.public - }).pop() - - if (!network) throw new Error('Unknown network version') - - // otherwise, assume a network object (or default to bitcoin) - } else { - network = networks || NETWORKS.bitcoin - } - - if (version !== network.bip32.private && - version !== network.bip32.public) throw new Error('Invalid network version') - - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... - var depth = buffer[4] - - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - var parentFingerprint = buffer.readUInt32BE(5) - if (depth === 0) { - if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint') - } - - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in MSB order. (0x00000000 if master key) - var index = buffer.readUInt32BE(9) - if (depth === 0 && index !== 0) throw new Error('Invalid index') - - // 32 bytes: the chain code - var chainCode = buffer.slice(13, 45) - var keyPair - - // 33 bytes: private key data (0x00 + k) - if (version === network.bip32.private) { - if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key') - - var d = BigInteger.fromBuffer(buffer.slice(46, 78)) - keyPair = new ECPair(d, null, { network: network }) - - // 33 bytes: public key data (0x02 + X or 0x03 + X) - } else { - var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78)) - // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw - - // Verify that the X coordinate in the public point corresponds to a point on the curve. - // If not, the extended public key is invalid. - curve.validate(Q) - - keyPair = new ECPair(null, Q, { network: network }) - } - - var hd = new HDNode(keyPair, chainCode) - hd.depth = depth - hd.index = index - hd.parentFingerprint = parentFingerprint - - return hd -} - -HDNode.prototype.getAddress = function () { - return this.keyPair.getAddress() -} - -HDNode.prototype.getIdentifier = function () { - return bcrypto.hash160(this.keyPair.getPublicKeyBuffer()) -} - -HDNode.prototype.getFingerprint = function () { - return this.getIdentifier().slice(0, 4) -} - -HDNode.prototype.getNetwork = function () { - return this.keyPair.getNetwork() -} - -HDNode.prototype.getPublicKeyBuffer = function () { - return this.keyPair.getPublicKeyBuffer() -} - -HDNode.prototype.neutered = function () { - var neuteredKeyPair = new ECPair(null, this.keyPair.Q, { - network: this.keyPair.network - }) - - var neutered = new HDNode(neuteredKeyPair, this.chainCode) - neutered.depth = this.depth - neutered.index = this.index - neutered.parentFingerprint = this.parentFingerprint - - return neutered -} - -HDNode.prototype.sign = function (hash) { - return this.keyPair.sign(hash) -} - -HDNode.prototype.verify = function (hash, signature) { - return this.keyPair.verify(hash, signature) -} - -HDNode.prototype.toBase58 = function (__isPrivate) { - if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0') - - // Version - var network = this.keyPair.network - var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public - var buffer = Buffer.allocUnsafe(78) - - // 4 bytes: version bytes - buffer.writeUInt32BE(version, 0) - - // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... - buffer.writeUInt8(this.depth, 4) - - // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) - buffer.writeUInt32BE(this.parentFingerprint, 5) - - // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. - // This is encoded in big endian. (0x00000000 if master key) - buffer.writeUInt32BE(this.index, 9) - - // 32 bytes: the chain code - this.chainCode.copy(buffer, 13) - - // 33 bytes: the public key or private key data - if (!this.isNeutered()) { - // 0x00 + k for private keys - buffer.writeUInt8(0, 45) - this.keyPair.d.toBuffer(32).copy(buffer, 46) - - // 33 bytes: the public key - } else { - // X9.62 encoding for public keys - this.keyPair.getPublicKeyBuffer().copy(buffer, 45) - } - - return base58check.encode(buffer) -} - -// https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions -HDNode.prototype.derive = function (index) { - typeforce(types.UInt32, index) - - var isHardened = index >= HDNode.HIGHEST_BIT - var data = Buffer.allocUnsafe(37) - - // Hardened child - if (isHardened) { - if (this.isNeutered()) throw new TypeError('Could not derive hardened child key') - - // data = 0x00 || ser256(kpar) || ser32(index) - data[0] = 0x00 - this.keyPair.d.toBuffer(32).copy(data, 1) - data.writeUInt32BE(index, 33) - - // Normal child - } else { - // data = serP(point(kpar)) || ser32(index) - // = serP(Kpar) || ser32(index) - this.keyPair.getPublicKeyBuffer().copy(data, 0) - data.writeUInt32BE(index, 33) - } - - var I = createHmac('sha512', this.chainCode).update(data).digest() - var IL = I.slice(0, 32) - var IR = I.slice(32) - - var pIL = BigInteger.fromBuffer(IL) - - // In case parse256(IL) >= n, proceed with the next value for i - if (pIL.compareTo(curve.n) >= 0) { - return this.derive(index + 1) - } - - // Private parent key -> private child key - var derivedKeyPair - if (!this.isNeutered()) { - // ki = parse256(IL) + kpar (mod n) - var ki = pIL.add(this.keyPair.d).mod(curve.n) - - // In case ki == 0, proceed with the next value for i - if (ki.signum() === 0) { - return this.derive(index + 1) - } - - derivedKeyPair = new ECPair(ki, null, { - network: this.keyPair.network - }) - - // Public parent key -> public child key - } else { - // Ki = point(parse256(IL)) + Kpar - // = G*IL + Kpar - var Ki = curve.G.multiply(pIL).add(this.keyPair.Q) - - // In case Ki is the point at infinity, proceed with the next value for i - if (curve.isInfinity(Ki)) { - return this.derive(index + 1) - } - - derivedKeyPair = new ECPair(null, Ki, { - network: this.keyPair.network - }) - } - - var hd = new HDNode(derivedKeyPair, IR) - hd.depth = this.depth + 1 - hd.index = index - hd.parentFingerprint = this.getFingerprint().readUInt32BE(0) - - return hd -} - -HDNode.prototype.deriveHardened = function (index) { - typeforce(types.UInt31, index) - - // Only derives hardened private keys by default - return this.derive(index + HDNode.HIGHEST_BIT) -} - -// Private === not neutered -// Public === neutered -HDNode.prototype.isNeutered = function () { - return !(this.keyPair.d) -} - -HDNode.prototype.derivePath = function (path) { - typeforce(types.BIP32Path, path) - - var splitPath = path.split('/') - if (splitPath[0] === 'm') { - if (this.parentFingerprint) { - throw new Error('Not a master node') - } - - splitPath = splitPath.slice(1) - } - - return splitPath.reduce(function (prevHd, indexStr) { - var index - if (indexStr.slice(-1) === "'") { - index = parseInt(indexStr.slice(0, -1), 10) - return prevHd.deriveHardened(index) - } else { - index = parseInt(indexStr, 10) - return prevHd.derive(index) - } - }, this) -} - -module.exports = HDNode - -},{"./crypto":14,"./ecpair":16,"./networks":20,"./types":47,"bigi":6,"bs58check":52,"create-hmac":56,"ecurve":60,"safe-buffer":117,"typeforce":135}],19:[function(require,module,exports){ -var script = require('./script') - -var templates = require('./templates') -for (var key in templates) { - script[key] = templates[key] -} - -module.exports = { - bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0 - - Block: require('./block'), - ECPair: require('./ecpair'), - ECSignature: require('./ecsignature'), - HDNode: require('./hdnode'), - Transaction: require('./transaction'), - TransactionBuilder: require('./transaction_builder'), - - address: require('./address'), - crypto: require('./crypto'), - networks: require('./networks'), - opcodes: require('bitcoin-ops'), - script: script -} - -},{"./address":11,"./block":12,"./bufferutils":13,"./crypto":14,"./ecpair":16,"./ecsignature":17,"./hdnode":18,"./networks":20,"./script":21,"./templates":23,"./transaction":45,"./transaction_builder":46,"bitcoin-ops":9}],20:[function(require,module,exports){ -// https://en.bitcoin.it/wiki/List_of_address_prefixes -// Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 - -module.exports = { - bitcoin: { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'bc', - bip32: { - public: 0x0488b21e, - private: 0x0488ade4 - }, - pubKeyHash: 0x00, - scriptHash: 0x05, - wif: 0x80 - }, - testnet: { - messagePrefix: '\x18Bitcoin Signed Message:\n', - bech32: 'tb', - bip32: { - public: 0x043587cf, - private: 0x04358394 - }, - pubKeyHash: 0x6f, - scriptHash: 0xc4, - wif: 0xef - }, - litecoin: { - messagePrefix: '\x19Litecoin Signed Message:\n', - bip32: { - public: 0x019da462, - private: 0x019d9cfe - }, - pubKeyHash: 0x30, - scriptHash: 0x32, - wif: 0xb0 - } -} - -},{}],21:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bip66 = require('bip66') -var pushdata = require('pushdata-bitcoin') -var typeforce = require('typeforce') -var types = require('./types') -var scriptNumber = require('./script_number') - -var OPS = require('bitcoin-ops') -var REVERSE_OPS = require('bitcoin-ops/map') -var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 - -function isOPInt (value) { - return types.Number(value) && - ((value === OPS.OP_0) || - (value >= OPS.OP_1 && value <= OPS.OP_16) || - (value === OPS.OP_1NEGATE)) -} - -function isPushOnlyChunk (value) { - return types.Buffer(value) || isOPInt(value) -} - -function isPushOnly (value) { - return types.Array(value) && value.every(isPushOnlyChunk) -} - -function asMinimalOP (buffer) { - if (buffer.length === 0) return OPS.OP_0 - if (buffer.length !== 1) return - if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0] - if (buffer[0] === 0x81) return OPS.OP_1NEGATE -} - -function compile (chunks) { - // TODO: remove me - if (Buffer.isBuffer(chunks)) return chunks - - typeforce(types.Array, chunks) - - var bufferSize = chunks.reduce(function (accum, chunk) { - // data chunk - if (Buffer.isBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { - return accum + 1 - } - - return accum + pushdata.encodingLength(chunk.length) + chunk.length - } - - // opcode - return accum + 1 - }, 0.0) - - var buffer = Buffer.allocUnsafe(bufferSize) - var offset = 0 - - chunks.forEach(function (chunk) { - // data chunk - if (Buffer.isBuffer(chunk)) { - // adhere to BIP62.3, minimal push policy - var opcode = asMinimalOP(chunk) - if (opcode !== undefined) { - buffer.writeUInt8(opcode, offset) - offset += 1 - return - } - - offset += pushdata.encode(buffer, chunk.length, offset) - chunk.copy(buffer, offset) - offset += chunk.length - - // opcode - } else { - buffer.writeUInt8(chunk, offset) - offset += 1 - } - }) - - if (offset !== buffer.length) throw new Error('Could not decode chunks') - return buffer -} - -function decompile (buffer) { - // TODO: remove me - if (types.Array(buffer)) return buffer - - typeforce(types.Buffer, buffer) - - var chunks = [] - var i = 0 - - while (i < buffer.length) { - var opcode = buffer[i] - - // data chunk - if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) { - var d = pushdata.decode(buffer, i) - - // did reading a pushDataInt fail? empty script - if (d === null) return [] - i += d.size - - // attempt to read too much data? empty script - if (i + d.number > buffer.length) return [] - - var data = buffer.slice(i, i + d.number) - i += d.number - - // decompile minimally - var op = asMinimalOP(data) - if (op !== undefined) { - chunks.push(op) - } else { - chunks.push(data) - } - - // opcode - } else { - chunks.push(opcode) - - i += 1 - } - } - - return chunks -} - -function toASM (chunks) { - if (Buffer.isBuffer(chunks)) { - chunks = decompile(chunks) - } - - return chunks.map(function (chunk) { - // data? - if (Buffer.isBuffer(chunk)) { - var op = asMinimalOP(chunk) - if (op === undefined) return chunk.toString('hex') - chunk = op - } - - // opcode! - return REVERSE_OPS[chunk] - }).join(' ') -} - -function fromASM (asm) { - typeforce(types.String, asm) - - return compile(asm.split(' ').map(function (chunkStr) { - // opcode? - if (OPS[chunkStr] !== undefined) return OPS[chunkStr] - typeforce(types.Hex, chunkStr) - - // data! - return Buffer.from(chunkStr, 'hex') - })) -} - -function toStack (chunks) { - chunks = decompile(chunks) - typeforce(isPushOnly, chunks) - - return chunks.map(function (op) { - if (Buffer.isBuffer(op)) return op - if (op === OPS.OP_0) return Buffer.allocUnsafe(0) - - return scriptNumber.encode(op - OP_INT_BASE) - }) -} - -function isCanonicalPubKey (buffer) { - if (!Buffer.isBuffer(buffer)) return false - if (buffer.length < 33) return false - - switch (buffer[0]) { - case 0x02: - case 0x03: - return buffer.length === 33 - case 0x04: - return buffer.length === 65 - } - - return false -} - -function isDefinedHashType (hashType) { - var hashTypeMod = hashType & ~0x80 - -// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE - return hashTypeMod > 0x00 && hashTypeMod < 0x04 -} - -function isCanonicalSignature (buffer) { - if (!Buffer.isBuffer(buffer)) return false - if (!isDefinedHashType(buffer[buffer.length - 1])) return false - - return bip66.check(buffer.slice(0, -1)) -} - -module.exports = { - compile: compile, - decompile: decompile, - fromASM: fromASM, - toASM: toASM, - toStack: toStack, - - number: require('./script_number'), - - isCanonicalPubKey: isCanonicalPubKey, - isCanonicalSignature: isCanonicalSignature, - isPushOnly: isPushOnly, - isDefinedHashType: isDefinedHashType -} - -},{"./script_number":22,"./types":47,"bip66":8,"bitcoin-ops":9,"bitcoin-ops/map":10,"pushdata-bitcoin":113,"safe-buffer":117,"typeforce":135}],22:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -function decode (buffer, maxLength, minimal) { - maxLength = maxLength || 4 - minimal = minimal === undefined ? true : minimal - - var length = buffer.length - if (length === 0) return 0 - if (length > maxLength) throw new TypeError('Script number overflow') - if (minimal) { - if ((buffer[length - 1] & 0x7f) === 0) { - if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number') - } - } - - // 40-bit - if (length === 5) { - var a = buffer.readUInt32LE(0) - var b = buffer.readUInt8(4) - - if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a) - return (b * 0x100000000) + a - } - - var result = 0 - - // 32-bit / 24-bit / 16-bit / 8-bit - for (var i = 0; i < length; ++i) { - result |= buffer[i] << (8 * i) - } - - if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1)))) - return result -} - -function scriptNumSize (i) { - return i > 0x7fffffff ? 5 - : i > 0x7fffff ? 4 - : i > 0x7fff ? 3 - : i > 0x7f ? 2 - : i > 0x00 ? 1 - : 0 -} - -function encode (number) { - var value = Math.abs(number) - var size = scriptNumSize(value) - var buffer = Buffer.allocUnsafe(size) - var negative = number < 0 - - for (var i = 0; i < size; ++i) { - buffer.writeUInt8(value & 0xff, i) - value >>= 8 - } - - if (buffer[size - 1] & 0x80) { - buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1) - } else if (negative) { - buffer[size - 1] |= 0x80 - } - - return buffer -} - -module.exports = { - decode: decode, - encode: encode -} - -},{"safe-buffer":117}],23:[function(require,module,exports){ -var decompile = require('../script').decompile -var multisig = require('./multisig') -var nullData = require('./nulldata') -var pubKey = require('./pubkey') -var pubKeyHash = require('./pubkeyhash') -var scriptHash = require('./scripthash') -var witnessPubKeyHash = require('./witnesspubkeyhash') -var witnessScriptHash = require('./witnessscripthash') -var witnessCommitment = require('./witnesscommitment') - -var types = { - MULTISIG: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment' -} - -function classifyOutput (script) { - if (witnessPubKeyHash.output.check(script)) return types.P2WPKH - if (witnessScriptHash.output.check(script)) return types.P2WSH - if (pubKeyHash.output.check(script)) return types.P2PKH - if (scriptHash.output.check(script)) return types.P2SH - - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) - if (multisig.output.check(chunks)) return types.MULTISIG - if (pubKey.output.check(chunks)) return types.P2PK - if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT - if (nullData.output.check(chunks)) return types.NULLDATA - - return types.NONSTANDARD -} - -function classifyInput (script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) - - if (pubKeyHash.input.check(chunks)) return types.P2PKH - if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH - if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG - if (pubKey.input.check(chunks)) return types.P2PK - - return types.NONSTANDARD -} - -function classifyWitness (script, allowIncomplete) { - // XXX: optimization, below functions .decompile before use - var chunks = decompile(script) - - if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH - if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH - - return types.NONSTANDARD -} - -module.exports = { - classifyInput: classifyInput, - classifyOutput: classifyOutput, - classifyWitness: classifyWitness, - multisig: multisig, - nullData: nullData, - pubKey: pubKey, - pubKeyHash: pubKeyHash, - scriptHash: scriptHash, - witnessPubKeyHash: witnessPubKeyHash, - witnessScriptHash: witnessScriptHash, - witnessCommitment: witnessCommitment, - types: types -} - -},{"../script":21,"./multisig":24,"./nulldata":27,"./pubkey":28,"./pubkeyhash":31,"./scripthash":34,"./witnesscommitment":37,"./witnesspubkeyhash":39,"./witnessscripthash":42}],24:[function(require,module,exports){ -module.exports = { - input: require('./input'), - output: require('./output') -} - -},{"./input":25,"./output":26}],25:[function(require,module,exports){ -// OP_0 [signatures ...] - -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var p2mso = require('./output') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function partialSignature (value) { - return value === OPS.OP_0 || bscript.isCanonicalSignature(value) -} - -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) - if (chunks.length < 2) return false - if (chunks[0] !== OPS.OP_0) return false - - if (allowIncomplete) { - return chunks.slice(1).every(partialSignature) - } - - return chunks.slice(1).every(bscript.isCanonicalSignature) -} -check.toJSON = function () { return 'multisig input' } - -var EMPTY_BUFFER = Buffer.allocUnsafe(0) - -function encodeStack (signatures, scriptPubKey) { - typeforce([partialSignature], signatures) - - if (scriptPubKey) { - var scriptData = p2mso.decode(scriptPubKey) - - if (signatures.length < scriptData.m) { - throw new TypeError('Not enough signatures provided') - } - - if (signatures.length > scriptData.pubKeys.length) { - throw new TypeError('Too many signatures provided') - } - } - - return [].concat(EMPTY_BUFFER, signatures.map(function (sig) { - if (sig === OPS.OP_0) { - return EMPTY_BUFFER - } - return sig - })) -} - -function encode (signatures, scriptPubKey) { - return bscript.compile(encodeStack(signatures, scriptPubKey)) -} - -function decodeStack (stack, allowIncomplete) { - typeforce(typeforce.Array, stack) - typeforce(check, stack, allowIncomplete) - return stack.slice(1) -} - -function decode (buffer, allowIncomplete) { - var stack = bscript.decompile(buffer) - return decodeStack(stack, allowIncomplete) -} - -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} - -},{"../../script":21,"./output":26,"bitcoin-ops":9,"safe-buffer":117,"typeforce":135}],26:[function(require,module,exports){ -// m [pubKeys ...] n OP_CHECKMULTISIG - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') -var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 - -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) - - if (chunks.length < 4) return false - if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false - if (!types.Number(chunks[0])) return false - if (!types.Number(chunks[chunks.length - 2])) return false - var m = chunks[0] - OP_INT_BASE - var n = chunks[chunks.length - 2] - OP_INT_BASE - - if (m <= 0) return false - if (n > 16) return false - if (m > n) return false - if (n !== chunks.length - 3) return false - if (allowIncomplete) return true - - var keys = chunks.slice(1, -2) - return keys.every(bscript.isCanonicalPubKey) -} -check.toJSON = function () { return 'multi-sig output' } - -function encode (m, pubKeys) { - typeforce({ - m: types.Number, - pubKeys: [bscript.isCanonicalPubKey] - }, { - m: m, - pubKeys: pubKeys - }) - - var n = pubKeys.length - if (n < m) throw new TypeError('Not enough pubKeys provided') - - return bscript.compile([].concat( - OP_INT_BASE + m, - pubKeys, - OP_INT_BASE + n, - OPS.OP_CHECKMULTISIG - )) -} - -function decode (buffer, allowIncomplete) { - var chunks = bscript.decompile(buffer) - typeforce(check, chunks, allowIncomplete) - - return { - m: chunks[0] - OP_INT_BASE, - pubKeys: chunks.slice(1, -2) - } -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"typeforce":135}],27:[function(require,module,exports){ -// OP_RETURN {data} - -var bscript = require('../script') -var types = require('../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length > 1 && - buffer[0] === OPS.OP_RETURN -} -check.toJSON = function () { return 'null data output' } - -function encode (data) { - typeforce(types.Buffer, data) - - return bscript.compile([OPS.OP_RETURN, data]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return buffer.slice(2) -} - -module.exports = { - output: { - check: check, - decode: decode, - encode: encode - } -} - -},{"../script":21,"../types":47,"bitcoin-ops":9,"typeforce":135}],28:[function(require,module,exports){ -arguments[4][24][0].apply(exports,arguments) -},{"./input":29,"./output":30,"dup":24}],29:[function(require,module,exports){ -// {signature} - -var bscript = require('../../script') -var typeforce = require('typeforce') - -function check (script) { - var chunks = bscript.decompile(script) - - return chunks.length === 1 && - bscript.isCanonicalSignature(chunks[0]) -} -check.toJSON = function () { return 'pubKey input' } - -function encodeStack (signature) { - typeforce(bscript.isCanonicalSignature, signature) - return [signature] -} - -function encode (signature) { - return bscript.compile(encodeStack(signature)) -} - -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - return stack[0] -} - -function decode (buffer) { - var stack = bscript.decompile(buffer) - return decodeStack(stack) -} - -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} - -},{"../../script":21,"typeforce":135}],30:[function(require,module,exports){ -// {pubKey} OP_CHECKSIG - -var bscript = require('../../script') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var chunks = bscript.decompile(script) - - return chunks.length === 2 && - bscript.isCanonicalPubKey(chunks[0]) && - chunks[1] === OPS.OP_CHECKSIG -} -check.toJSON = function () { return 'pubKey output' } - -function encode (pubKey) { - typeforce(bscript.isCanonicalPubKey, pubKey) - - return bscript.compile([pubKey, OPS.OP_CHECKSIG]) -} - -function decode (buffer) { - var chunks = bscript.decompile(buffer) - typeforce(check, chunks) - - return chunks[0] -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"bitcoin-ops":9,"typeforce":135}],31:[function(require,module,exports){ -arguments[4][24][0].apply(exports,arguments) -},{"./input":32,"./output":33,"dup":24}],32:[function(require,module,exports){ -// {signature} {pubKey} - -var bscript = require('../../script') -var typeforce = require('typeforce') - -function check (script) { - var chunks = bscript.decompile(script) - - return chunks.length === 2 && - bscript.isCanonicalSignature(chunks[0]) && - bscript.isCanonicalPubKey(chunks[1]) -} -check.toJSON = function () { return 'pubKeyHash input' } - -function encodeStack (signature, pubKey) { - typeforce({ - signature: bscript.isCanonicalSignature, - pubKey: bscript.isCanonicalPubKey - }, { - signature: signature, - pubKey: pubKey - }) - - return [signature, pubKey] -} - -function encode (signature, pubKey) { - return bscript.compile(encodeStack(signature, pubKey)) -} - -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - - return { - signature: stack[0], - pubKey: stack[1] - } -} - -function decode (buffer) { - var stack = bscript.decompile(buffer) - return decodeStack(stack) -} - -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} - -},{"../../script":21,"typeforce":135}],33:[function(require,module,exports){ -// OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length === 25 && - buffer[0] === OPS.OP_DUP && - buffer[1] === OPS.OP_HASH160 && - buffer[2] === 0x14 && - buffer[23] === OPS.OP_EQUALVERIFY && - buffer[24] === OPS.OP_CHECKSIG -} -check.toJSON = function () { return 'pubKeyHash output' } - -function encode (pubKeyHash) { - typeforce(types.Hash160bit, pubKeyHash) - - return bscript.compile([ - OPS.OP_DUP, - OPS.OP_HASH160, - pubKeyHash, - OPS.OP_EQUALVERIFY, - OPS.OP_CHECKSIG - ]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return buffer.slice(3, 23) -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"typeforce":135}],34:[function(require,module,exports){ -arguments[4][24][0].apply(exports,arguments) -},{"./input":35,"./output":36,"dup":24}],35:[function(require,module,exports){ -// {serialized scriptPubKey script} - -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var typeforce = require('typeforce') - -var p2ms = require('../multisig/') -var p2pk = require('../pubkey/') -var p2pkh = require('../pubkeyhash/') -var p2wpkho = require('../witnesspubkeyhash/output') -var p2wsho = require('../witnessscripthash/output') - -function check (script, allowIncomplete) { - var chunks = bscript.decompile(script) - if (chunks.length < 1) return false - - var lastChunk = chunks[chunks.length - 1] - if (!Buffer.isBuffer(lastChunk)) return false - - var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1))) - var redeemScriptChunks = bscript.decompile(lastChunk) - - // is redeemScript a valid script? - if (redeemScriptChunks.length === 0) return false - - // is redeemScriptSig push only? - if (!bscript.isPushOnly(scriptSigChunks)) return false - - // is witness? - if (chunks.length === 1) { - return p2wsho.check(redeemScriptChunks) || - p2wpkho.check(redeemScriptChunks) - } - - // match types - if (p2pkh.input.check(scriptSigChunks) && - p2pkh.output.check(redeemScriptChunks)) return true - - if (p2ms.input.check(scriptSigChunks, allowIncomplete) && - p2ms.output.check(redeemScriptChunks)) return true - - if (p2pk.input.check(scriptSigChunks) && - p2pk.output.check(redeemScriptChunks)) return true - - return false -} -check.toJSON = function () { return 'scriptHash input' } - -function encodeStack (redeemScriptStack, redeemScript) { - var serializedScriptPubKey = bscript.compile(redeemScript) - - return [].concat(redeemScriptStack, serializedScriptPubKey) -} - -function encode (redeemScriptSig, redeemScript) { - var redeemScriptStack = bscript.decompile(redeemScriptSig) - - return bscript.compile(encodeStack(redeemScriptStack, redeemScript)) -} - -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - - return { - redeemScriptStack: stack.slice(0, -1), - redeemScript: stack[stack.length - 1] - } -} - -function decode (buffer) { - var stack = bscript.decompile(buffer) - var result = decodeStack(stack) - result.redeemScriptSig = bscript.compile(result.redeemScriptStack) - delete result.redeemScriptStack - return result -} - -module.exports = { - check: check, - decode: decode, - decodeStack: decodeStack, - encode: encode, - encodeStack: encodeStack -} - -},{"../../script":21,"../multisig/":24,"../pubkey/":28,"../pubkeyhash/":31,"../witnesspubkeyhash/output":41,"../witnessscripthash/output":44,"safe-buffer":117,"typeforce":135}],36:[function(require,module,exports){ -// OP_HASH160 {scriptHash} OP_EQUAL - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length === 23 && - buffer[0] === OPS.OP_HASH160 && - buffer[1] === 0x14 && - buffer[22] === OPS.OP_EQUAL -} -check.toJSON = function () { return 'scriptHash output' } - -function encode (scriptHash) { - typeforce(types.Hash160bit, scriptHash) - - return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return buffer.slice(2, 22) -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"typeforce":135}],37:[function(require,module,exports){ -module.exports = { - output: require('./output') -} - -},{"./output":38}],38:[function(require,module,exports){ -// OP_RETURN {aa21a9ed} {commitment} - -var Buffer = require('safe-buffer').Buffer -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -var HEADER = Buffer.from('aa21a9ed', 'hex') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length > 37 && - buffer[0] === OPS.OP_RETURN && - buffer[1] === 0x24 && - buffer.slice(2, 6).equals(HEADER) -} - -check.toJSON = function () { return 'Witness commitment output' } - -function encode (commitment) { - typeforce(types.Hash256bit, commitment) - - var buffer = Buffer.allocUnsafe(36) - HEADER.copy(buffer, 0) - commitment.copy(buffer, 4) - - return bscript.compile([OPS.OP_RETURN, buffer]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return bscript.decompile(buffer)[1].slice(4, 36) -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"safe-buffer":117,"typeforce":135}],39:[function(require,module,exports){ -arguments[4][24][0].apply(exports,arguments) -},{"./input":40,"./output":41,"dup":24}],40:[function(require,module,exports){ -// {signature} {pubKey} - -var bscript = require('../../script') -var typeforce = require('typeforce') - -function isCompressedCanonicalPubKey (pubKey) { - return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33 -} - -function check (script) { - var chunks = bscript.decompile(script) - - return chunks.length === 2 && - bscript.isCanonicalSignature(chunks[0]) && - isCompressedCanonicalPubKey(chunks[1]) -} -check.toJSON = function () { return 'witnessPubKeyHash input' } - -function encodeStack (signature, pubKey) { - typeforce({ - signature: bscript.isCanonicalSignature, - pubKey: isCompressedCanonicalPubKey - }, { - signature: signature, - pubKey: pubKey - }) - - return [signature, pubKey] -} - -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - - return { - signature: stack[0], - pubKey: stack[1] - } -} - -module.exports = { - check: check, - decodeStack: decodeStack, - encodeStack: encodeStack -} - -},{"../../script":21,"typeforce":135}],41:[function(require,module,exports){ -// OP_0 {pubKeyHash} - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length === 22 && - buffer[0] === OPS.OP_0 && - buffer[1] === 0x14 -} -check.toJSON = function () { return 'Witness pubKeyHash output' } - -function encode (pubKeyHash) { - typeforce(types.Hash160bit, pubKeyHash) - - return bscript.compile([OPS.OP_0, pubKeyHash]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return buffer.slice(2) -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"typeforce":135}],42:[function(require,module,exports){ -arguments[4][24][0].apply(exports,arguments) -},{"./input":43,"./output":44,"dup":24}],43:[function(require,module,exports){ -(function (Buffer){ -// {serialized scriptPubKey script} - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') - -var p2ms = require('../multisig/') -var p2pk = require('../pubkey/') -var p2pkh = require('../pubkeyhash/') - -function check (chunks, allowIncomplete) { - typeforce(types.Array, chunks) - if (chunks.length < 1) return false - - var witnessScript = chunks[chunks.length - 1] - if (!Buffer.isBuffer(witnessScript)) return false - - var witnessScriptChunks = bscript.decompile(witnessScript) - - // is witnessScript a valid script? - if (witnessScriptChunks.length === 0) return false - - var witnessRawScriptSig = bscript.compile(chunks.slice(0, -1)) - - // match types - if (p2pkh.input.check(witnessRawScriptSig) && - p2pkh.output.check(witnessScriptChunks)) return true - - if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) && - p2ms.output.check(witnessScriptChunks)) return true - - if (p2pk.input.check(witnessRawScriptSig) && - p2pk.output.check(witnessScriptChunks)) return true - - return false -} -check.toJSON = function () { return 'witnessScriptHash input' } - -function encodeStack (witnessData, witnessScript) { - typeforce({ - witnessData: [types.Buffer], - witnessScript: types.Buffer - }, { - witnessData: witnessData, - witnessScript: witnessScript - }) - - return [].concat(witnessData, witnessScript) -} - -function decodeStack (stack) { - typeforce(typeforce.Array, stack) - typeforce(check, stack) - return { - witnessData: stack.slice(0, -1), - witnessScript: stack[stack.length - 1] - } -} - -module.exports = { - check: check, - decodeStack: decodeStack, - encodeStack: encodeStack -} - -}).call(this,{"isBuffer":require("../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) -},{"../../../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":154,"../../script":21,"../../types":47,"../multisig/":24,"../pubkey/":28,"../pubkeyhash/":31,"typeforce":135}],44:[function(require,module,exports){ -// OP_0 {scriptHash} - -var bscript = require('../../script') -var types = require('../../types') -var typeforce = require('typeforce') -var OPS = require('bitcoin-ops') - -function check (script) { - var buffer = bscript.compile(script) - - return buffer.length === 34 && - buffer[0] === OPS.OP_0 && - buffer[1] === 0x20 -} -check.toJSON = function () { return 'Witness scriptHash output' } - -function encode (scriptHash) { - typeforce(types.Hash256bit, scriptHash) - - return bscript.compile([OPS.OP_0, scriptHash]) -} - -function decode (buffer) { - typeforce(check, buffer) - - return buffer.slice(2) -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"../../script":21,"../../types":47,"bitcoin-ops":9,"typeforce":135}],45:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var bcrypto = require('./crypto') -var bscript = require('./script') -var bufferutils = require('./bufferutils') -var opcodes = require('bitcoin-ops') -var typeforce = require('typeforce') -var types = require('./types') -var varuint = require('varuint-bitcoin') - -function varSliceSize (someScript) { - var length = someScript.length - - return varuint.encodingLength(length) + length -} - -function vectorSize (someVector) { - var length = someVector.length - - return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { - return sum + varSliceSize(witness) - }, 0) -} - -function Transaction () { - this.version = 1 - this.locktime = 0 - this.ins = [] - this.outs = [] -} - -Transaction.DEFAULT_SEQUENCE = 0xffffffff -Transaction.SIGHASH_ALL = 0x01 -Transaction.SIGHASH_NONE = 0x02 -Transaction.SIGHASH_SINGLE = 0x03 -Transaction.SIGHASH_ANYONECANPAY = 0x80 -Transaction.ADVANCED_TRANSACTION_MARKER = 0x00 -Transaction.ADVANCED_TRANSACTION_FLAG = 0x01 - -var EMPTY_SCRIPT = Buffer.allocUnsafe(0) -var EMPTY_WITNESS = [] -var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex') -var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex') -var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex') -var BLANK_OUTPUT = { - script: EMPTY_SCRIPT, - valueBuffer: VALUE_UINT64_MAX -} - -Transaction.fromBuffer = function (buffer, __noStrict) { - var offset = 0 - function readSlice (n) { - offset += n - return buffer.slice(offset - n, offset) - } - - function readUInt32 () { - var i = buffer.readUInt32LE(offset) - offset += 4 - return i - } - - function readInt32 () { - var i = buffer.readInt32LE(offset) - offset += 4 - return i - } - - function readUInt64 () { - var i = bufferutils.readUInt64LE(buffer, offset) - offset += 8 - return i - } - - function readVarInt () { - var vi = varuint.decode(buffer, offset) - offset += varuint.decode.bytes - return vi - } - - function readVarSlice () { - return readSlice(readVarInt()) - } - - function readVector () { - var count = readVarInt() - var vector = [] - for (var i = 0; i < count; i++) vector.push(readVarSlice()) - return vector - } - - var tx = new Transaction() - tx.version = readInt32() - - var marker = buffer.readUInt8(offset) - var flag = buffer.readUInt8(offset + 1) - - var hasWitnesses = false - if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && - flag === Transaction.ADVANCED_TRANSACTION_FLAG) { - offset += 2 - hasWitnesses = true - } - - var vinLen = readVarInt() - for (var i = 0; i < vinLen; ++i) { - tx.ins.push({ - hash: readSlice(32), - index: readUInt32(), - script: readVarSlice(), - sequence: readUInt32(), - witness: EMPTY_WITNESS - }) - } - - var voutLen = readVarInt() - for (i = 0; i < voutLen; ++i) { - tx.outs.push({ - value: readUInt64(), - script: readVarSlice() - }) - } - - if (hasWitnesses) { - for (i = 0; i < vinLen; ++i) { - tx.ins[i].witness = readVector() - } - - // was this pointless? - if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data') - } - - tx.locktime = readUInt32() - - if (__noStrict) return tx - if (offset !== buffer.length) throw new Error('Transaction has unexpected data') - - return tx -} - -Transaction.fromHex = function (hex) { - return Transaction.fromBuffer(Buffer.from(hex, 'hex')) -} - -Transaction.isCoinbaseHash = function (buffer) { - typeforce(types.Hash256bit, buffer) - for (var i = 0; i < 32; ++i) { - if (buffer[i] !== 0) return false - } - return true -} - -Transaction.prototype.isCoinbase = function () { - return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) -} - -Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { - typeforce(types.tuple( - types.Hash256bit, - types.UInt32, - types.maybe(types.UInt32), - types.maybe(types.Buffer) - ), arguments) - - if (types.Null(sequence)) { - sequence = Transaction.DEFAULT_SEQUENCE - } - - // Add the input and return the input's index - return (this.ins.push({ - hash: hash, - index: index, - script: scriptSig || EMPTY_SCRIPT, - sequence: sequence, - witness: EMPTY_WITNESS - }) - 1) -} - -Transaction.prototype.addOutput = function (scriptPubKey, value) { - typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) - - // Add the output and return the output's index - return (this.outs.push({ - script: scriptPubKey, - value: value - }) - 1) -} - -Transaction.prototype.hasWitnesses = function () { - return this.ins.some(function (x) { - return x.witness.length !== 0 - }) -} - -Transaction.prototype.weight = function () { - var base = this.__byteLength(false) - var total = this.__byteLength(true) - return base * 3 + total -} - -Transaction.prototype.virtualSize = function () { - return Math.ceil(this.weight() / 4) -} - -Transaction.prototype.byteLength = function () { - return this.__byteLength(true) -} - -Transaction.prototype.__byteLength = function (__allowWitness) { - var hasWitnesses = __allowWitness && this.hasWitnesses() - - return ( - (hasWitnesses ? 10 : 8) + - varuint.encodingLength(this.ins.length) + - varuint.encodingLength(this.outs.length) + - this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) + - this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) + - (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0) - ) -} - -Transaction.prototype.clone = function () { - var newTx = new Transaction() - newTx.version = this.version - newTx.locktime = this.locktime - - newTx.ins = this.ins.map(function (txIn) { - return { - hash: txIn.hash, - index: txIn.index, - script: txIn.script, - sequence: txIn.sequence, - witness: txIn.witness - } - }) - - newTx.outs = this.outs.map(function (txOut) { - return { - script: txOut.script, - value: txOut.value - } - }) - - return newTx -} - -/** - * Hash transaction for signing a specific input. - * - * Bitcoin uses a different hash for each signed transaction input. - * This method copies the transaction, makes the necessary changes based on the - * hashType, and then hashes the result. - * This hash can then be used to sign the provided transaction input. - */ -Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { - typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments) - - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 - if (inIndex >= this.ins.length) return ONE - - // ignore OP_CODESEPARATOR - var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { - return x !== opcodes.OP_CODESEPARATOR - })) - - var txTmp = this.clone() - - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { - txTmp.outs = [] - - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, i) { - if (i === inIndex) return - - input.sequence = 0 - }) - - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE - - // truncate outputs after - txTmp.outs.length = inIndex + 1 - - // "blank" outputs before - for (var i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT - } - - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, y) { - if (y === inIndex) return - - input.sequence = 0 - }) - } - - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]] - txTmp.ins[0].script = ourScript - - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) - txTmp.ins[inIndex].script = ourScript - } - - // serialize and hash - var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) - buffer.writeInt32LE(hashType, buffer.length - 4) - txTmp.__toBuffer(buffer, 0, false) - - return bcrypto.hash256(buffer) -} - -Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { - typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments) - - var tbuffer, toffset - function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) } - function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } - function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) } - function writeVarInt (i) { - varuint.encode(i, tbuffer, toffset) - toffset += varuint.encode.bytes - } - function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } - - var hashOutputs = ZERO - var hashPrevouts = ZERO - var hashSequence = ZERO - - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { - tbuffer = Buffer.allocUnsafe(36 * this.ins.length) - toffset = 0 - - this.ins.forEach(function (txIn) { - writeSlice(txIn.hash) - writeUInt32(txIn.index) - }) - - hashPrevouts = bcrypto.hash256(tbuffer) - } - - if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && - (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { - tbuffer = Buffer.allocUnsafe(4 * this.ins.length) - toffset = 0 - - this.ins.forEach(function (txIn) { - writeUInt32(txIn.sequence) - }) - - hashSequence = bcrypto.hash256(tbuffer) - } - - if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && - (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { - var txOutsSize = this.outs.reduce(function (sum, output) { - return sum + 8 + varSliceSize(output.script) - }, 0) - - tbuffer = Buffer.allocUnsafe(txOutsSize) - toffset = 0 - - this.outs.forEach(function (out) { - writeUInt64(out.value) - writeVarSlice(out.script) - }) - - hashOutputs = bcrypto.hash256(tbuffer) - } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { - var output = this.outs[inIndex] - - tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)) - toffset = 0 - writeUInt64(output.value) - writeVarSlice(output.script) - - hashOutputs = bcrypto.hash256(tbuffer) - } - - tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)) - toffset = 0 - - var input = this.ins[inIndex] - writeUInt32(this.version) - writeSlice(hashPrevouts) - writeSlice(hashSequence) - writeSlice(input.hash) - writeUInt32(input.index) - writeVarSlice(prevOutScript) - writeUInt64(value) - writeUInt32(input.sequence) - writeSlice(hashOutputs) - writeUInt32(this.locktime) - writeUInt32(hashType) - return bcrypto.hash256(tbuffer) -} - -Transaction.prototype.getHash = function () { - return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) -} - -Transaction.prototype.getId = function () { - // transaction hash's are displayed in reverse order - return this.getHash().reverse().toString('hex') -} - -Transaction.prototype.toBuffer = function (buffer, initialOffset) { - return this.__toBuffer(buffer, initialOffset, true) -} - -Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { - if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) - - var offset = initialOffset || 0 - function writeSlice (slice) { offset += slice.copy(buffer, offset) } - function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } - function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } - function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) } - function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) } - function writeVarInt (i) { - varuint.encode(i, buffer, offset) - offset += varuint.encode.bytes - } - function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } - function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) } - - writeInt32(this.version) - - var hasWitnesses = __allowWitness && this.hasWitnesses() - - if (hasWitnesses) { - writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER) - writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG) - } - - writeVarInt(this.ins.length) - - this.ins.forEach(function (txIn) { - writeSlice(txIn.hash) - writeUInt32(txIn.index) - writeVarSlice(txIn.script) - writeUInt32(txIn.sequence) - }) - - writeVarInt(this.outs.length) - this.outs.forEach(function (txOut) { - if (!txOut.valueBuffer) { - writeUInt64(txOut.value) - } else { - writeSlice(txOut.valueBuffer) - } - - writeVarSlice(txOut.script) - }) - - if (hasWitnesses) { - this.ins.forEach(function (input) { - writeVector(input.witness) - }) - } - - writeUInt32(this.locktime) - - // avoid slicing unless necessary - if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) - return buffer -} - -Transaction.prototype.toHex = function () { - return this.toBuffer().toString('hex') -} - -Transaction.prototype.setInputScript = function (index, scriptSig) { - typeforce(types.tuple(types.Number, types.Buffer), arguments) - - this.ins[index].script = scriptSig -} - -Transaction.prototype.setWitness = function (index, witness) { - typeforce(types.tuple(types.Number, [types.Buffer]), arguments) - - this.ins[index].witness = witness -} - -module.exports = Transaction - -},{"./bufferutils":13,"./crypto":14,"./script":21,"./types":47,"bitcoin-ops":9,"safe-buffer":117,"typeforce":135,"varuint-bitcoin":137}],46:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var baddress = require('./address') -var bcrypto = require('./crypto') -var bscript = require('./script') -var btemplates = require('./templates') -var networks = require('./networks') -var ops = require('bitcoin-ops') -var typeforce = require('typeforce') -var types = require('./types') -var scriptTypes = btemplates.types -var SIGNABLE = [btemplates.types.P2PKH, btemplates.types.P2PK, btemplates.types.MULTISIG] -var P2SH = SIGNABLE.concat([btemplates.types.P2WPKH, btemplates.types.P2WSH]) - -var ECPair = require('./ecpair') -var ECSignature = require('./ecsignature') -var Transaction = require('./transaction') - -function supportedType (type) { - return SIGNABLE.indexOf(type) !== -1 -} - -function supportedP2SHType (type) { - return P2SH.indexOf(type) !== -1 -} - -function extractChunks (type, chunks, script) { - var pubKeys = [] - var signatures = [] - switch (type) { - case scriptTypes.P2PKH: - // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)') - pubKeys = chunks.slice(1) - signatures = chunks.slice(0, 1) - break - - case scriptTypes.P2PK: - pubKeys[0] = script ? btemplates.pubKey.output.decode(script) : undefined - signatures = chunks.slice(0, 1) - break - - case scriptTypes.MULTISIG: - if (script) { - var multisig = btemplates.multisig.output.decode(script) - pubKeys = multisig.pubKeys - } - - signatures = chunks.slice(1).map(function (chunk) { - return chunk.length === 0 ? undefined : chunk - }) - break - } - - return { - pubKeys: pubKeys, - signatures: signatures - } -} -function expandInput (scriptSig, witnessStack) { - if (scriptSig.length === 0 && witnessStack.length === 0) return {} - - var prevOutScript - var prevOutType - var scriptType - var script - var redeemScript - var witnessScript - var witnessScriptType - var redeemScriptType - var witness = false - var p2wsh = false - var p2sh = false - var witnessProgram - var chunks - - var scriptSigChunks = bscript.decompile(scriptSig) - var sigType = btemplates.classifyInput(scriptSigChunks, true) - if (sigType === scriptTypes.P2SH) { - p2sh = true - redeemScript = scriptSigChunks[scriptSigChunks.length - 1] - redeemScriptType = btemplates.classifyOutput(redeemScript) - prevOutScript = btemplates.scriptHash.output.encode(bcrypto.hash160(redeemScript)) - prevOutType = scriptTypes.P2SH - script = redeemScript - } - - var classifyWitness = btemplates.classifyWitness(witnessStack, true) - if (classifyWitness === scriptTypes.P2WSH) { - witnessScript = witnessStack[witnessStack.length - 1] - witnessScriptType = btemplates.classifyOutput(witnessScript) - p2wsh = true - witness = true - if (scriptSig.length === 0) { - prevOutScript = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) - prevOutType = scriptTypes.P2WSH - if (redeemScript !== undefined) { - throw new Error('Redeem script given when unnecessary') - } - // bare witness - } else { - if (!redeemScript) { - throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty') - } - witnessProgram = btemplates.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) - if (!redeemScript.equals(witnessProgram)) { - throw new Error('Redeem script didn\'t match witnessScript') - } - } - - if (!supportedType(btemplates.classifyOutput(witnessScript))) { - throw new Error('unsupported witness script') - } - - script = witnessScript - scriptType = witnessScriptType - chunks = witnessStack.slice(0, -1) - } else if (classifyWitness === scriptTypes.P2WPKH) { - witness = true - var key = witnessStack[witnessStack.length - 1] - var keyHash = bcrypto.hash160(key) - if (scriptSig.length === 0) { - prevOutScript = btemplates.witnessPubKeyHash.output.encode(keyHash) - prevOutType = scriptTypes.P2WPKH - if (typeof redeemScript !== 'undefined') { - throw new Error('Redeem script given when unnecessary') - } - } else { - if (!redeemScript) { - throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty') - } - witnessProgram = btemplates.witnessPubKeyHash.output.encode(keyHash) - if (!redeemScript.equals(witnessProgram)) { - throw new Error('Redeem script did not have the right witness program') - } - } - - scriptType = scriptTypes.P2PKH - chunks = witnessStack - } else if (redeemScript) { - if (!supportedP2SHType(redeemScriptType)) { - throw new Error('Bad redeemscript!') - } - - script = redeemScript - scriptType = redeemScriptType - chunks = scriptSigChunks.slice(0, -1) - } else { - prevOutType = scriptType = btemplates.classifyInput(scriptSig) - chunks = scriptSigChunks - } - - var expanded = extractChunks(scriptType, chunks, script) - - var result = { - pubKeys: expanded.pubKeys, - signatures: expanded.signatures, - prevOutScript: prevOutScript, - prevOutType: prevOutType, - signType: scriptType, - signScript: script, - witness: Boolean(witness) - } - - if (p2sh) { - result.redeemScript = redeemScript - result.redeemScriptType = redeemScriptType - } - - if (p2wsh) { - result.witnessScript = witnessScript - result.witnessScriptType = witnessScriptType - } - - return result -} - -// could be done in expandInput, but requires the original Transaction for hashForSignature -function fixMultisigOrder (input, transaction, vin) { - if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return - if (input.pubKeys.length === input.signatures.length) return - - var unmatched = input.signatures.concat() - - input.signatures = input.pubKeys.map(function (pubKey) { - var keyPair = ECPair.fromPublicKeyBuffer(pubKey) - var match - - // check for a signature - unmatched.some(function (signature, i) { - // skip if undefined || OP_0 - if (!signature) return false - - // TODO: avoid O(n) hashForSignature - var parsed = ECSignature.parseScriptSignature(signature) - var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType) - - // skip if signature does not match pubKey - if (!keyPair.verify(hash, parsed.signature)) return false - - // remove matched signature from unmatched - unmatched[i] = undefined - match = signature - - return true - }) - - return match - }) -} - -function expandOutput (script, scriptType, ourPubKey) { - typeforce(types.Buffer, script) - - var scriptChunks = bscript.decompile(script) - if (!scriptType) { - scriptType = btemplates.classifyOutput(script) - } - - var pubKeys = [] - - switch (scriptType) { - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2PKH: - if (!ourPubKey) break - - var pkh1 = scriptChunks[2] - var pkh2 = bcrypto.hash160(ourPubKey) - if (pkh1.equals(pkh2)) pubKeys = [ourPubKey] - break - - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2WPKH: - if (!ourPubKey) break - - var wpkh1 = scriptChunks[1] - var wpkh2 = bcrypto.hash160(ourPubKey) - if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey] - break - - case scriptTypes.P2PK: - pubKeys = scriptChunks.slice(0, 1) - break - - case scriptTypes.MULTISIG: - pubKeys = scriptChunks.slice(1, -2) - break - - default: return { scriptType: scriptType } - } - - return { - pubKeys: pubKeys, - scriptType: scriptType, - signatures: pubKeys.map(function () { return undefined }) - } -} - -function checkP2SHInput (input, redeemScriptHash) { - if (input.prevOutType) { - if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH') - - var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1] - if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)') - } -} - -function checkP2WSHInput (input, witnessScriptHash) { - if (input.prevOutType) { - if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH') - - var scriptHash = bscript.decompile(input.prevOutScript)[1] - if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)') - } -} - -function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) { - var expanded - var prevOutType - var prevOutScript - - var p2sh = false - var p2shType - var redeemScriptHash - - var witness = false - var p2wsh = false - var witnessType - var witnessScriptHash - - var signType - var signScript - - if (redeemScript && witnessScript) { - redeemScriptHash = bcrypto.hash160(redeemScript) - witnessScriptHash = bcrypto.sha256(witnessScript) - checkP2SHInput(input, redeemScriptHash) - - if (!redeemScript.equals(btemplates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script') - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2SH - prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash) - p2sh = witness = p2wsh = true - p2shType = btemplates.types.P2WSH - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (redeemScript) { - redeemScriptHash = bcrypto.hash160(redeemScript) - checkP2SHInput(input, redeemScriptHash) - - expanded = expandOutput(redeemScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2SH - prevOutScript = btemplates.scriptHash.output.encode(redeemScriptHash) - p2sh = true - signType = p2shType = expanded.scriptType - signScript = redeemScript - witness = signType === btemplates.types.P2WPKH - } else if (witnessScript) { - witnessScriptHash = bcrypto.sha256(witnessScript) - checkP2WSHInput(input, witnessScriptHash) - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') - - prevOutType = btemplates.types.P2WSH - prevOutScript = btemplates.witnessScriptHash.output.encode(witnessScriptHash) - witness = p2wsh = true - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (input.prevOutType) { - // embedded scripts are not possible without a redeemScript - if (input.prevOutType === scriptTypes.P2SH || - input.prevOutType === scriptTypes.P2WSH) { - throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript') - } - - prevOutType = input.prevOutType - prevOutScript = input.prevOutScript - expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey) - if (!expanded.pubKeys) return - - witness = (input.prevOutType === scriptTypes.P2WPKH) - signType = prevOutType - signScript = prevOutScript - } else { - prevOutScript = btemplates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey)) - expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey) - - prevOutType = scriptTypes.P2PKH - witness = false - signType = prevOutType - signScript = prevOutScript - } - - if (signType === scriptTypes.P2WPKH) { - signScript = btemplates.pubKeyHash.output.encode(btemplates.witnessPubKeyHash.output.decode(signScript)) - } - - if (p2sh) { - input.redeemScript = redeemScript - input.redeemScriptType = p2shType - } - - if (p2wsh) { - input.witnessScript = witnessScript - input.witnessScriptType = witnessType - } - - input.pubKeys = expanded.pubKeys - input.signatures = expanded.signatures - input.signScript = signScript - input.signType = signType - input.prevOutScript = prevOutScript - input.prevOutType = prevOutType - input.witness = witness -} - -function buildStack (type, signatures, pubKeys, allowIncomplete) { - if (type === scriptTypes.P2PKH) { - if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return btemplates.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0]) - } else if (type === scriptTypes.P2PK) { - if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return btemplates.pubKey.input.encodeStack(signatures[0]) - } else if (type === scriptTypes.MULTISIG) { - if (signatures.length > 0) { - signatures = signatures.map(function (signature) { - return signature || ops.OP_0 - }) - if (!allowIncomplete) { - // remove blank signatures - signatures = signatures.filter(function (x) { return x !== ops.OP_0 }) - } - - return btemplates.multisig.input.encodeStack(signatures) - } - } else { - throw new Error('Not yet supported') - } - - if (!allowIncomplete) throw new Error('Not enough signatures provided') - return [] -} - -function buildInput (input, allowIncomplete) { - var scriptType = input.prevOutType - var sig = [] - var witness = [] - - if (supportedType(scriptType)) { - sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete) - } - - var p2sh = false - if (scriptType === btemplates.types.P2SH) { - // We can remove this error later when we have a guarantee prepareInput - // rejects unsignable scripts - it MUST be signable at this point. - if (!allowIncomplete && !supportedP2SHType(input.redeemScriptType)) { - throw new Error('Impossible to sign this type') - } - - if (supportedType(input.redeemScriptType)) { - sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete) - } - - // If it wasn't SIGNABLE, it's witness, defer to that - if (input.redeemScriptType) { - p2sh = true - scriptType = input.redeemScriptType - } - } - - switch (scriptType) { - // P2WPKH is a special case of P2PKH - case btemplates.types.P2WPKH: - witness = buildStack(btemplates.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete) - break - - case btemplates.types.P2WSH: - // We can remove this check later - if (!allowIncomplete && !supportedType(input.witnessScriptType)) { - throw new Error('Impossible to sign this type') - } - - if (supportedType(input.witnessScriptType)) { - witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete) - witness.push(input.witnessScript) - scriptType = input.witnessScriptType - } - - break - } - - // append redeemScript if necessary - if (p2sh) { - sig.push(input.redeemScript) - } - - return { - type: scriptType, - script: bscript.compile(sig), - witness: witness - } -} - -function TransactionBuilder (network, maximumFeeRate) { - this.prevTxMap = {} - this.network = network || networks.bitcoin - - // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth) - this.maximumFeeRate = maximumFeeRate || 2500 - - this.inputs = [] - this.tx = new Transaction() -} - -TransactionBuilder.prototype.setLockTime = function (locktime) { - typeforce(types.UInt32, locktime) - - // if any signatures exist, throw - if (this.inputs.some(function (input) { - if (!input.signatures) return false - - return input.signatures.some(function (s) { return s }) - })) { - throw new Error('No, this would invalidate signatures') - } - - this.tx.locktime = locktime -} - -TransactionBuilder.prototype.setVersion = function (version) { - typeforce(types.UInt32, version) - - // XXX: this might eventually become more complex depending on what the versions represent - this.tx.version = version -} - -TransactionBuilder.fromTransaction = function (transaction, network) { - var txb = new TransactionBuilder(network) - - // Copy transaction fields - txb.setVersion(transaction.version) - txb.setLockTime(transaction.locktime) - - // Copy outputs (done first to avoid signature invalidation) - transaction.outs.forEach(function (txOut) { - txb.addOutput(txOut.script, txOut.value) - }) - - // Copy inputs - transaction.ins.forEach(function (txIn) { - txb.__addInputUnsafe(txIn.hash, txIn.index, { - sequence: txIn.sequence, - script: txIn.script, - witness: txIn.witness - }) - }) - - // fix some things not possible through the public API - txb.inputs.forEach(function (input, i) { - fixMultisigOrder(input, transaction, i) - }) - - return txb -} - -TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) { - if (!this.__canModifyInputs()) { - throw new Error('No, this would invalidate signatures') - } - - var value - - // is it a hex string? - if (typeof txHash === 'string') { - // transaction hashs's are displayed in reverse order, un-reverse it - txHash = Buffer.from(txHash, 'hex').reverse() - - // is it a Transaction object? - } else if (txHash instanceof Transaction) { - var txOut = txHash.outs[vout] - prevOutScript = txOut.script - value = txOut.value - - txHash = txHash.getHash() - } - - return this.__addInputUnsafe(txHash, vout, { - sequence: sequence, - prevOutScript: prevOutScript, - value: value - }) -} - -TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) { - if (Transaction.isCoinbaseHash(txHash)) { - throw new Error('coinbase inputs not supported') - } - - var prevTxOut = txHash.toString('hex') + ':' + vout - if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut) - - var input = {} - - // derive what we can from the scriptSig - if (options.script !== undefined) { - input = expandInput(options.script, options.witness || []) - } - - // if an input value was given, retain it - if (options.value !== undefined) { - input.value = options.value - } - - // derive what we can from the previous transactions output script - if (!input.prevOutScript && options.prevOutScript) { - var prevOutType - - if (!input.pubKeys && !input.signatures) { - var expanded = expandOutput(options.prevOutScript) - - if (expanded.pubKeys) { - input.pubKeys = expanded.pubKeys - input.signatures = expanded.signatures - } - - prevOutType = expanded.scriptType - } - - input.prevOutScript = options.prevOutScript - input.prevOutType = prevOutType || btemplates.classifyOutput(options.prevOutScript) - } - - var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig) - this.inputs[vin] = input - this.prevTxMap[prevTxOut] = vin - return vin -} - -TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) { - if (!this.__canModifyOutputs()) { - throw new Error('No, this would invalidate signatures') - } - - // Attempt to get a script if it's a base58 address string - if (typeof scriptPubKey === 'string') { - scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network) - } - - return this.tx.addOutput(scriptPubKey, value) -} - -TransactionBuilder.prototype.build = function () { - return this.__build(false) -} -TransactionBuilder.prototype.buildIncomplete = function () { - return this.__build(true) -} - -TransactionBuilder.prototype.__build = function (allowIncomplete) { - if (!allowIncomplete) { - if (!this.tx.ins.length) throw new Error('Transaction has no inputs') - if (!this.tx.outs.length) throw new Error('Transaction has no outputs') - } - - var tx = this.tx.clone() - // Create script signatures from inputs - this.inputs.forEach(function (input, i) { - var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType - if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete') - var result = buildInput(input, allowIncomplete) - - // skip if no result - if (!allowIncomplete) { - if (!supportedType(result.type) && result.type !== btemplates.types.P2WPKH) { - throw new Error(result.type + ' not supported') - } - } - - tx.setInputScript(i, result.script) - tx.setWitness(i, result.witness) - }) - - if (!allowIncomplete) { - // do not rely on this, its merely a last resort - if (this.__overMaximumFees(tx.virtualSize())) { - throw new Error('Transaction has absurd fees') - } - } - - return tx -} - -function canSign (input) { - return input.prevOutScript !== undefined && - input.signScript !== undefined && - input.pubKeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubKeys.length && - input.pubKeys.length > 0 && - ( - input.witness === false || - (input.witness === true && input.value !== undefined) - ) -} - -TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) { - // TODO: remove keyPair.network matching in 4.0.0 - if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network') - if (!this.inputs[vin]) throw new Error('No input at index: ' + vin) - hashType = hashType || Transaction.SIGHASH_ALL - - var input = this.inputs[vin] - - // if redeemScript was previously provided, enforce consistency - if (input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript)) { - throw new Error('Inconsistent redeemScript') - } - - var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer() - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue') - typeforce(types.Satoshi, witnessValue) - input.value = witnessValue - } - - if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript) - if (!canSign(input)) throw Error(input.prevOutType + ' not supported') - } - - // ready to sign - var signatureHash - if (input.witness) { - signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, input.value, hashType) - } else { - signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType) - } - - // enforce in order signing of public keys - var signed = input.pubKeys.some(function (pubKey, i) { - if (!kpPubKey.equals(pubKey)) return false - if (input.signatures[i]) throw new Error('Signature already exists') - if (kpPubKey.length !== 33 && - input.signType === scriptTypes.P2WPKH) throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH') - - var signature = keyPair.sign(signatureHash) - if (Buffer.isBuffer(signature)) signature = ECSignature.fromRSBuffer(signature) - - input.signatures[i] = signature.toScriptSignature(hashType) - return true - }) - - if (!signed) throw new Error('Key pair cannot sign for this input') -} - -function signatureHashType (buffer) { - return buffer.readUInt8(buffer.length - 1) -} - -TransactionBuilder.prototype.__canModifyInputs = function () { - return this.inputs.every(function (input) { - // any signatures? - if (input.signatures === undefined) return true - - return input.signatures.every(function (signature) { - if (!signature) return true - var hashType = signatureHashType(signature) - - // if SIGHASH_ANYONECANPAY is set, signatures would not - // be invalidated by more inputs - return hashType & Transaction.SIGHASH_ANYONECANPAY - }) - }) -} - -TransactionBuilder.prototype.__canModifyOutputs = function () { - var nInputs = this.tx.ins.length - var nOutputs = this.tx.outs.length - - return this.inputs.every(function (input) { - if (input.signatures === undefined) return true - - return input.signatures.every(function (signature) { - if (!signature) return true - var hashType = signatureHashType(signature) - - var hashTypeMod = hashType & 0x1f - if (hashTypeMod === Transaction.SIGHASH_NONE) return true - if (hashTypeMod === Transaction.SIGHASH_SINGLE) { - // if SIGHASH_SINGLE is set, and nInputs > nOutputs - // some signatures would be invalidated by the addition - // of more outputs - return nInputs <= nOutputs - } - }) - }) -} - -TransactionBuilder.prototype.__overMaximumFees = function (bytes) { - // not all inputs will have .value defined - var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0) - - // but all outputs do, and if we have any input value - // we can immediately determine if the outputs are too small - var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0) - var fee = incoming - outgoing - var feeRate = fee / bytes - - return feeRate > this.maximumFeeRate -} - -module.exports = TransactionBuilder - -},{"./address":11,"./crypto":14,"./ecpair":16,"./ecsignature":17,"./networks":20,"./script":21,"./templates":23,"./transaction":45,"./types":47,"bitcoin-ops":9,"safe-buffer":117,"typeforce":135}],47:[function(require,module,exports){ -var typeforce = require('typeforce') - -var UINT31_MAX = Math.pow(2, 31) - 1 -function UInt31 (value) { - return typeforce.UInt32(value) && value <= UINT31_MAX -} - -function BIP32Path (value) { - return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) -} -BIP32Path.toJSON = function () { return 'BIP32 derivation path' } - -var SATOSHI_MAX = 21 * 1e14 -function Satoshi (value) { - return typeforce.UInt53(value) && value <= SATOSHI_MAX -} - -// external dependent types -var BigInt = typeforce.quacksLike('BigInteger') -var ECPoint = typeforce.quacksLike('Point') - -// exposed, external API -var ECSignature = typeforce.compile({ r: BigInt, s: BigInt }) -var Network = typeforce.compile({ - messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String), - bip32: { - public: typeforce.UInt32, - private: typeforce.UInt32 - }, - pubKeyHash: typeforce.UInt8, - scriptHash: typeforce.UInt8, - wif: typeforce.UInt8 -}) - -// extend typeforce types with ours -var types = { - BigInt: BigInt, - BIP32Path: BIP32Path, - Buffer256bit: typeforce.BufferN(32), - ECPoint: ECPoint, - ECSignature: ECSignature, - Hash160bit: typeforce.BufferN(20), - Hash256bit: typeforce.BufferN(32), - Network: Network, - Satoshi: Satoshi, - UInt31: UInt31 -} - -for (var typeName in typeforce) { - types[typeName] = typeforce[typeName] -} - -module.exports = types - -},{"typeforce":135}],48:[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('buffer').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).toRed(this); - 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); - -},{"buffer":148}],49:[function(require,module,exports){ -var r; - -module.exports = function rand(len) { - if (!r) - r = new Rand(null); - - return r.generate(len); -}; - -function Rand(rand) { - this.rand = rand; -} -module.exports.Rand = Rand; - -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; - -// Emulate crypto API using randy -Rand.prototype._rand = function _rand(n) { - if (this.rand.getBytes) - return this.rand.getBytes(n); - - var res = new Uint8Array(n); - for (var i = 0; i < res.length; i++) - res[i] = this.rand.getByte(); - return res; -}; - -if (typeof self === 'object') { - if (self.crypto && self.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.crypto.getRandomValues(arr); - return arr; - }; - } else if (self.msCrypto && self.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - self.msCrypto.getRandomValues(arr); - return arr; - }; - - // Safari's WebWorkers do not have `crypto` - } else if (typeof window === 'object') { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js or Web worker with no crypto support - try { - var crypto = require('crypto'); - if (typeof crypto.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto.randomBytes(n); - }; - } catch (e) { - } -} - -},{"crypto":148}],50:[function(require,module,exports){ -var basex = require('base-x') -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' - -module.exports = basex(ALPHABET) - -},{"base-x":2}],51:[function(require,module,exports){ -'use strict' - -var base58 = require('bs58') -var Buffer = require('safe-buffer').Buffer - -module.exports = function (checksumFn) { - // Encode a buffer as a base58-check encoded string - function encode (payload) { - var checksum = checksumFn(payload) - - return base58.encode(Buffer.concat([ - payload, - checksum - ], payload.length + 4)) - } - - function decodeRaw (buffer) { - var payload = buffer.slice(0, -4) - var checksum = buffer.slice(-4) - var newChecksum = checksumFn(payload) - - if (checksum[0] ^ newChecksum[0] | - checksum[1] ^ newChecksum[1] | - checksum[2] ^ newChecksum[2] | - checksum[3] ^ newChecksum[3]) return - - return payload - } - - // Decode a base58-check encoded string to a buffer, no result if checksum is wrong - function decodeUnsafe (string) { - var buffer = base58.decodeUnsafe(string) - if (!buffer) return - - return decodeRaw(buffer) - } - - function decode (string) { - var buffer = base58.decode(string) - var payload = decodeRaw(buffer, checksumFn) - if (!payload) throw new Error('Invalid checksum') - return payload - } - - return { - encode: encode, - decode: decode, - decodeUnsafe: decodeUnsafe - } -} - -},{"bs58":50,"safe-buffer":117}],52:[function(require,module,exports){ -'use strict' - -var createHash = require('create-hash') -var bs58checkBase = require('./base') - -// SHA256(SHA256(buffer)) -function sha256x2 (buffer) { - var tmp = createHash('sha256').update(buffer).digest() - return createHash('sha256').update(tmp).digest() -} - -module.exports = bs58checkBase(sha256x2) - -},{"./base":51,"create-hash":54}],53:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var StringDecoder = require('string_decoder').StringDecoder -var inherits = require('inherits') - -function CipherBase (hashMode) { - Transform.call(this) - this.hashMode = typeof hashMode === 'string' - if (this.hashMode) { - this[hashMode] = this._finalOrDigest - } else { - this.final = this._finalOrDigest - } - if (this._final) { - this.__final = this._final - this._final = null - } - this._decoder = null - this._encoding = null -} -inherits(CipherBase, Transform) - -CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = Buffer.from(data, inputEnc) - } - - var outData = this._update(data) - if (this.hashMode) return this - - if (outputEnc) { - outData = this._toString(outData, outputEnc) - } - - return outData -} - -CipherBase.prototype.setAutoPadding = function () {} -CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') -} - -CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') -} - -CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') -} - -CipherBase.prototype._transform = function (data, _, next) { - var err - try { - if (this.hashMode) { - this._update(data) - } else { - this.push(this._update(data)) - } - } catch (e) { - err = e - } finally { - next(err) - } -} -CipherBase.prototype._flush = function (done) { - var err - try { - this.push(this.__final()) - } catch (e) { - err = e - } - - done(err) -} -CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this.__final() || Buffer.alloc(0) - if (outputEnc) { - outData = this._toString(outData, outputEnc, true) - } - return outData -} - -CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc) - this._encoding = enc - } - - if (this._encoding !== enc) throw new Error('can\'t switch encodings') - - var out = this._decoder.write(value) - if (fin) { - out += this._decoder.end() - } - - return out -} - -module.exports = CipherBase - -},{"inherits":98,"safe-buffer":117,"stream":172,"string_decoder":173}],54:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var MD5 = require('md5.js') -var RIPEMD160 = require('ripemd160') -var sha = require('sha.js') -var Base = require('cipher-base') - -function Hash (hash) { - Base.call(this, 'digest') - - this._hash = hash -} - -inherits(Hash, Base) - -Hash.prototype._update = function (data) { - this._hash.update(data) -} - -Hash.prototype._final = function () { - return this._hash.digest() -} - -module.exports = function createHash (alg) { - alg = alg.toLowerCase() - if (alg === 'md5') return new MD5() - if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160() - - return new Hash(sha(alg)) -} - -},{"cipher-base":53,"inherits":98,"md5.js":109,"ripemd160":115,"sha.js":125}],55:[function(require,module,exports){ -var MD5 = require('md5.js') - -module.exports = function (buffer) { - return new MD5().update(buffer).digest() -} - -},{"md5.js":109}],56:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Legacy = require('./legacy') -var Base = require('cipher-base') -var Buffer = require('safe-buffer').Buffer -var md5 = require('create-hash/md5') -var RIPEMD160 = require('ripemd160') - -var sha = require('sha.js') - -var ZEROS = Buffer.alloc(128) - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - - this._alg = alg - this._key = key - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - key = hash.update(key).digest() - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - this._hash.update(ipad) -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.update(data) -} - -Hmac.prototype._final = function () { - var h = this._hash.digest() - var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) - return hash.update(this._opad).update(h).digest() -} - -module.exports = function createHmac (alg, key) { - alg = alg.toLowerCase() - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac(alg, key) -} - -},{"./legacy":57,"cipher-base":53,"create-hash/md5":55,"inherits":98,"ripemd160":115,"safe-buffer":117,"sha.js":125}],57:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Buffer = require('safe-buffer').Buffer - -var Base = require('cipher-base') - -var ZEROS = Buffer.alloc(128) -var blocksize = 64 - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - this._alg = alg - this._key = key - - if (key.length > blocksize) { - key = alg(key) - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - - this._hash = [ipad] -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.push(data) -} - -Hmac.prototype._final = function () { - var h = this._alg(Buffer.concat(this._hash)) - return this._alg(Buffer.concat([this._opad, h])) -} -module.exports = Hmac - -},{"cipher-base":53,"inherits":98,"safe-buffer":117}],58:[function(require,module,exports){ -var assert = require('assert') -var BigInteger = require('bigi') - -var Point = require('./point') - -function Curve (p, a, b, Gx, Gy, n, h) { - this.p = p - this.a = a - this.b = b - this.G = Point.fromAffine(this, Gx, Gy) - this.n = n - this.h = h - - this.infinity = new Point(this, null, null, BigInteger.ZERO) - - // result caching - this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) - - // determine size of p in bytes - this.pLength = Math.floor((this.p.bitLength() + 7) / 8) -} - -Curve.prototype.pointFromX = function (isOdd, x) { - var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) - var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves - - var y = beta - if (beta.isEven() ^ !isOdd) { - y = this.p.subtract(y) // -y % p - } - - return Point.fromAffine(this, x, y) -} - -Curve.prototype.isInfinity = function (Q) { - if (Q === this.infinity) return true - - return Q.z.signum() === 0 && Q.y.signum() !== 0 -} - -Curve.prototype.isOnCurve = function (Q) { - if (this.isInfinity(Q)) return true - - var x = Q.affineX - var y = Q.affineY - var a = this.a - var b = this.b - var p = this.p - - // Check that xQ and yQ are integers in the interval [0, p - 1] - if (x.signum() < 0 || x.compareTo(p) >= 0) return false - if (y.signum() < 0 || y.compareTo(p) >= 0) return false - - // and check that y^2 = x^3 + ax + b (mod p) - var lhs = y.square().mod(p) - var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) - return lhs.equals(rhs) -} - -/** - * Validate an elliptic curve point. - * - * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive - */ -Curve.prototype.validate = function (Q) { - // Check Q != O - assert(!this.isInfinity(Q), 'Point is at infinity') - assert(this.isOnCurve(Q), 'Point is not on the curve') - - // Check nQ = O (where Q is a scalar multiple of G) - var nQ = Q.multiply(this.n) - assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') - - return true -} - -module.exports = Curve - -},{"./point":62,"assert":143,"bigi":6}],59:[function(require,module,exports){ -module.exports={ - "secp128r1": { - "p": "fffffffdffffffffffffffffffffffff", - "a": "fffffffdfffffffffffffffffffffffc", - "b": "e87579c11079f43dd824993c2cee5ed3", - "n": "fffffffe0000000075a30d1b9038a115", - "h": "01", - "Gx": "161ff7528b899b2d0c28607ca52c5b86", - "Gy": "cf5ac8395bafeb13c02da292dded7a83" - }, - "secp160k1": { - "p": "fffffffffffffffffffffffffffffffeffffac73", - "a": "00", - "b": "07", - "n": "0100000000000000000001b8fa16dfab9aca16b6b3", - "h": "01", - "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb", - "Gy": "938cf935318fdced6bc28286531733c3f03c4fee" - }, - "secp160r1": { - "p": "ffffffffffffffffffffffffffffffff7fffffff", - "a": "ffffffffffffffffffffffffffffffff7ffffffc", - "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45", - "n": "0100000000000000000001f4c8f927aed3ca752257", - "h": "01", - "Gx": "4a96b5688ef573284664698968c38bb913cbfc82", - "Gy": "23a628553168947d59dcc912042351377ac5fb32" - }, - "secp192k1": { - "p": "fffffffffffffffffffffffffffffffffffffffeffffee37", - "a": "00", - "b": "03", - "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d", - "h": "01", - "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d", - "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d" - }, - "secp192r1": { - "p": "fffffffffffffffffffffffffffffffeffffffffffffffff", - "a": "fffffffffffffffffffffffffffffffefffffffffffffffc", - "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", - "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831", - "h": "01", - "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", - "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811" - }, - "secp256k1": { - "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", - "a": "00", - "b": "07", - "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", - "h": "01", - "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", - "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" - }, - "secp256r1": { - "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", - "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", - "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", - "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", - "h": "01", - "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", - "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" - } -} - -},{}],60:[function(require,module,exports){ -var Point = require('./point') -var Curve = require('./curve') - -var getCurveByName = require('./names') - -module.exports = { - Curve: Curve, - Point: Point, - getCurveByName: getCurveByName -} - -},{"./curve":58,"./names":61,"./point":62}],61:[function(require,module,exports){ -var BigInteger = require('bigi') - -var curves = require('./curves.json') -var Curve = require('./curve') - -function getCurveByName (name) { - var curve = curves[name] - if (!curve) return null - - var p = new BigInteger(curve.p, 16) - var a = new BigInteger(curve.a, 16) - var b = new BigInteger(curve.b, 16) - var n = new BigInteger(curve.n, 16) - var h = new BigInteger(curve.h, 16) - var Gx = new BigInteger(curve.Gx, 16) - var Gy = new BigInteger(curve.Gy, 16) - - return new Curve(p, a, b, Gx, Gy, n, h) -} - -module.exports = getCurveByName - -},{"./curve":58,"./curves.json":59,"bigi":6}],62:[function(require,module,exports){ -var assert = require('assert') -var Buffer = require('safe-buffer').Buffer -var BigInteger = require('bigi') - -var THREE = BigInteger.valueOf(3) - -function Point (curve, x, y, z) { - assert.notStrictEqual(z, undefined, 'Missing Z coordinate') - - this.curve = curve - this.x = x - this.y = y - this.z = z - this._zInv = null - - this.compressed = true -} - -Object.defineProperty(Point.prototype, 'zInv', { - get: function () { - if (this._zInv === null) { - this._zInv = this.z.modInverse(this.curve.p) - } - - return this._zInv - } -}) - -Object.defineProperty(Point.prototype, 'affineX', { - get: function () { - return this.x.multiply(this.zInv).mod(this.curve.p) - } -}) - -Object.defineProperty(Point.prototype, 'affineY', { - get: function () { - return this.y.multiply(this.zInv).mod(this.curve.p) - } -}) - -Point.fromAffine = function (curve, x, y) { - return new Point(curve, x, y, BigInteger.ONE) -} - -Point.prototype.equals = function (other) { - if (other === this) return true - if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) - if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) - - // u = Y2 * Z1 - Y1 * Z2 - var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) - - if (u.signum() !== 0) return false - - // v = X2 * Z1 - X1 * Z2 - var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) - - return v.signum() === 0 -} - -Point.prototype.negate = function () { - var y = this.curve.p.subtract(this.y) - - return new Point(this.curve, this.x, y, this.z) -} - -Point.prototype.add = function (b) { - if (this.curve.isInfinity(this)) return b - if (this.curve.isInfinity(b)) return this - - var x1 = this.x - var y1 = this.y - var x2 = b.x - var y2 = b.y - - // u = Y2 * Z1 - Y1 * Z2 - var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) - // v = X2 * Z1 - X1 * Z2 - var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) - - if (v.signum() === 0) { - if (u.signum() === 0) { - return this.twice() // this == b, so double - } - - return this.curve.infinity // this = -b, so infinity - } - - 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.p) - // 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.p) - // z3 = v^3 * z1 * z2 - var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) - - return new Point(this.curve, x3, y3, z3) -} - -Point.prototype.twice = function () { - if (this.curve.isInfinity(this)) return this - if (this.y.signum() === 0) return this.curve.infinity - - var x1 = this.x - var y1 = this.y - - var y1z1 = y1.multiply(this.z).mod(this.curve.p) - var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) - var a = this.curve.a - - // w = 3 * x1^2 + a * z1^2 - var w = x1.square().multiply(THREE) - - if (a.signum() !== 0) { - w = w.add(this.z.square().multiply(a)) - } - - w = w.mod(this.curve.p) - // 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.p) - // 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.pow(3)).mod(this.curve.p) - // z3 = 8 * (y1 * z1)^3 - var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) - - return new Point(this.curve, x3, y3, z3) -} - -// Simple NAF (Non-Adjacent Form) multiplication algorithm -// TODO: modularize the multiplication algorithm -Point.prototype.multiply = function (k) { - if (this.curve.isInfinity(this)) return this - if (k.signum() === 0) return this.curve.infinity - - var e = k - var h = e.multiply(THREE) - - var neg = this.negate() - var R = this - - for (var i = h.bitLength() - 2; i > 0; --i) { - var hBit = h.testBit(i) - var eBit = e.testBit(i) - - R = R.twice() - - if (hBit !== eBit) { - R = R.add(hBit ? this : neg) - } - } - - return R -} - -// Compute this*j + x*k (simultaneous multiplication) -Point.prototype.multiplyTwo = function (j, x, k) { - var i = Math.max(j.bitLength(), k.bitLength()) - 1 - var R = this.curve.infinity - var both = this.add(x) - - while (i >= 0) { - var jBit = j.testBit(i) - var kBit = k.testBit(i) - - R = R.twice() - - if (jBit) { - if (kBit) { - R = R.add(both) - } else { - R = R.add(this) - } - } else if (kBit) { - R = R.add(x) - } - --i - } - - return R -} - -Point.prototype.getEncoded = function (compressed) { - if (compressed == null) compressed = this.compressed - if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00' - - var x = this.affineX - var y = this.affineY - var byteLength = this.curve.pLength - var buffer - - // 0x02/0x03 | X - if (compressed) { - buffer = Buffer.allocUnsafe(1 + byteLength) - buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) - - // 0x04 | X | Y - } else { - buffer = Buffer.allocUnsafe(1 + byteLength + byteLength) - buffer.writeUInt8(0x04, 0) - - y.toBuffer(byteLength).copy(buffer, 1 + byteLength) - } - - x.toBuffer(byteLength).copy(buffer, 1) - - return buffer -} - -Point.decodeFrom = function (curve, buffer) { - var type = buffer.readUInt8(0) - var compressed = (type !== 4) - - var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) - var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) - - var Q - if (compressed) { - assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') - assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') - - var isOdd = (type === 0x03) - Q = curve.pointFromX(isOdd, x) - } else { - assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') - - var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) - Q = Point.fromAffine(curve, x, y) - } - - Q.compressed = compressed - return Q -} - -Point.prototype.toString = function () { - if (this.curve.isInfinity(this)) return '(INFINITY)' - - return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' -} - -module.exports = Point - -},{"assert":143,"bigi":6,"safe-buffer":117}],63:[function(require,module,exports){ -'use strict'; - -var elliptic = exports; - -elliptic.version = require('../package.json').version; -elliptic.utils = require('./elliptic/utils'); -elliptic.rand = require('brorand'); -elliptic.curve = require('./elliptic/curve'); -elliptic.curves = require('./elliptic/curves'); - -// Protocols -elliptic.ec = require('./elliptic/ec'); -elliptic.eddsa = require('./elliptic/eddsa'); - -},{"../package.json":78,"./elliptic/curve":66,"./elliptic/curves":69,"./elliptic/ec":70,"./elliptic/eddsa":73,"./elliptic/utils":77,"brorand":49}],64:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var getNAF = utils.getNAF; -var getJSF = utils.getJSF; -var assert = utils.assert; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new BN(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); - - // Useful for many curves - this.zero = new BN(0).toRed(this.red); - this.one = new BN(1).toRed(this.red); - this.two = new BN(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -module.exports = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); - - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -},{"../../elliptic":63,"bn.js":48}],65:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var assert = elliptic.utils.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - Base.call(this, 'edwards', conf); - - this.a = new BN(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, Base); -module.exports = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - c^2) / (c^2 d y^2 - a) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.c2); - var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } - - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - if (x.fromRed().isOdd() !== odd) - x = x.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = z ? new BN(z, 16) : this.curve.one; - this.t = t && new BN(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point, Base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - (this.y.cmp(this.z) === 0 || - (this.zOne && this.y.cmp(this.curve.c) === 0)); -}; - -Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); - } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.z).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; - -Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; - -Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -// Compatibility with BaseCurve -Point.prototype.toP = Point.prototype.normalize; -Point.prototype.mixedAdd = Point.prototype.add; - -},{"../../elliptic":63,"../curve":66,"bn.js":48,"inherits":98}],66:[function(require,module,exports){ -'use strict'; - -var curve = exports; - -curve.base = require('./base'); -curve.short = require('./short'); -curve.mont = require('./mont'); -curve.edwards = require('./edwards'); - -},{"./base":64,"./edwards":65,"./mont":67,"./short":68}],67:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; - -function MontCurve(conf) { - Base.call(this, 'mont', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.i4 = new BN(4).toRed(this.red).redInvm(); - this.two = new BN(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, Base); -module.exports = MontCurve; - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point(curve, x, z) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new BN(x, 16); - this.z = new BN(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits(Point, Base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils.toArray(bytes, enc), 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -Point.prototype.precompute = function precompute() { - // No-op -}; - -Point.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point.prototype.mul = function mul(k) { - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -},{"../../elliptic":63,"../curve":66,"bn.js":48,"inherits":98}],68:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var assert = elliptic.utils.assert; - -function ShortCurve(conf) { - Base.call(this, 'short', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, Base); -module.exports = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new BN(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN(vec.a, 16), - b: new BN(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : BN.mont(num); - var tinv = new BN(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN(1); - var y1 = new BN(0); - var x2 = new BN(0); - var y2 = new BN(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; - -function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, Base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new BN(k, 16); - - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new BN(0); - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = new BN(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, Base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new BN(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -},{"../../elliptic":63,"../curve":66,"bn.js":48,"inherits":98}],69:[function(require,module,exports){ -'use strict'; - -var curves = exports; - -var hash = require('hash.js'); -var elliptic = require('../elliptic'); - -var assert = elliptic.utils.assert; - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new elliptic.curve.short(options); - else if (options.type === 'edwards') - this.curve = new elliptic.curve.edwards(options); - else - this.curve = new elliptic.curve.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); - -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); - -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); - -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '9' - ] -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); - -var pre; -try { - pre = require('./precomputed/secp256k1'); -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); - -},{"../elliptic":63,"./precomputed/secp256k1":76,"hash.js":85}],70:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var HmacDRBG = require('hmac-drbg'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); - - options = elliptic.curves[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof elliptic.curves.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; -} -module.exports = EC; - -EC.prototype.keyPair = function keyPair(options) { - return new KeyPair(this, options); -}; - -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair.fromPrivate(this, priv, enc); -}; - -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair.fromPublic(this, pub, enc); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN(2)); - do { - var priv = new BN(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; - -EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN(msg, 16)); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new BN(1)); - - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new BN(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; - - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature(signature, 'hex'); - - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; - -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature(signature, enc); - - var n = this.n; - var e = new BN(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; - -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; - - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -},{"../../elliptic":63,"./key":71,"./signature":72,"bn.js":48,"hmac-drbg":97}],71:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); -} -module.exports = KeyPair; - -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; - -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } - - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - if (!enc) - return this.pub; - - return this.pub.encode(enc, compact); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN(key, enc || 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -},{"../../elliptic":63,"bn.js":48}],72:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -function Signature(options, enc) { - if (options instanceof Signature) - return options; - - if (this._importDER(options, enc)) - return; - - assert(options.r && options.s, 'Signature without r or s'); - this.r = new BN(options.r, 16); - this.s = new BN(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; -} -module.exports = Signature; - -function Position() { - this.place = 0; -} - -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} - -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); - } - - this.r = new BN(r); - this.s = new BN(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils.encode(res, enc); -}; - -},{"../../elliptic":63,"bn.js":48}],73:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = elliptic.curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; -} - -module.exports = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils.intFromLE(hash.digest()).umod(this.curve.n); -}; - -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair.fromPublic(this, pub); -}; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair.fromSecret(this, secret); -}; - -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); -}; - -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; - -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; - -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; - -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils.intFromLE(bytes); -}; - -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; - -},{"../../elliptic":63,"./key":74,"./signature":75,"hash.js":85}],74:[function(require,module,exports){ -'use strict'; - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var cachedProperty = utils.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes(params.pub); -} - -KeyPair.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair) - return pub; - return new KeyPair(eddsa, { pub: pub }); -}; - -KeyPair.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair) - return secret; - return new KeyPair(eddsa, { secret: secret }); -}; - -KeyPair.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair.prototype.sign = function sign(message) { - assert(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair.prototype.getSecret = function getSecret(enc) { - assert(this._secret, 'KeyPair is public only'); - return utils.encode(this.secret(), enc); -}; - -KeyPair.prototype.getPublic = function getPublic(enc) { - return utils.encode(this.pubBytes(), enc); -}; - -module.exports = KeyPair; - -},{"../../elliptic":63}],75:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var cachedProperty = utils.cachedProperty; -var parseBytes = utils.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; - } - - assert(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty(Signature, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty(Signature, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty(Signature, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty(Signature, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature.prototype.toHex = function toHex() { - return utils.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -module.exports = Signature; - -},{"../../elliptic":63,"bn.js":48}],76:[function(require,module,exports){ -module.exports = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; - -},{}],77:[function(require,module,exports){ -'use strict'; - -var utils = exports; -var BN = require('bn.js'); -var minAssert = require('minimalistic-assert'); -var minUtils = require('minimalistic-crypto-utils'); - -utils.assert = minAssert; -utils.toArray = minUtils.toArray; -utils.zero2 = minUtils.zero2; -utils.toHex = minUtils.toHex; -utils.encode = minUtils.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; - - -},{"bn.js":48,"minimalistic-assert":111,"minimalistic-crypto-utils":112}],78:[function(require,module,exports){ -module.exports={ - "_from": "elliptic@^6.2.3", - "_id": "elliptic@6.4.1", - "_inBundle": false, - "_integrity": "sha512-BsXLz5sqX8OHcsh7CqBMztyXARmGQ3LWPtGjJi6DiJHq5C/qvi9P3OqgswKSDftbu8+IoI/QDTAm2fFnQ9SZSQ==", - "_location": "/elliptic", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "elliptic@^6.2.3", - "name": "elliptic", - "escapedName": "elliptic", - "rawSpec": "^6.2.3", - "saveSpec": null, - "fetchSpec": "^6.2.3" - }, - "_requiredBy": [ - "/browserify-sign", - "/create-ecdh", - "/eth-lib", - "/secp256k1", - "/web3-eth-accounts/eth-lib", - "/web3-utils/eth-lib" - ], - "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.1.tgz", - "_shasum": "c2d0b7776911b86722c632c3c06c60f2f819939a", - "_spec": "elliptic@^6.2.3", - "_where": "/Users/pidgin/projects/array-io-keychain/docs/src/node_modules/secp256k1", - "author": { - "name": "Fedor Indutny", - "email": "fedor@indutny.com" - }, - "bugs": { - "url": "https://github.com/indutny/elliptic/issues" - }, - "bundleDependencies": false, - "dependencies": { - "bn.js": "^4.4.0", - "brorand": "^1.0.1", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.0" - }, - "deprecated": false, - "description": "EC cryptography", - "devDependencies": { - "brfs": "^1.4.3", - "coveralls": "^2.11.3", - "grunt": "^0.4.5", - "grunt-browserify": "^5.0.0", - "grunt-cli": "^1.2.0", - "grunt-contrib-connect": "^1.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^1.0.1", - "grunt-mocha-istanbul": "^3.0.1", - "grunt-saucelabs": "^8.6.2", - "istanbul": "^0.4.2", - "jscs": "^2.9.0", - "jshint": "^2.6.0", - "mocha": "^2.1.0" - }, - "files": [ - "lib" - ], - "homepage": "https://github.com/indutny/elliptic", - "keywords": [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ], - "license": "MIT", - "main": "lib/elliptic.js", - "name": "elliptic", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/indutny/elliptic.git" - }, - "scripts": { - "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "lint": "npm run jscs && npm run jshint", - "test": "npm run lint && npm run unit", - "unit": "istanbul test _mocha --reporter=spec test/index.js", - "version": "grunt dist && git add dist/" - }, - "version": "6.4.1" -} - -},{}],79:[function(require,module,exports){ -module.exports={ - "genesisGasLimit": { - "v": 5000, - "d": "Gas limit of the Genesis block." - }, - "genesisDifficulty": { - "v": 17179869184, - "d": "Difficulty of the Genesis block." - }, - "genesisNonce": { - "v": "0x0000000000000042", - "d": "the geneis nonce" - }, - "genesisExtraData": { - "v": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", - "d": "extra data " - }, - "genesisHash": { - "v": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", - "d": "genesis hash" - }, - "genesisStateRoot": { - "v": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544", - "d": "the genesis state root" - }, - "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." - }, - "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." - }, - "maximumExtraDataSize": { - "v": 32, - "d": "Maximum size extra data may be after Genesis." - }, - "epochDuration": { - "v": 30000, - "d": "Duration between proof-of-work epochs." - }, - "stackLimit": { - "v": 1024, - "d": "Maximum size of VM stack allowed." - }, - "callCreateDepth": { - "v": 1024, - "d": "Maximum depth of call/create stack." - }, - - "tierStepGas": { - "v": [0, 2, 3, 5, 8, 10, 20], - "d": "Once per operation, for a selection of them." - }, - "expGas": { - "v": 10, - "d": "Once per EXP instuction." - }, - "expByteGas": { - "v": 10, - "d": "Times ceil(log256(exponent)) for the EXP instruction." - }, - - "sha3Gas": { - "v": 30, - "d": "Once per SHA3 operation." - }, - "sha3WordGas": { - "v": 6, - "d": "Once per word of the SHA3 operation's data." - }, - "sloadGas": { - "v": 50, - "d": "Once per SLOAD operation." - }, - "sstoreSetGas": { - "v": 20000, - "d": "Once per SSTORE operation if the zeroness changes from zero." - }, - "sstoreResetGas": { - "v": 5000, - "d": "Once per SSTORE operation if the zeroness does not change from zero." - }, - "sstoreRefundGas": { - "v": 15000, - "d": "Once per SSTORE operation if the zeroness changes to zero." - }, - "jumpdestGas": { - "v": 1, - "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero." - }, - - "logGas": { - "v": 375, - "d": "Per LOG* operation." - }, - "logDataGas": { - "v": 8, - "d": "Per byte in a LOG* operation's data." - }, - "logTopicGas": { - "v": 375, - "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas." - }, - - "createGas": { - "v": 32000, - "d": "Once per CREATE operation & contract-creation transaction." - }, - - "callGas": { - "v": 40, - "d": "Once per CALL operation & message call transaction." - }, - "callStipend": { - "v": 2300, - "d": "Free gas given at beginning of call." - }, - "callValueTransferGas": { - "v": 9000, - "d": "Paid for CALL when the value transfor is non-zero." - }, - "callNewAccountGas": { - "v": 25000, - "d": "Paid for CALL when the destination address didn't exist prior." - }, - - "suicideRefundGas": { - "v": 24000, - "d": "Refunded following a suicide operation." - }, - - "memoryGas": { - "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." - }, - - "createDataGas": { - "v": 200, - "d": "" - }, - "txGas": { - "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" - }, - "txDataZeroGas": { - "v": 4, - "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions." - }, - "txDataNonZeroGas": { - "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." - }, - - "copyGas": { - "v": 3, - "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added." - }, - - "ecrecoverGas": { - "v": 3000, - "d": "" - }, - "sha256Gas": { - "v": 60, - "d": "" - }, - "sha256WordGas": { - "v": 12, - "d": "" - }, - "ripemd160Gas": { - "v": 600, - "d": "" - }, - "ripemd160WordGas": { - "v": 120, - "d": "" - }, - "identityGas": { - "v": 15, - "d": "" - }, - "identityWordGas": { - "v": 3, - "d": "" - }, - "minerReward": { - "v": "5000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - }, - "ommerReward": { - "v": "625000000000000000", - "d": "The amount of wei a miner of an uncle block gets for being inculded in the blockchain" - }, - "niblingReward": { - "v": "156250000000000000", - "d": "the amount a miner gets for inculding a uncle" - }, - "homeSteadForkNumber": { - "v": 1150000, - "d": "the block that the Homestead fork started at" - }, - "homesteadRepriceForkNumber": { - "v": 2463000, - "d": "the block that the Homestead Reprice (EIP150) fork started at" - }, - "timebombPeriod": { - "v": 100000, - "d": "Exponential difficulty timebomb period" - }, - "freeBlockPeriod": { - "v": 2 - } -} - -},{}],80:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var ethUtil = require('ethereumjs-util'); -var fees = require('ethereum-common/params.json'); -var BN = ethUtil.BN; - -// secp256k1n/2 -var N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - -/** - * Creates a new transaction object. - * - * @example - * var rawTx = { - * nonce: '00', - * gasPrice: '09184e72a000', - * gasLimit: '2710', - * to: '0000000000000000000000000000000000000000', - * value: '00', - * data: '7f7465737432000000000000000000000000000000000000000000000000000000600057', - * v: '1c', - * r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab', - * s: '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13' - * }; - * var tx = new Transaction(rawTx); - * - * @class - * @param {Buffer | Array | Object} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. - * - * Or lastly an Object containing the Properties of the transaction like in the Usage example. - * - * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum - * - * @property {Buffer} raw The raw rlp encoded transaction - * @param {Buffer} data.nonce nonce number - * @param {Buffer} data.gasLimit transaction gas limit - * @param {Buffer} data.gasPrice transaction gas price - * @param {Buffer} data.to to the to address - * @param {Buffer} data.value the amount of ether sent - * @param {Buffer} data.data this will contain the data of the message or the init of a contract - * @param {Buffer} data.v EC signature parameter - * @param {Buffer} data.r EC signature parameter - * @param {Buffer} data.s EC recovery ID - * @param {Number} data.chainId EIP 155 chainId - mainnet: 1, ropsten: 3 - * */ - -var Transaction = function () { - function Transaction(data) { - _classCallCheck(this, Transaction); - - data = data || {}; - // Define Properties - var fields = [{ - name: 'nonce', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'gasPrice', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'gasLimit', - alias: 'gas', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'to', - allowZero: true, - length: 20, - default: new Buffer([]) - }, { - name: 'value', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'data', - alias: 'input', - allowZero: true, - default: new Buffer([]) - }, { - name: 'v', - allowZero: true, - default: new Buffer([0x1c]) - }, { - name: 'r', - length: 32, - allowZero: true, - allowLess: true, - default: new Buffer([]) - }, { - name: 's', - length: 32, - allowZero: true, - allowLess: true, - default: new Buffer([]) - }]; - - /** - * Returns the rlp encoding of the transaction - * @method serialize - * @return {Buffer} - * @memberof Transaction - * @name serialize - */ - // attached serialize - ethUtil.defineProperties(this, fields, data); - - /** - * @property {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters. - * @name from - * @memberof Transaction - */ - Object.defineProperty(this, 'from', { - enumerable: true, - configurable: true, - get: this.getSenderAddress.bind(this) - }); - - // calculate chainId from signature - var sigV = ethUtil.bufferToInt(this.v); - var chainId = Math.floor((sigV - 35) / 2); - if (chainId < 0) chainId = 0; - - // set chainId - this._chainId = chainId || data.chainId || 0; - this._homestead = true; - } - - /** - * If the tx's `to` is to the creation address - * @return {Boolean} - */ - - - Transaction.prototype.toCreationAddress = function toCreationAddress() { - return this.to.toString('hex') === ''; - }; - - /** - * Computes a sha3-256 hash of the serialized tx - * @param {Boolean} [includeSignature=true] whether or not to inculde the signature - * @return {Buffer} - */ - - - Transaction.prototype.hash = function hash(includeSignature) { - if (includeSignature === undefined) includeSignature = true; - - // EIP155 spec: - // when computing the hash of a transaction for purposes of signing or recovering, - // instead of hashing only the first six elements (ie. nonce, gasprice, startgas, to, value, data), - // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0 - - var items = void 0; - if (includeSignature) { - items = this.raw; - } else { - if (this._chainId > 0) { - var raw = this.raw.slice(); - this.v = this._chainId; - this.r = 0; - this.s = 0; - items = this.raw; - this.raw = raw; - } else { - items = this.raw.slice(0, 6); - } - } - - // create hash - return ethUtil.rlphash(items); - }; - - /** - * returns the public key of the sender - * @return {Buffer} - */ - - - Transaction.prototype.getChainId = function getChainId() { - return this._chainId; - }; - - /** - * returns the sender's address - * @return {Buffer} - */ - - - Transaction.prototype.getSenderAddress = function getSenderAddress() { - if (this._from) { - return this._from; - } - var pubkey = this.getSenderPublicKey(); - this._from = ethUtil.publicToAddress(pubkey); - return this._from; - }; - - /** - * returns the public key of the sender - * @return {Buffer} - */ - - - Transaction.prototype.getSenderPublicKey = function getSenderPublicKey() { - if (!this._senderPubKey || !this._senderPubKey.length) { - if (!this.verifySignature()) throw new Error('Invalid Signature'); - } - return this._senderPubKey; - }; - - /** - * Determines if the signature is valid - * @return {Boolean} - */ - - - Transaction.prototype.verifySignature = function verifySignature() { - var msgHash = this.hash(false); - // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. - if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) { - return false; - } - - try { - var v = ethUtil.bufferToInt(this.v); - if (this._chainId > 0) { - v -= this._chainId * 2 + 8; - } - this._senderPubKey = ethUtil.ecrecover(msgHash, v, this.r, this.s); - } catch (e) { - return false; - } - - return !!this._senderPubKey; - }; - - /** - * sign a transaction with a given a private key - * @param {Buffer} privateKey - */ - - - Transaction.prototype.sign = function sign(privateKey) { - var msgHash = this.hash(false); - var sig = ethUtil.ecsign(msgHash, privateKey); - if (this._chainId > 0) { - sig.v += this._chainId * 2 + 8; - } - Object.assign(this, sig); - }; - - /** - * The amount of gas paid for the data in this tx - * @return {BN} - */ - - - Transaction.prototype.getDataFee = function getDataFee() { - var data = this.raw[5]; - var cost = new BN(0); - for (var i = 0; i < data.length; i++) { - data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v); - } - return cost; - }; - - /** - * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) - * @return {BN} - */ - - - Transaction.prototype.getBaseFee = function getBaseFee() { - var fee = this.getDataFee().iaddn(fees.txGas.v); - if (this._homestead && this.toCreationAddress()) { - fee.iaddn(fees.txCreation.v); - } - return fee; - }; - - /** - * the up front amount that an account must have for this transaction to be valid - * @return {BN} - */ - - - Transaction.prototype.getUpfrontCost = function getUpfrontCost() { - return new BN(this.gasLimit).imul(new BN(this.gasPrice)).iadd(new BN(this.value)); - }; - - /** - * validates the signature and checks to see if it has enough gas - * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean - * @return {Boolean|String} - */ - - - Transaction.prototype.validate = function validate(stringError) { - var errors = []; - if (!this.verifySignature()) { - errors.push('Invalid Signature'); - } - - if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) { - errors.push(['gas limit is too low. Need at least ' + this.getBaseFee()]); - } - - if (stringError === undefined || stringError === false) { - return errors.length === 0; - } else { - return errors.join(' '); - } - }; - - return Transaction; -}(); - -module.exports = Transaction; -}).call(this,require("buffer").Buffer) -},{"buffer":149,"ethereum-common/params.json":79,"ethereumjs-util":81}],81:[function(require,module,exports){ -'use strict'; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var createKeccakHash = require('keccak'); -var secp256k1 = require('secp256k1'); -var assert = require('assert'); -var rlp = require('rlp'); -var BN = require('bn.js'); -var createHash = require('create-hash'); -var Buffer = require('safe-buffer').Buffer; -Object.assign(exports, require('ethjs-util')); - -/** - * the max integer that this VM can handle (a ```BN```) - * @var {BN} MAX_INTEGER - */ -exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); - -/** - * 2^256 (a ```BN```) - * @var {BN} TWO_POW256 - */ -exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); - -/** - * Keccak-256 hash of null (a ```String```) - * @var {String} KECCAK256_NULL_S - */ -exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; -exports.SHA3_NULL_S = exports.KECCAK256_NULL_S; - -/** - * Keccak-256 hash of null (a ```Buffer```) - * @var {Buffer} KECCAK256_NULL - */ -exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); -exports.SHA3_NULL = exports.KECCAK256_NULL; - -/** - * Keccak-256 of an RLP of an empty array (a ```String```) - * @var {String} KECCAK256_RLP_ARRAY_S - */ -exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; -exports.SHA3_RLP_ARRAY_S = exports.KECCAK256_RLP_ARRAY_S; - -/** - * Keccak-256 of an RLP of an empty array (a ```Buffer```) - * @var {Buffer} KECCAK256_RLP_ARRAY - */ -exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); -exports.SHA3_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY; - -/** - * Keccak-256 hash of the RLP of null (a ```String```) - * @var {String} KECCAK256_RLP_S - */ -exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; -exports.SHA3_RLP_S = exports.KECCAK256_RLP_S; - -/** - * Keccak-256 hash of the RLP of null (a ```Buffer```) - * @var {Buffer} KECCAK256_RLP - */ -exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); -exports.SHA3_RLP = exports.KECCAK256_RLP; - -/** - * [`BN`](https://github.com/indutny/bn.js) - * @var {Function} - */ -exports.BN = BN; - -/** - * [`rlp`](https://github.com/ethereumjs/rlp) - * @var {Function} - */ -exports.rlp = rlp; - -/** - * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) - * @var {Object} - */ -exports.secp256k1 = secp256k1; - -/** - * Returns a buffer filled with 0s - * @method zeros - * @param {Number} bytes the number of bytes the buffer should be - * @return {Buffer} - */ -exports.zeros = function (bytes) { - return Buffer.allocUnsafe(bytes).fill(0); -}; - -/** - * Returns a zero address - * @method zeroAddress - * @return {String} - */ -exports.zeroAddress = function () { - var addressLength = 20; - var zeroAddress = exports.zeros(addressLength); - return exports.bufferToHex(zeroAddress); -}; - -/** - * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @method lsetLength - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @param {Boolean} [right=false] whether to start padding form the left or right - * @return {Buffer|Array} - */ -exports.setLengthLeft = exports.setLength = function (msg, length, right) { - var buf = exports.zeros(length); - msg = exports.toBuffer(msg); - if (right) { - if (msg.length < length) { - msg.copy(buf); - return buf; - } - return msg.slice(0, length); - } else { - if (msg.length < length) { - msg.copy(buf, length - msg.length); - return buf; - } - return msg.slice(-length); - } -}; - -/** - * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @return {Buffer|Array} - */ -exports.setLengthRight = function (msg, length) { - return exports.setLength(msg, length, true); -}; - -/** - * Trims leading zeros from a `Buffer` or an `Array` - * @param {Buffer|Array|String} a - * @return {Buffer|Array|String} - */ -exports.unpad = exports.stripZeros = function (a) { - a = exports.stripHexPrefix(a); - var first = a[0]; - while (a.length > 0 && first.toString() === '0') { - a = a.slice(1); - first = a[0]; - } - return a; -}; -/** - * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. - * @param {*} v the value - */ -exports.toBuffer = function (v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = Buffer.from(v); - } else if (typeof v === 'string') { - if (exports.isHexString(v)) { - v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); - } else { - v = Buffer.from(v); - } - } else if (typeof v === 'number') { - v = exports.intToBuffer(v); - } else if (v === null || v === undefined) { - v = Buffer.allocUnsafe(0); - } else if (BN.isBN(v)) { - v = v.toArrayLike(Buffer); - } else if (v.toArray) { - // converts a BN to a Buffer - v = Buffer.from(v.toArray()); - } else { - throw new Error('invalid type'); - } - } - return v; -}; - -/** - * Converts a `Buffer` to a `Number` - * @param {Buffer} buf - * @return {Number} - * @throws If the input number exceeds 53 bits. - */ -exports.bufferToInt = function (buf) { - return new BN(exports.toBuffer(buf)).toNumber(); -}; - -/** - * Converts a `Buffer` into a hex `String` - * @param {Buffer} buf - * @return {String} - */ -exports.bufferToHex = function (buf) { - buf = exports.toBuffer(buf); - return '0x' + buf.toString('hex'); -}; - -/** - * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. - * @param {Buffer} num - * @return {BN} - */ -exports.fromSigned = function (num) { - return new BN(num).fromTwos(256); -}; - -/** - * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. - * @param {BN} num - * @return {Buffer} - */ -exports.toUnsigned = function (num) { - return Buffer.from(num.toTwos(256).toArray()); -}; - -/** - * Creates Keccak hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bits=256] the Keccak width - * @return {Buffer} - */ -exports.keccak = function (a, bits) { - a = exports.toBuffer(a); - if (!bits) bits = 256; - - return createKeccakHash('keccak' + bits).update(a).digest(); -}; - -/** - * Creates Keccak-256 hash of the input, alias for keccak(a, 256) - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.keccak256 = function (a) { - return exports.keccak(a); -}; - -/** - * Creates SHA-3 (Keccak) hash of the input [OBSOLETE] - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bits=256] the SHA-3 width - * @return {Buffer} - */ -exports.sha3 = exports.keccak; - -/** - * Creates SHA256 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.sha256 = function (a) { - a = exports.toBuffer(a); - return createHash('sha256').update(a).digest(); -}; - -/** - * Creates RIPEMD160 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Boolean} padded whether it should be padded to 256 bits or not - * @return {Buffer} - */ -exports.ripemd160 = function (a, padded) { - a = exports.toBuffer(a); - var hash = createHash('rmd160').update(a).digest(); - if (padded === true) { - return exports.setLength(hash, 32); - } else { - return hash; - } -}; - -/** - * Creates SHA-3 hash of the RLP encoded version of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.rlphash = function (a) { - return exports.keccak(rlp.encode(a)); -}; - -/** - * Checks if the private key satisfies the rules of the curve secp256k1. - * @param {Buffer} privateKey - * @return {Boolean} - */ -exports.isValidPrivate = function (privateKey) { - return secp256k1.privateKeyVerify(privateKey); -}; - -/** - * Checks if the public key satisfies the rules of the curve secp256k1 - * and the requirements of Ethereum. - * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Boolean} - */ -exports.isValidPublic = function (publicKey, sanitize) { - if (publicKey.length === 64) { - // Convert to SEC1 for secp256k1 - return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); - } - - if (!sanitize) { - return false; - } - - return secp256k1.publicKeyVerify(publicKey); -}; - -/** - * Returns the ethereum address of a given public key. - * Accepts "Ethereum public keys" and SEC1 encoded keys. - * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Buffer} - */ -exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { - pubKey = exports.toBuffer(pubKey); - if (sanitize && pubKey.length !== 64) { - pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); - } - assert(pubKey.length === 64); - // Only take the lower 160bits of the hash - return exports.keccak(pubKey).slice(-20); -}; - -/** - * Returns the ethereum public key of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -var privateToPublic = exports.privateToPublic = function (privateKey) { - privateKey = exports.toBuffer(privateKey); - // skip the type flag and use the X, Y points - return secp256k1.publicKeyCreate(privateKey, false).slice(1); -}; - -/** - * Converts a public key to the Ethereum format. - * @param {Buffer} publicKey - * @return {Buffer} - */ -exports.importPublic = function (publicKey) { - publicKey = exports.toBuffer(publicKey); - if (publicKey.length !== 64) { - publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); - } - return publicKey; -}; - -/** - * ECDSA sign - * @param {Buffer} msgHash - * @param {Buffer} privateKey - * @return {Object} - */ -exports.ecsign = function (msgHash, privateKey) { - var sig = secp256k1.sign(msgHash, privateKey); - - var ret = {}; - ret.r = sig.signature.slice(0, 32); - ret.s = sig.signature.slice(32, 64); - ret.v = sig.recovery + 27; - return ret; -}; - -/** - * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. - * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` - * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key - * used to produce the signature. - * @param message - * @returns {Buffer} hash - */ -exports.hashPersonalMessage = function (message) { - var prefix = exports.toBuffer('\x19Ethereum Signed Message:\n' + message.length.toString()); - return exports.keccak(Buffer.concat([prefix, message])); -}; - -/** - * ECDSA public key recovery from signature - * @param {Buffer} msgHash - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {Buffer} publicKey - */ -exports.ecrecover = function (msgHash, v, r, s) { - var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); - var recovery = v - 27; - if (recovery !== 0 && recovery !== 1) { - throw new Error('Invalid signature v value'); - } - var senderPubKey = secp256k1.recover(msgHash, signature, recovery); - return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); -}; - -/** - * Convert signature parameters into the format of `eth_sign` RPC method - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {String} sig - */ -exports.toRpcSig = function (v, r, s) { - // NOTE: with potential introduction of chainId this might need to be updated - if (v !== 27 && v !== 28) { - throw new Error('Invalid recovery id'); - } - - // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin - // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 - return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v - 27)])); -}; - -/** - * Convert signature format of the `eth_sign` RPC method to signature parameters - * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 - * @param {String} sig - * @return {Object} - */ -exports.fromRpcSig = function (sig) { - sig = exports.toBuffer(sig); - - // NOTE: with potential introduction of chainId this might need to be updated - if (sig.length !== 65) { - throw new Error('Invalid signature length'); - } - - var v = sig[64]; - // support both versions of `eth_sign` responses - if (v < 27) { - v += 27; - } - - return { - v: v, - r: sig.slice(0, 32), - s: sig.slice(32, 64) - }; -}; - -/** - * Returns the ethereum address of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -exports.privateToAddress = function (privateKey) { - return exports.publicToAddress(privateToPublic(privateKey)); -}; - -/** - * Checks if the address is a valid. Accepts checksummed addresses too - * @param {String} address - * @return {Boolean} - */ -exports.isValidAddress = function (address) { - return (/^0x[0-9a-fA-F]{40}$/.test(address) - ); -}; - -/** - * Checks if a given address is a zero address - * @method isZeroAddress - * @param {String} address - * @return {Boolean} - */ -exports.isZeroAddress = function (address) { - var zeroAddress = exports.zeroAddress(); - return zeroAddress === exports.addHexPrefix(address); -}; - -/** - * Returns a checksummed address - * @param {String} address - * @return {String} - */ -exports.toChecksumAddress = function (address) { - address = exports.stripHexPrefix(address).toLowerCase(); - var hash = exports.keccak(address).toString('hex'); - var ret = '0x'; - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase(); - } else { - ret += address[i]; - } - } - - return ret; -}; - -/** - * Checks if the address is a valid checksummed address - * @param {Buffer} address - * @return {Boolean} - */ -exports.isValidChecksumAddress = function (address) { - return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; -}; - -/** - * Generates an address of a newly created contract - * @param {Buffer} from the address which is creating this new address - * @param {Buffer} nonce the nonce of the from account - * @return {Buffer} - */ -exports.generateAddress = function (from, nonce) { - from = exports.toBuffer(from); - nonce = new BN(nonce); - - if (nonce.isZero()) { - // in RLP we want to encode null in the case of zero nonce - // read the RLP documentation for an answer if you dare - nonce = null; - } else { - nonce = Buffer.from(nonce.toArray()); - } - - // Only take the lower 160bits of the hash - return exports.rlphash([from, nonce]).slice(-20); -}; - -/** - * Returns true if the supplied address belongs to a precompiled account (Byzantium) - * @param {Buffer|String} address - * @return {Boolean} - */ -exports.isPrecompiled = function (address) { - var a = exports.unpad(address); - return a.length === 1 && a[0] >= 1 && a[0] <= 8; -}; - -/** - * Adds "0x" to a given `String` if it does not already start with "0x" - * @param {String} str - * @return {String} - */ -exports.addHexPrefix = function (str) { - if (typeof str !== 'string') { - return str; - } - - return exports.isHexPrefixed(str) ? str : '0x' + str; -}; - -/** - * Validate ECDSA signature - * @method isValidSignature - * @param {Buffer} v - * @param {Buffer} r - * @param {Buffer} s - * @param {Boolean} [homestead=true] - * @return {Boolean} - */ - -exports.isValidSignature = function (v, r, s, homestead) { - var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); - - if (r.length !== 32 || s.length !== 32) { - return false; - } - - if (v !== 27 && v !== 28) { - return false; - } - - r = new BN(r); - s = new BN(s); - - if (r.isZero() || r.gt(SECP256K1_N) || s.isZero() || s.gt(SECP256K1_N)) { - return false; - } - - if (homestead === false && new BN(s).cmp(SECP256K1_N_DIV_2) === 1) { - return false; - } - - return true; -}; - -/** - * Converts a `Buffer` or `Array` to JSON - * @param {Buffer|Array} ba - * @return {Array|String|null} - */ -exports.baToJSON = function (ba) { - if (Buffer.isBuffer(ba)) { - return '0x' + ba.toString('hex'); - } else if (ba instanceof Array) { - var array = []; - for (var i = 0; i < ba.length; i++) { - array.push(exports.baToJSON(ba[i])); - } - return array; - } -}; - -/** - * Defines properties on a `Object`. It make the assumption that underlying data is binary. - * @param {Object} self the `Object` to define properties on - * @param {Array} fields an array fields to define. Fields can contain: - * * `name` - the name of the properties - * * `length` - the number of bytes the field can have - * * `allowLess` - if the field can be less than the length - * * `allowEmpty` - * @param {*} data data to be validated against the definitions - */ -exports.defineProperties = function (self, fields, data) { - self.raw = []; - self._fields = []; - - // attach the `toJSON` - self.toJSON = function (label) { - if (label) { - var obj = {}; - self._fields.forEach(function (field) { - obj[field] = '0x' + self[field].toString('hex'); - }); - return obj; - } - return exports.baToJSON(this.raw); - }; - - self.serialize = function serialize() { - return rlp.encode(self.raw); - }; - - fields.forEach(function (field, i) { - self._fields.push(field.name); - function getter() { - return self.raw[i]; - } - function setter(v) { - v = exports.toBuffer(v); - - if (v.toString('hex') === '00' && !field.allowZero) { - v = Buffer.allocUnsafe(0); - } - - if (field.allowLess && field.length) { - v = exports.stripZeros(v); - assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes'); - } else if (!(field.allowZero && v.length === 0) && field.length) { - assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length); - } - - self.raw[i] = v; - } - - Object.defineProperty(self, field.name, { - enumerable: true, - configurable: true, - get: getter, - set: setter - }); - - if (field.default) { - self[field.name] = field.default; - } - - // attach alias - if (field.alias) { - Object.defineProperty(self, field.alias, { - enumerable: false, - configurable: true, - set: setter, - get: getter - }); - } - }); - - // if the constuctor is passed data - if (data) { - if (typeof data === 'string') { - data = Buffer.from(exports.stripHexPrefix(data), 'hex'); - } - - if (Buffer.isBuffer(data)) { - data = rlp.decode(data); - } - - if (Array.isArray(data)) { - if (data.length > self._fields.length) { - throw new Error('wrong number of fields in data'); - } - - // make sure all the items are buffers - data.forEach(function (d, i) { - self[self._fields[i]] = exports.toBuffer(d); - }); - } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { - var keys = Object.keys(data); - fields.forEach(function (field) { - if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]; - if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; - }); - } else { - throw new Error('invalid data'); - } - } -}; -},{"assert":143,"bn.js":48,"create-hash":54,"ethjs-util":83,"keccak":100,"rlp":116,"safe-buffer":117,"secp256k1":118}],82:[function(require,module,exports){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var BN = require("bn.js"); -exports.BN = BN; -var rlp = require("rlp"); -exports.rlp = rlp; -var createKeccakHash = require('keccak'); -var secp256k1 = require('secp256k1'); -exports.secp256k1 = secp256k1; -var assert = require('assert'); -var createHash = require('create-hash'); -var Buffer = require('safe-buffer').Buffer; -var ethjsUtil = require('ethjs-util'); -Object.assign(exports, ethjsUtil); -/** - * The max integer that this VM can handle - */ -exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); -/** - * 2^256 - */ -exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); -/** - * Keccak-256 hash of null - */ -exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; -/** - * Keccak-256 hash of null - */ -exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex'); -/** - * Keccak-256 of an RLP of an empty array - */ -exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; -/** - * Keccak-256 of an RLP of an empty array - */ -exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex'); -/** - * Keccak-256 hash of the RLP of null - */ -exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; -/** - * Keccak-256 hash of the RLP of null - */ -exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex'); -/** - * Returns a buffer filled with 0s. - * @param bytes the number of bytes the buffer should be - */ -exports.zeros = function (bytes) { - return Buffer.allocUnsafe(bytes).fill(0); -}; -/** - * Returns a zero address. - */ -exports.zeroAddress = function () { - var addressLength = 20; - var addr = exports.zeros(addressLength); - return exports.bufferToHex(addr); -}; -/** - * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @param msg the value to pad (Buffer|Array) - * @param length the number of bytes the output should be - * @param right whether to start padding form the left or right - * @return (Buffer|Array) - */ -exports.setLengthLeft = function (msg, length, right) { - if (right === void 0) { right = false; } - var buf = exports.zeros(length); - msg = exports.toBuffer(msg); - if (right) { - if (msg.length < length) { - msg.copy(buf); - return buf; - } - return msg.slice(0, length); - } - else { - if (msg.length < length) { - msg.copy(buf, length - msg.length); - return buf; - } - return msg.slice(-length); - } -}; -exports.setLength = exports.setLengthLeft; -/** - * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @param msg the value to pad (Buffer|Array) - * @param length the number of bytes the output should be - * @return (Buffer|Array) - */ -exports.setLengthRight = function (msg, length) { - return exports.setLength(msg, length, true); -}; -/** - * Trims leading zeros from a `Buffer` or an `Array`. - * @param a (Buffer|Array|String) - * @return (Buffer|Array|String) - */ -exports.unpad = function (a) { - a = ethjsUtil.stripHexPrefix(a); - var first = a[0]; - while (a.length > 0 && first.toString() === '0') { - a = a.slice(1); - first = a[0]; - } - return a; -}; -exports.stripZeros = exports.unpad; -/** - * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. - * @param v the value - */ -exports.toBuffer = function (v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = Buffer.from(v); - } - else if (typeof v === 'string') { - if (exports.isHexString(v)) { - v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); - } - else { - v = Buffer.from(v); - } - } - else if (typeof v === 'number') { - v = exports.intToBuffer(v); - } - else if (v === null || v === undefined) { - v = Buffer.allocUnsafe(0); - } - else if (BN.isBN(v)) { - v = v.toArrayLike(Buffer); - } - else if (v.toArray) { - // converts a BN to a Buffer - v = Buffer.from(v.toArray()); - } - else { - throw new Error('invalid type'); - } - } - return v; -}; -/** - * Converts a `Buffer` to a `Number`. - * @param buf `Buffer` object to convert - * @throws If the input number exceeds 53 bits. - */ -exports.bufferToInt = function (buf) { - return new BN(exports.toBuffer(buf)).toNumber(); -}; -/** - * Converts a `Buffer` into a hex `String`. - * @param buf `Buffer` object to convert - */ -exports.bufferToHex = function (buf) { - buf = exports.toBuffer(buf); - return '0x' + buf.toString('hex'); -}; -/** - * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. - * @param num Signed integer value - */ -exports.fromSigned = function (num) { - return new BN(num).fromTwos(256); -}; -/** - * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. - * @param num - */ -exports.toUnsigned = function (num) { - return Buffer.from(num.toTwos(256).toArray()); -}; -/** - * Creates Keccak hash of the input - * @param a The input data (Buffer|Array|String|Number) - * @param bits The Keccak width - */ -exports.keccak = function (a, bits) { - if (bits === void 0) { bits = 256; } - a = exports.toBuffer(a); - if (!bits) - bits = 256; - return createKeccakHash("keccak" + bits) - .update(a) - .digest(); -}; -/** - * Creates Keccak-256 hash of the input, alias for keccak(a, 256). - * @param a The input data (Buffer|Array|String|Number) - */ -exports.keccak256 = function (a) { - return exports.keccak(a); -}; -/** - * Creates SHA256 hash of the input. - * @param a The input data (Buffer|Array|String|Number) - */ -exports.sha256 = function (a) { - a = exports.toBuffer(a); - return createHash('sha256') - .update(a) - .digest(); -}; -/** - * Creates RIPEMD160 hash of the input. - * @param a The input data (Buffer|Array|String|Number) - * @param padded Whether it should be padded to 256 bits or not - */ -exports.ripemd160 = function (a, padded) { - a = exports.toBuffer(a); - var hash = createHash('rmd160') - .update(a) - .digest(); - if (padded === true) { - return exports.setLength(hash, 32); - } - else { - return hash; - } -}; -/** - * Creates SHA-3 hash of the RLP encoded version of the input. - * @param a The input data - */ -exports.rlphash = function (a) { - return exports.keccak(rlp.encode(a)); -}; -/** - * Checks if the private key satisfies the rules of the curve secp256k1. - */ -exports.isValidPrivate = function (privateKey) { - return secp256k1.privateKeyVerify(privateKey); -}; -/** - * Checks if the public key satisfies the rules of the curve secp256k1 - * and the requirements of Ethereum. - * @param publicKey The two points of an uncompressed key, unless sanitize is enabled - * @param sanitize Accept public keys in other formats - */ -exports.isValidPublic = function (publicKey, sanitize) { - if (sanitize === void 0) { sanitize = false; } - if (publicKey.length === 64) { - // Convert to SEC1 for secp256k1 - return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); - } - if (!sanitize) { - return false; - } - return secp256k1.publicKeyVerify(publicKey); -}; -/** - * Returns the ethereum address of a given public key. - * Accepts "Ethereum public keys" and SEC1 encoded keys. - * @param pubKey The two points of an uncompressed key, unless sanitize is enabled - * @param sanitize Accept public keys in other formats - */ -exports.pubToAddress = function (pubKey, sanitize) { - if (sanitize === void 0) { sanitize = false; } - pubKey = exports.toBuffer(pubKey); - if (sanitize && pubKey.length !== 64) { - pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); - } - assert(pubKey.length === 64); - // Only take the lower 160bits of the hash - return exports.keccak(pubKey).slice(-20); -}; -exports.publicToAddress = exports.pubToAddress; -/** - * Returns the ethereum public key of a given private key. - * @param privateKey A private key must be 256 bits wide - */ -exports.privateToPublic = function (privateKey) { - privateKey = exports.toBuffer(privateKey); - // skip the type flag and use the X, Y points - return secp256k1.publicKeyCreate(privateKey, false).slice(1); -}; -/** - * Converts a public key to the Ethereum format. - */ -exports.importPublic = function (publicKey) { - publicKey = exports.toBuffer(publicKey); - if (publicKey.length !== 64) { - publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); - } - return publicKey; -}; -/** - * Returns the ECDSA signature of a message hash. - */ -exports.ecsign = function (msgHash, privateKey, chainId) { - var sig = secp256k1.sign(msgHash, privateKey); - var recovery = sig.recovery; - var ret = { - r: sig.signature.slice(0, 32), - s: sig.signature.slice(32, 64), - v: chainId ? recovery + (chainId * 2 + 35) : recovery + 27, - }; - return ret; -}; -/** - * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. - * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` - * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key - * used to produce the signature. - */ -exports.hashPersonalMessage = function (message) { - var prefix = exports.toBuffer("\u0019Ethereum Signed Message:\n" + message.length.toString()); - return exports.keccak(Buffer.concat([prefix, message])); -}; -/** - * ECDSA public key recovery from signature. - * @returns Recovered public key - */ -exports.ecrecover = function (msgHash, v, r, s, chainId) { - var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); - var recovery = calculateSigRecovery(v, chainId); - if (!isValidSigRecovery(recovery)) { - throw new Error('Invalid signature v value'); - } - var senderPubKey = secp256k1.recover(msgHash, signature, recovery); - return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); -}; -/** - * Convert signature parameters into the format of `eth_sign` RPC method. - * @returns Signature - */ -exports.toRpcSig = function (v, r, s, chainId) { - var recovery = calculateSigRecovery(v, chainId); - if (!isValidSigRecovery(recovery)) { - throw new Error('Invalid signature v value'); - } - // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin - return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v)])); -}; -/** - * Convert signature format of the `eth_sign` RPC method to signature parameters - * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 - */ -exports.fromRpcSig = function (sig) { - var buf = exports.toBuffer(sig); - // NOTE: with potential introduction of chainId this might need to be updated - if (buf.length !== 65) { - throw new Error('Invalid signature length'); - } - var v = buf[64]; - // support both versions of `eth_sign` responses - if (v < 27) { - v += 27; - } - return { - v: v, - r: buf.slice(0, 32), - s: buf.slice(32, 64), - }; -}; -/** - * Returns the ethereum address of a given private key. - * @param privateKey A private key must be 256 bits wide - */ -exports.privateToAddress = function (privateKey) { - return exports.publicToAddress(exports.privateToPublic(privateKey)); -}; -/** - * Checks if the address is a valid. Accepts checksummed addresses too. - */ -exports.isValidAddress = function (address) { - return /^0x[0-9a-fA-F]{40}$/.test(address); -}; -/** - * Checks if a given address is a zero address. - */ -exports.isZeroAddress = function (address) { - var zeroAddr = exports.zeroAddress(); - return zeroAddr === exports.addHexPrefix(address); -}; -/** - * Returns a checksummed address. - */ -exports.toChecksumAddress = function (address) { - address = ethjsUtil.stripHexPrefix(address).toLowerCase(); - var hash = exports.keccak(address).toString('hex'); - var ret = '0x'; - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase(); - } - else { - ret += address[i]; - } - } - return ret; -}; -/** - * Checks if the address is a valid checksummed address. - */ -exports.isValidChecksumAddress = function (address) { - return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; -}; -/** - * Generates an address of a newly created contract. - * @param from The address which is creating this new address - * @param nonce The nonce of the from account - */ -exports.generateAddress = function (from, nonce) { - from = exports.toBuffer(from); - var nonceBN = new BN(nonce); - if (nonceBN.isZero()) { - // in RLP we want to encode null in the case of zero nonce - // read the RLP documentation for an answer if you dare - return exports.rlphash([from, null]).slice(-20); - } - // Only take the lower 160bits of the hash - return exports.rlphash([from, Buffer.from(nonceBN.toArray())]).slice(-20); -}; -/** - * Generates an address for a contract created using CREATE2. - * @param from The address which is creating this new address - * @param salt A salt - * @param initCode The init code of the contract being created - */ -exports.generateAddress2 = function (from, salt, initCode) { - var fromBuf = exports.toBuffer(from); - var saltBuf = exports.toBuffer(salt); - var initCodeBuf = exports.toBuffer(initCode); - assert(fromBuf.length === 20); - assert(saltBuf.length === 32); - var address = exports.keccak256(Buffer.concat([Buffer.from('ff', 'hex'), fromBuf, saltBuf, exports.keccak256(initCodeBuf)])); - return address.slice(-20); -}; -/** - * Returns true if the supplied address belongs to a precompiled account (Byzantium). - */ -exports.isPrecompiled = function (address) { - var a = exports.unpad(address); - return a.length === 1 && a[0] >= 1 && a[0] <= 8; -}; -/** - * Adds "0x" to a given `String` if it does not already start with "0x". - */ -exports.addHexPrefix = function (str) { - if (typeof str !== 'string') { - return str; - } - return ethjsUtil.isHexPrefixed(str) ? str : '0x' + str; -}; -/** - * Validate a ECDSA signature. - * @param homesteadOrLater Indicates whether this is being used on either the homestead hardfork or a later one - */ -exports.isValidSignature = function (v, r, s, homesteadOrLater, chainId) { - if (homesteadOrLater === void 0) { homesteadOrLater = true; } - var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); - if (r.length !== 32 || s.length !== 32) { - return false; - } - if (!isValidSigRecovery(calculateSigRecovery(v, chainId))) { - return false; - } - var rBN = new BN(r); - var sBN = new BN(s); - if (rBN.isZero() || rBN.gt(SECP256K1_N) || sBN.isZero() || sBN.gt(SECP256K1_N)) { - return false; - } - if (homesteadOrLater && sBN.cmp(SECP256K1_N_DIV_2) === 1) { - return false; - } - return true; -}; -/** - * Converts a `Buffer` or `Array` to JSON. - * @param ba (Buffer|Array) - * @return (Array|String|null) - */ -exports.baToJSON = function (ba) { - if (Buffer.isBuffer(ba)) { - return "0x" + ba.toString('hex'); - } - else if (ba instanceof Array) { - var array = []; - for (var i = 0; i < ba.length; i++) { - array.push(exports.baToJSON(ba[i])); - } - return array; - } -}; -/** - * Defines properties on a `Object`. It make the assumption that underlying data is binary. - * @param self the `Object` to define properties on - * @param fields an array fields to define. Fields can contain: - * * `name` - the name of the properties - * * `length` - the number of bytes the field can have - * * `allowLess` - if the field can be less than the length - * * `allowEmpty` - * @param data data to be validated against the definitions - */ -exports.defineProperties = function (self, fields, data) { - self.raw = []; - self._fields = []; - // attach the `toJSON` - self.toJSON = function (label) { - if (label === void 0) { label = false; } - if (label) { - var obj_1 = {}; - self._fields.forEach(function (field) { - obj_1[field] = "0x" + self[field].toString('hex'); - }); - return obj_1; - } - return exports.baToJSON(self.raw); - }; - self.serialize = function serialize() { - return rlp.encode(self.raw); - }; - fields.forEach(function (field, i) { - self._fields.push(field.name); - function getter() { - return self.raw[i]; - } - function setter(v) { - v = exports.toBuffer(v); - if (v.toString('hex') === '00' && !field.allowZero) { - v = Buffer.allocUnsafe(0); - } - if (field.allowLess && field.length) { - v = exports.stripZeros(v); - assert(field.length >= v.length, "The field " + field.name + " must not have more " + field.length + " bytes"); - } - else if (!(field.allowZero && v.length === 0) && field.length) { - assert(field.length === v.length, "The field " + field.name + " must have byte length of " + field.length); - } - self.raw[i] = v; - } - Object.defineProperty(self, field.name, { - enumerable: true, - configurable: true, - get: getter, - set: setter, - }); - if (field.default) { - self[field.name] = field.default; - } - // attach alias - if (field.alias) { - Object.defineProperty(self, field.alias, { - enumerable: false, - configurable: true, - set: setter, - get: getter, - }); - } - }); - // if the constuctor is passed data - if (data) { - if (typeof data === 'string') { - data = Buffer.from(ethjsUtil.stripHexPrefix(data), 'hex'); - } - if (Buffer.isBuffer(data)) { - data = rlp.decode(data); - } - if (Array.isArray(data)) { - if (data.length > self._fields.length) { - throw new Error('wrong number of fields in data'); - } - // make sure all the items are buffers - data.forEach(function (d, i) { - self[self._fields[i]] = exports.toBuffer(d); - }); - } - else if (typeof data === 'object') { - var keys_1 = Object.keys(data); - fields.forEach(function (field) { - if (keys_1.indexOf(field.name) !== -1) - self[field.name] = data[field.name]; - if (keys_1.indexOf(field.alias) !== -1) - self[field.alias] = data[field.alias]; - }); - } - else { - throw new Error('invalid data'); - } - } -}; -function calculateSigRecovery(v, chainId) { - return chainId ? v - (2 * chainId + 35) : v - 27; -} -function isValidSigRecovery(recovery) { - return recovery === 0 || recovery === 1; -} - -},{"assert":143,"bn.js":48,"create-hash":54,"ethjs-util":83,"keccak":100,"rlp":116,"safe-buffer":117,"secp256k1":118}],83:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var isHexPrefixed = require('is-hex-prefixed'); -var stripHexPrefix = require('strip-hex-prefix'); - -/** - * Pads a `String` to have an even length - * @param {String} value - * @return {String} output - */ -function padToEven(value) { - var a = value; // eslint-disable-line - - if (typeof a !== 'string') { - throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.'); - } - - if (a.length % 2) { - a = '0' + a; - } - - return a; -} - -/** - * Converts a `Number` into a hex `String` - * @param {Number} i - * @return {String} - */ -function intToHex(i) { - var hex = i.toString(16); // eslint-disable-line - - return '0x' + hex; -} - -/** - * Converts an `Number` to a `Buffer` - * @param {Number} i - * @return {Buffer} - */ -function intToBuffer(i) { - var hex = intToHex(i); - - return new Buffer(padToEven(hex.slice(2)), 'hex'); -} - -/** - * Get the binary size of a string - * @param {String} str - * @return {Number} - */ -function getBinarySize(str) { - if (typeof str !== 'string') { - throw new Error('[ethjs-util] while getting binary size, method getBinarySize requires input \'str\' to be type String, got \'' + typeof str + '\'.'); - } - - return Buffer.byteLength(str, 'utf8'); -} - -/** - * Returns TRUE if the first specified array contains all elements - * from the second one. FALSE otherwise. - * - * @param {array} superset - * @param {array} subset - * - * @returns {boolean} - */ -function arrayContainsArray(superset, subset, some) { - if (Array.isArray(superset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'superset\' to be an array got type \'' + typeof superset + '\''); - } - if (Array.isArray(subset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'subset\' to be an array got type \'' + typeof subset + '\''); - } - - return subset[Boolean(some) && 'some' || 'every'](function (value) { - return superset.indexOf(value) >= 0; - }); -} - -/** - * Should be called to get utf8 from it's hex representation - * - * @method toUtf8 - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toUtf8(hex) { - var bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex'); - - return bufferValue.toString('utf8'); -} - -/** - * Should be called to get ascii from it's hex representation - * - * @method toAscii - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toAscii(hex) { - var str = ''; // eslint-disable-line - var i = 0, - l = hex.length; // eslint-disable-line - - if (hex.substring(0, 2) === '0x') { - i = 2; - } - - for (; i < l; i += 2) { - var code = parseInt(hex.substr(i, 2), 16); - str += String.fromCharCode(code); - } - - return str; -} - -/** - * Should be called to get hex representation (prefixed by 0x) of utf8 string - * - * @method fromUtf8 - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromUtf8(stringValue) { - var str = new Buffer(stringValue, 'utf8'); - - return '0x' + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); -} - -/** - * Should be called to get hex representation (prefixed by 0x) of ascii string - * - * @method fromAscii - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromAscii(stringValue) { - var hex = ''; // eslint-disable-line - for (var i = 0; i < stringValue.length; i++) { - // eslint-disable-line - var code = stringValue.charCodeAt(i); - var n = code.toString(16); - hex += n.length < 2 ? '0' + n : n; - } - - return '0x' + hex; -} - -/** - * getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] - * - * @method getKeys get specific key from inner object array of objects - * @param {String} params - * @param {String} key - * @param {Boolean} allowEmpty - * @returns {Array} output just a simple array of output keys - */ -function getKeys(params, key, allowEmpty) { - if (!Array.isArray(params)) { - throw new Error('[ethjs-util] method getKeys expecting type Array as \'params\' input, got \'' + typeof params + '\''); - } - if (typeof key !== 'string') { - throw new Error('[ethjs-util] method getKeys expecting type String for input \'key\' got \'' + typeof key + '\'.'); - } - - var result = []; // eslint-disable-line - - for (var i = 0; i < params.length; i++) { - // eslint-disable-line - var value = params[i][key]; // eslint-disable-line - if (allowEmpty && !value) { - value = ''; - } else if (typeof value !== 'string') { - throw new Error('invalid abi'); - } - result.push(value); - } - - return result; -} - -/** - * Is the string a hex string. - * - * @method check if string is hex string of specific length - * @param {String} value - * @param {Number} length - * @returns {Boolean} output the string is a hex string - */ -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; -} - -module.exports = { - arrayContainsArray: arrayContainsArray, - intToBuffer: intToBuffer, - getBinarySize: getBinarySize, - isHexPrefixed: isHexPrefixed, - stripHexPrefix: stripHexPrefix, - padToEven: padToEven, - intToHex: intToHex, - fromAscii: fromAscii, - fromUtf8: fromUtf8, - toAscii: toAscii, - toUtf8: toUtf8, - getKeys: getKeys, - isHexString: isHexString -}; -}).call(this,require("buffer").Buffer) -},{"buffer":149,"is-hex-prefixed":99,"strip-hex-prefix":132}],84:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var inherits = require('inherits') - -function throwIfNotStringOrBuffer (val, prefix) { - if (!Buffer.isBuffer(val) && typeof val !== 'string') { - throw new TypeError(prefix + ' must be a string or a buffer') - } -} - -function HashBase (blockSize) { - Transform.call(this) - - this._block = Buffer.allocUnsafe(blockSize) - this._blockSize = blockSize - this._blockOffset = 0 - this._length = [0, 0, 0, 0] - - this._finalized = false -} - -inherits(HashBase, Transform) - -HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype.update = function (data, encoding) { - throwIfNotStringOrBuffer(data, 'Data') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - // consume data - var block = this._block - var offset = 0 - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] - this._update() - this._blockOffset = 0 - } - while (offset < data.length) block[this._blockOffset++] = data[offset++] - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry - carry = (this._length[j] / 0x0100000000) | 0 - if (carry > 0) this._length[j] -= 0x0100000000 * carry - } - - return this -} - -HashBase.prototype._update = function () { - throw new Error('_update is not implemented') -} - -HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - - var digest = this._digest() - if (encoding !== undefined) digest = digest.toString(encoding) - - // reset state - this._block.fill(0) - this._blockOffset = 0 - for (var i = 0; i < 4; ++i) this._length[i] = 0 - - return digest -} - -HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') -} - -module.exports = HashBase - -},{"inherits":98,"safe-buffer":117,"stream":172}],85:[function(require,module,exports){ -var hash = exports; - -hash.utils = require('./hash/utils'); -hash.common = require('./hash/common'); -hash.sha = require('./hash/sha'); -hash.ripemd = require('./hash/ripemd'); -hash.hmac = require('./hash/hmac'); - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.sha384 = hash.sha.sha384; -hash.sha512 = hash.sha.sha512; -hash.ripemd160 = hash.ripemd.ripemd160; - -},{"./hash/common":86,"./hash/hmac":87,"./hash/ripemd":88,"./hash/sha":89,"./hash/utils":96}],86:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.padLength = this.constructor.padLength / 8; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + this.padLength) % bytes); - var res = new Array(k + this.padLength); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - for (var t = 8; t < this.padLength; t++) - res[i++] = 0; - - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - - for (t = 8; t < this.padLength; t++) - res[i++] = 0; - } - - return res; -}; - -},{"./utils":96,"minimalistic-assert":111}],87:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -},{"./utils":96,"minimalistic-assert":111}],88:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var common = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -},{"./common":86,"./utils":96}],89:[function(require,module,exports){ -'use strict'; - -exports.sha1 = require('./sha/1'); -exports.sha224 = require('./sha/224'); -exports.sha256 = require('./sha/256'); -exports.sha384 = require('./sha/384'); -exports.sha512 = require('./sha/512'); - -},{"./sha/1":90,"./sha/224":91,"./sha/256":92,"./sha/384":93,"./sha/512":94}],90:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_5 = utils.sum32_5; -var ft_1 = shaCommon.ft_1; -var BlockHash = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -module.exports = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; - -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - - for(; i < W.length; i++) - W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -},{"../common":86,"../utils":96,"./common":95}],91:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var SHA256 = require('./256'); - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, SHA256); -module.exports = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - - -},{"../utils":96,"./256":92}],92:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); -var assert = require('minimalistic-assert'); - -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var ch32 = shaCommon.ch32; -var maj32 = shaCommon.maj32; -var s0_256 = shaCommon.s0_256; -var s1_256 = shaCommon.s1_256; -var g0_256 = shaCommon.g0_256; -var g1_256 = shaCommon.g1_256; - -var BlockHash = common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 - ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash); -module.exports = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; -SHA256.padLength = 64; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - assert(this.k.length === W.length); - for (i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -},{"../common":86,"../utils":96,"./common":95,"minimalistic-assert":111}],93:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); - -var SHA512 = require('./512'); - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, SHA512); -module.exports = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -},{"../utils":96,"./512":94}],94:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var assert = require('minimalistic-assert'); - -var rotr64_hi = utils.rotr64_hi; -var rotr64_lo = utils.rotr64_lo; -var shr64_hi = utils.shr64_hi; -var shr64_lo = utils.shr64_lo; -var sum64 = utils.sum64; -var sum64_hi = utils.sum64_hi; -var sum64_lo = utils.sum64_lo; -var sum64_4_hi = utils.sum64_4_hi; -var sum64_4_lo = utils.sum64_4_lo; -var sum64_5_hi = utils.sum64_5_hi; -var sum64_5_lo = utils.sum64_5_lo; - -var BlockHash = common.BlockHash; - -var sha512_K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -]; - -function SHA512() { - if (!(this instanceof SHA512)) - return new SHA512(); - - BlockHash.call(this); - this.h = [ - 0x6a09e667, 0xf3bcc908, - 0xbb67ae85, 0x84caa73b, - 0x3c6ef372, 0xfe94f82b, - 0xa54ff53a, 0x5f1d36f1, - 0x510e527f, 0xade682d1, - 0x9b05688c, 0x2b3e6c1f, - 0x1f83d9ab, 0xfb41bd6b, - 0x5be0cd19, 0x137e2179 ]; - this.k = sha512_K; - this.W = new Array(160); -} -utils.inherits(SHA512, BlockHash); -module.exports = SHA512; - -SHA512.blockSize = 1024; -SHA512.outSize = 512; -SHA512.hmacStrength = 192; -SHA512.padLength = 128; - -SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { - var W = this.W; - - // 32 x 32bit words - for (var i = 0; i < 32; i++) - W[i] = msg[start + i]; - for (; i < W.length; i += 2) { - var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 - var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); - var c1_hi = W[i - 14]; // i - 7 - var c1_lo = W[i - 13]; - var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 - var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); - var c3_hi = W[i - 32]; // i - 16 - var c3_lo = W[i - 31]; - - W[i] = sum64_4_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - W[i + 1] = sum64_4_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo); - } -}; - -SHA512.prototype._update = function _update(msg, start) { - this._prepareBlock(msg, start); - - var W = this.W; - - var ah = this.h[0]; - var al = this.h[1]; - var bh = this.h[2]; - var bl = this.h[3]; - var ch = this.h[4]; - var cl = this.h[5]; - var dh = this.h[6]; - var dl = this.h[7]; - var eh = this.h[8]; - var el = this.h[9]; - var fh = this.h[10]; - var fl = this.h[11]; - var gh = this.h[12]; - var gl = this.h[13]; - var hh = this.h[14]; - var hl = this.h[15]; - - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i += 2) { - var c0_hi = hh; - var c0_lo = hl; - var c1_hi = s1_512_hi(eh, el); - var c1_lo = s1_512_lo(eh, el); - var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); - var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); - var c3_hi = this.k[i]; - var c3_lo = this.k[i + 1]; - var c4_hi = W[i]; - var c4_lo = W[i + 1]; - - var T1_hi = sum64_5_hi( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - var T1_lo = sum64_5_lo( - c0_hi, c0_lo, - c1_hi, c1_lo, - c2_hi, c2_lo, - c3_hi, c3_lo, - c4_hi, c4_lo); - - c0_hi = s0_512_hi(ah, al); - c0_lo = s0_512_lo(ah, al); - c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); - c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); - - var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); - var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); - - hh = gh; - hl = gl; - - gh = fh; - gl = fl; - - fh = eh; - fl = el; - - eh = sum64_hi(dh, dl, T1_hi, T1_lo); - el = sum64_lo(dl, dl, T1_hi, T1_lo); - - dh = ch; - dl = cl; - - ch = bh; - cl = bl; - - bh = ah; - bl = al; - - ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); - al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); - } - - sum64(this.h, 0, ah, al); - sum64(this.h, 2, bh, bl); - sum64(this.h, 4, ch, cl); - sum64(this.h, 6, dh, dl); - sum64(this.h, 8, eh, el); - sum64(this.h, 10, fh, fl); - sum64(this.h, 12, gh, gl); - sum64(this.h, 14, hh, hl); -}; - -SHA512.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ ((~xh) & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function ch64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ ((~xl) & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_hi(xh, xl, yh, yl, zh) { - var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); - if (r < 0) - r += 0x100000000; - return r; -} - -function maj64_lo(xh, xl, yh, yl, zh, zl) { - var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 28); - var c1_hi = rotr64_hi(xl, xh, 2); // 34 - var c2_hi = rotr64_hi(xl, xh, 7); // 39 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 28); - var c1_lo = rotr64_lo(xl, xh, 2); // 34 - var c2_lo = rotr64_lo(xl, xh, 7); // 39 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 14); - var c1_hi = rotr64_hi(xh, xl, 18); - var c2_hi = rotr64_hi(xl, xh, 9); // 41 - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function s1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 14); - var c1_lo = rotr64_lo(xh, xl, 18); - var c2_lo = rotr64_lo(xl, xh, 9); // 41 - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 1); - var c1_hi = rotr64_hi(xh, xl, 8); - var c2_hi = shr64_hi(xh, xl, 7); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g0_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 1); - var c1_lo = rotr64_lo(xh, xl, 8); - var c2_lo = shr64_lo(xh, xl, 7); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_hi(xh, xl) { - var c0_hi = rotr64_hi(xh, xl, 19); - var c1_hi = rotr64_hi(xl, xh, 29); // 61 - var c2_hi = shr64_hi(xh, xl, 6); - - var r = c0_hi ^ c1_hi ^ c2_hi; - if (r < 0) - r += 0x100000000; - return r; -} - -function g1_512_lo(xh, xl) { - var c0_lo = rotr64_lo(xh, xl, 19); - var c1_lo = rotr64_lo(xl, xh, 29); // 61 - var c2_lo = shr64_lo(xh, xl, 6); - - var r = c0_lo ^ c1_lo ^ c2_lo; - if (r < 0) - r += 0x100000000; - return r; -} - -},{"../common":86,"../utils":96,"minimalistic-assert":111}],95:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var rotr32 = utils.rotr32; - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z); - if (s === 2) - return maj32(x, y, z); -} -exports.ft_1 = ft_1; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} -exports.ch32 = ch32; - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} -exports.maj32 = maj32; - -function p32(x, y, z) { - return x ^ y ^ z; -} -exports.p32 = p32; - -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} -exports.s0_256 = s0_256; - -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} -exports.s1_256 = s1_256; - -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} -exports.g0_256 = g0_256; - -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); -} -exports.g1_256 = g1_256; - -},{"../utils":96}],96:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -exports.inherits = inherits; - -function isSurrogatePair(msg, i) { - if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) { - return false; - } - if (i < 0 || i + 1 >= msg.length) { - return false; - } - return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00; -} - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - // Inspired by stringToUtf8ByteArray() in closure-library by Google - // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143 - // Apache License 2.0 - // https://github.com/google/closure-library/blob/master/LICENSE - var p = 0; - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - if (c < 128) { - res[p++] = c; - } else if (c < 2048) { - res[p++] = (c >> 6) | 192; - res[p++] = (c & 63) | 128; - } else if (isSurrogatePair(msg, i)) { - c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF); - res[p++] = (c >> 18) | 240; - res[p++] = ((c >> 12) & 63) | 128; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } else { - res[p++] = (c >> 12) | 224; - res[p++] = ((c >> 6) & 63) | 128; - res[p++] = (c & 63) | 128; - } - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -exports.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -exports.toHex = toHex; - -function htonl(w) { - var res = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - return res >>> 0; -} -exports.htonl = htonl; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') - w = htonl(w); - res += zero8(w.toString(16)); - } - return res; -} -exports.toHex32 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -exports.zero2 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -exports.zero8 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - res[i] = w >>> 0; - } - return res; -} -exports.join32 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -exports.split32 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -exports.rotr32 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -exports.rotl32 = rotl32; - -function sum32(a, b) { - return (a + b) >>> 0; -} -exports.sum32 = sum32; - -function sum32_3(a, b, c) { - return (a + b + c) >>> 0; -} -exports.sum32_3 = sum32_3; - -function sum32_4(a, b, c, d) { - return (a + b + c + d) >>> 0; -} -exports.sum32_4 = sum32_4; - -function sum32_5(a, b, c, d, e) { - return (a + b + c + d + e) >>> 0; -} -exports.sum32_5 = sum32_5; - -function sum64(buf, pos, ah, al) { - var bh = buf[pos]; - var bl = buf[pos + 1]; - - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - buf[pos] = hi >>> 0; - buf[pos + 1] = lo; -} -exports.sum64 = sum64; - -function sum64_hi(ah, al, bh, bl) { - var lo = (al + bl) >>> 0; - var hi = (lo < al ? 1 : 0) + ah + bh; - return hi >>> 0; -} -exports.sum64_hi = sum64_hi; - -function sum64_lo(ah, al, bh, bl) { - var lo = al + bl; - return lo >>> 0; -} -exports.sum64_lo = sum64_lo; - -function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - - var hi = ah + bh + ch + dh + carry; - return hi >>> 0; -} -exports.sum64_4_hi = sum64_4_hi; - -function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { - var lo = al + bl + cl + dl; - return lo >>> 0; -} -exports.sum64_4_lo = sum64_4_lo; - -function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var carry = 0; - var lo = al; - lo = (lo + bl) >>> 0; - carry += lo < al ? 1 : 0; - lo = (lo + cl) >>> 0; - carry += lo < cl ? 1 : 0; - lo = (lo + dl) >>> 0; - carry += lo < dl ? 1 : 0; - lo = (lo + el) >>> 0; - carry += lo < el ? 1 : 0; - - var hi = ah + bh + ch + dh + eh + carry; - return hi >>> 0; -} -exports.sum64_5_hi = sum64_5_hi; - -function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { - var lo = al + bl + cl + dl + el; - - return lo >>> 0; -} -exports.sum64_5_lo = sum64_5_lo; - -function rotr64_hi(ah, al, num) { - var r = (al << (32 - num)) | (ah >>> num); - return r >>> 0; -} -exports.rotr64_hi = rotr64_hi; - -function rotr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.rotr64_lo = rotr64_lo; - -function shr64_hi(ah, al, num) { - return ah >>> num; -} -exports.shr64_hi = shr64_hi; - -function shr64_lo(ah, al, num) { - var r = (ah << (32 - num)) | (al >>> num); - return r >>> 0; -} -exports.shr64_lo = shr64_lo; - -},{"inherits":98,"minimalistic-assert":111}],97:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var utils = require('minimalistic-crypto-utils'); -var assert = require('minimalistic-assert'); - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils.toArray(options.pers, options.persEnc || 'hex'); - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -module.exports = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils.toArray(entropy, entropyEnc); - add = utils.toArray(add, addEnc); - - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils.toArray(add, addEnc || 'hex'); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils.encode(res, enc); -}; - -},{"hash.js":85,"minimalistic-assert":111,"minimalistic-crypto-utils":112}],98:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, 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) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],99:[function(require,module,exports){ -/** - * Returns a `Boolean` on whether or not the a `String` starts with '0x' - * @param {String} str the string input value - * @return {Boolean} a boolean if it is or is not hex prefixed - * @throws if the str input is not a string - */ -module.exports = function isHexPrefixed(str) { - if (typeof str !== 'string') { - throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + (typeof str) + ", while checking isHexPrefixed."); - } - - return str.slice(0, 2) === '0x'; -} - -},{}],100:[function(require,module,exports){ -'use strict' -module.exports = require('./lib/api')(require('./lib/keccak')) - -},{"./lib/api":101,"./lib/keccak":105}],101:[function(require,module,exports){ -'use strict' -var createKeccak = require('./keccak') -var createShake = require('./shake') - -module.exports = function (KeccakState) { - var Keccak = createKeccak(KeccakState) - var Shake = createShake(KeccakState) - - return function (algorithm, options) { - var hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm - switch (hash) { - case 'keccak224': return new Keccak(1152, 448, null, 224, options) - case 'keccak256': return new Keccak(1088, 512, null, 256, options) - case 'keccak384': return new Keccak(832, 768, null, 384, options) - case 'keccak512': return new Keccak(576, 1024, null, 512, options) - - case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options) - case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options) - case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options) - case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options) - - case 'shake128': return new Shake(1344, 256, 0x1f, options) - case 'shake256': return new Shake(1088, 512, 0x1f, options) - - default: throw new Error('Invald algorithm: ' + algorithm) - } - } -} - -},{"./keccak":102,"./shake":103}],102:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var inherits = require('inherits') - -module.exports = function (KeccakState) { - function Keccak (rate, capacity, delimitedSuffix, hashBitLength, options) { - Transform.call(this, options) - - this._rate = rate - this._capacity = capacity - this._delimitedSuffix = delimitedSuffix - this._hashBitLength = hashBitLength - this._options = options - - this._state = new KeccakState() - this._state.initialize(rate, capacity) - this._finalized = false - } - - inherits(Keccak, Transform) - - Keccak.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) - } - - Keccak.prototype._flush = function (callback) { - var error = null - try { - this.push(this.digest()) - } catch (err) { - error = err - } - - callback(error) - } - - Keccak.prototype.update = function (data, encoding) { - if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - this._state.absorb(data) - - return this - } - - Keccak.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - - if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix) - var digest = this._state.squeeze(this._hashBitLength / 8) - if (encoding !== undefined) digest = digest.toString(encoding) - - this._resetState() - - return digest - } - - // remove result from memory - Keccak.prototype._resetState = function () { - this._state.initialize(this._rate, this._capacity) - return this - } - - // because sometimes we need hash right now and little later - Keccak.prototype._clone = function () { - var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options) - this._state.copy(clone._state) - clone._finalized = this._finalized - - return clone - } - - return Keccak -} - -},{"inherits":98,"safe-buffer":117,"stream":172}],103:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var Transform = require('stream').Transform -var inherits = require('inherits') - -module.exports = function (KeccakState) { - function Shake (rate, capacity, delimitedSuffix, options) { - Transform.call(this, options) - - this._rate = rate - this._capacity = capacity - this._delimitedSuffix = delimitedSuffix - this._options = options - - this._state = new KeccakState() - this._state.initialize(rate, capacity) - this._finalized = false - } - - inherits(Shake, Transform) - - Shake.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - this.update(chunk, encoding) - } catch (err) { - error = err - } - - callback(error) - } - - Shake.prototype._flush = function () {} - - Shake.prototype._read = function (size) { - this.push(this.squeeze(size)) - } - - Shake.prototype.update = function (data, encoding) { - if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') - if (this._finalized) throw new Error('Squeeze already called') - if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) - - this._state.absorb(data) - - return this - } - - Shake.prototype.squeeze = function (dataByteLength, encoding) { - if (!this._finalized) { - this._finalized = true - this._state.absorbLastFewBits(this._delimitedSuffix) - } - - var data = this._state.squeeze(dataByteLength) - if (encoding !== undefined) data = data.toString(encoding) - - return data - } - - Shake.prototype._resetState = function () { - this._state.initialize(this._rate, this._capacity) - return this - } - - Shake.prototype._clone = function () { - var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options) - this._state.copy(clone._state) - clone._finalized = this._finalized - - return clone - } - - return Shake -} - -},{"inherits":98,"safe-buffer":117,"stream":172}],104:[function(require,module,exports){ -'use strict' -var P1600_ROUND_CONSTANTS = [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] - -exports.p1600 = function (s) { - for (var round = 0; round < 24; ++round) { - // theta - var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40] - var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41] - var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42] - var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43] - var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44] - var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45] - var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46] - var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47] - var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48] - var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49] - - var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31) - var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31) - var t1slo0 = s[0] ^ lo - var t1shi0 = s[1] ^ hi - var t1slo5 = s[10] ^ lo - var t1shi5 = s[11] ^ hi - var t1slo10 = s[20] ^ lo - var t1shi10 = s[21] ^ hi - var t1slo15 = s[30] ^ lo - var t1shi15 = s[31] ^ hi - var t1slo20 = s[40] ^ lo - var t1shi20 = s[41] ^ hi - lo = lo0 ^ (lo2 << 1 | hi2 >>> 31) - hi = hi0 ^ (hi2 << 1 | lo2 >>> 31) - var t1slo1 = s[2] ^ lo - var t1shi1 = s[3] ^ hi - var t1slo6 = s[12] ^ lo - var t1shi6 = s[13] ^ hi - var t1slo11 = s[22] ^ lo - var t1shi11 = s[23] ^ hi - var t1slo16 = s[32] ^ lo - var t1shi16 = s[33] ^ hi - var t1slo21 = s[42] ^ lo - var t1shi21 = s[43] ^ hi - lo = lo1 ^ (lo3 << 1 | hi3 >>> 31) - hi = hi1 ^ (hi3 << 1 | lo3 >>> 31) - var t1slo2 = s[4] ^ lo - var t1shi2 = s[5] ^ hi - var t1slo7 = s[14] ^ lo - var t1shi7 = s[15] ^ hi - var t1slo12 = s[24] ^ lo - var t1shi12 = s[25] ^ hi - var t1slo17 = s[34] ^ lo - var t1shi17 = s[35] ^ hi - var t1slo22 = s[44] ^ lo - var t1shi22 = s[45] ^ hi - lo = lo2 ^ (lo4 << 1 | hi4 >>> 31) - hi = hi2 ^ (hi4 << 1 | lo4 >>> 31) - var t1slo3 = s[6] ^ lo - var t1shi3 = s[7] ^ hi - var t1slo8 = s[16] ^ lo - var t1shi8 = s[17] ^ hi - var t1slo13 = s[26] ^ lo - var t1shi13 = s[27] ^ hi - var t1slo18 = s[36] ^ lo - var t1shi18 = s[37] ^ hi - var t1slo23 = s[46] ^ lo - var t1shi23 = s[47] ^ hi - lo = lo3 ^ (lo0 << 1 | hi0 >>> 31) - hi = hi3 ^ (hi0 << 1 | lo0 >>> 31) - var t1slo4 = s[8] ^ lo - var t1shi4 = s[9] ^ hi - var t1slo9 = s[18] ^ lo - var t1shi9 = s[19] ^ hi - var t1slo14 = s[28] ^ lo - var t1shi14 = s[29] ^ hi - var t1slo19 = s[38] ^ lo - var t1shi19 = s[39] ^ hi - var t1slo24 = s[48] ^ lo - var t1shi24 = s[49] ^ hi - - // rho & pi - var t2slo0 = t1slo0 - var t2shi0 = t1shi0 - var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28) - var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28) - var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29) - var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29) - var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23) - var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23) - var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14) - var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14) - var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31) - var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31) - var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20) - var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20) - var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22) - var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22) - var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19) - var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19) - var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30) - var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30) - var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2) - var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2) - var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26) - var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26) - var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21) - var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21) - var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17) - var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17) - var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3) - var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3) - var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4) - var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4) - var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9) - var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9) - var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7) - var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7) - var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11) - var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11) - var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8) - var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8) - var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5) - var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5) - var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12) - var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12) - var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25) - var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25) - var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24) - var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24) - var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18) - var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18) - - // chi - s[0] = t2slo0 ^ (~t2slo1 & t2slo2) - s[1] = t2shi0 ^ (~t2shi1 & t2shi2) - s[10] = t2slo5 ^ (~t2slo6 & t2slo7) - s[11] = t2shi5 ^ (~t2shi6 & t2shi7) - s[20] = t2slo10 ^ (~t2slo11 & t2slo12) - s[21] = t2shi10 ^ (~t2shi11 & t2shi12) - s[30] = t2slo15 ^ (~t2slo16 & t2slo17) - s[31] = t2shi15 ^ (~t2shi16 & t2shi17) - s[40] = t2slo20 ^ (~t2slo21 & t2slo22) - s[41] = t2shi20 ^ (~t2shi21 & t2shi22) - s[2] = t2slo1 ^ (~t2slo2 & t2slo3) - s[3] = t2shi1 ^ (~t2shi2 & t2shi3) - s[12] = t2slo6 ^ (~t2slo7 & t2slo8) - s[13] = t2shi6 ^ (~t2shi7 & t2shi8) - s[22] = t2slo11 ^ (~t2slo12 & t2slo13) - s[23] = t2shi11 ^ (~t2shi12 & t2shi13) - s[32] = t2slo16 ^ (~t2slo17 & t2slo18) - s[33] = t2shi16 ^ (~t2shi17 & t2shi18) - s[42] = t2slo21 ^ (~t2slo22 & t2slo23) - s[43] = t2shi21 ^ (~t2shi22 & t2shi23) - s[4] = t2slo2 ^ (~t2slo3 & t2slo4) - s[5] = t2shi2 ^ (~t2shi3 & t2shi4) - s[14] = t2slo7 ^ (~t2slo8 & t2slo9) - s[15] = t2shi7 ^ (~t2shi8 & t2shi9) - s[24] = t2slo12 ^ (~t2slo13 & t2slo14) - s[25] = t2shi12 ^ (~t2shi13 & t2shi14) - s[34] = t2slo17 ^ (~t2slo18 & t2slo19) - s[35] = t2shi17 ^ (~t2shi18 & t2shi19) - s[44] = t2slo22 ^ (~t2slo23 & t2slo24) - s[45] = t2shi22 ^ (~t2shi23 & t2shi24) - s[6] = t2slo3 ^ (~t2slo4 & t2slo0) - s[7] = t2shi3 ^ (~t2shi4 & t2shi0) - s[16] = t2slo8 ^ (~t2slo9 & t2slo5) - s[17] = t2shi8 ^ (~t2shi9 & t2shi5) - s[26] = t2slo13 ^ (~t2slo14 & t2slo10) - s[27] = t2shi13 ^ (~t2shi14 & t2shi10) - s[36] = t2slo18 ^ (~t2slo19 & t2slo15) - s[37] = t2shi18 ^ (~t2shi19 & t2shi15) - s[46] = t2slo23 ^ (~t2slo24 & t2slo20) - s[47] = t2shi23 ^ (~t2shi24 & t2shi20) - s[8] = t2slo4 ^ (~t2slo0 & t2slo1) - s[9] = t2shi4 ^ (~t2shi0 & t2shi1) - s[18] = t2slo9 ^ (~t2slo5 & t2slo6) - s[19] = t2shi9 ^ (~t2shi5 & t2shi6) - s[28] = t2slo14 ^ (~t2slo10 & t2slo11) - s[29] = t2shi14 ^ (~t2shi10 & t2shi11) - s[38] = t2slo19 ^ (~t2slo15 & t2slo16) - s[39] = t2shi19 ^ (~t2shi15 & t2shi16) - s[48] = t2slo24 ^ (~t2slo20 & t2slo21) - s[49] = t2shi24 ^ (~t2shi20 & t2shi21) - - // iota - s[0] ^= P1600_ROUND_CONSTANTS[round * 2] - s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1] - } -} - -},{}],105:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var keccakState = require('./keccak-state-unroll') - -function Keccak () { - // much faster than `new Array(50)` - this.state = [ - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0 - ] - - this.blockSize = null - this.count = 0 - this.squeezing = false -} - -Keccak.prototype.initialize = function (rate, capacity) { - for (var i = 0; i < 50; ++i) this.state[i] = 0 - this.blockSize = rate / 8 - this.count = 0 - this.squeezing = false -} - -Keccak.prototype.absorb = function (data) { - for (var i = 0; i < data.length; ++i) { - this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4)) - this.count += 1 - if (this.count === this.blockSize) { - keccakState.p1600(this.state) - this.count = 0 - } - } -} - -Keccak.prototype.absorbLastFewBits = function (bits) { - this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4)) - if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state) - this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4)) - keccakState.p1600(this.state) - this.count = 0 - this.squeezing = true -} - -Keccak.prototype.squeeze = function (length) { - if (!this.squeezing) this.absorbLastFewBits(0x01) - - var output = Buffer.alloc(length) - for (var i = 0; i < length; ++i) { - output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff - this.count += 1 - if (this.count === this.blockSize) { - keccakState.p1600(this.state) - this.count = 0 - } - } - - return output -} - -Keccak.prototype.copy = function (dest) { - for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i] - dest.blockSize = this.blockSize - dest.count = this.count - dest.squeezing = this.squeezing -} - -module.exports = Keccak - -},{"./keccak-state-unroll":104,"safe-buffer":117}],106:[function(require,module,exports){ -var bitcoin = require('bitcoinjs-lib'); -const Keychain = require('./keychain'); -var Buffer = require('safe-buffer').Buffer - -var EMPTY_SCRIPT = Buffer.allocUnsafe(0) - -var scriptTypes = { - MULTISIG: 'multisig', - NONSTANDARD: 'nonstandard', - NULLDATA: 'nulldata', - P2PK: 'pubkey', - P2PKH: 'pubkeyhash', - P2SH: 'scripthash', - P2WPKH: 'witnesspubkeyhash', - P2WSH: 'witnessscripthash', - WITNESS_COMMITMENT: 'witnesscommitment' -} - -function canSign (input) { - return input.prevOutScript !== undefined && - input.signScript !== undefined && - input.pubKeys !== undefined && - input.signatures !== undefined && - input.signatures.length === input.pubKeys.length && - input.pubKeys.length > 0 && - ( - input.witness === false || - (input.witness === true && input.value !== undefined) - ) -} - - -function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) { - // console.log('prepareInput input ', input, kpPubKey, redeemScript, witnessValue, witnessScript); - var expanded - var prevOutType - var prevOutScript - - var p2sh = false - var p2shType - var redeemScriptHash - - var witness = false - var p2wsh = false - var witnessType - var witnessScriptHash - - var signType - var signScript - - if (redeemScript && witnessScript) { - redeemScriptHash = bitcoin.crypto.hash160(redeemScript) - witnessScriptHash = bitcoin.crypto.sha256(witnessScript) - checkP2SHInput(input, redeemScriptHash) - - if (!redeemScript.equals(bitcoin.templates.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script') - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bitcoin.script.toASM(redeemScript) + '"') - - prevOutType = bitcoin.templates.types.P2SH - prevOutScript = bitcoin.templates.scriptHash.output.encode(redeemScriptHash) - p2sh = witness = p2wsh = true - p2shType = bitcoin.templates.types.P2WSH - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (redeemScript) { - redeemScriptHash = bitcoin.crypto.hash160(redeemScript) - checkP2SHInput(input, redeemScriptHash) - - expanded = expandOutput(redeemScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bitcoin.script.toASM(redeemScript) + '"') - - prevOutType = bitcoin.templates.types.P2SH - prevOutScript = bitcoin.templates.scriptHash.output.encode(redeemScriptHash) - p2sh = true - signType = p2shType = expanded.scriptType - signScript = redeemScript - witness = signType === bitcoin.templates.types.P2WPKH - } else if (witnessScript) { - witnessScriptHash = bitcoin.crypto.sha256(witnessScript) // first sha256 - checkP2WSHInput(input, witnessScriptHash) - - expanded = expandOutput(witnessScript, undefined, kpPubKey) - if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bitcoin.script.toASM(redeemScript) + '"') - - prevOutType = bitcoin.templates.types.P2WSH - prevOutScript = bitcoin.templates.witnessScriptHash.output.encode(witnessScriptHash) - witness = p2wsh = true - signType = witnessType = expanded.scriptType - signScript = witnessScript - } else if (input.prevOutType) { - - // embedded scripts are not possible without a redeemScript - if (input.prevOutType === scriptTypes.P2SH || - input.prevOutType === scriptTypes.P2WSH) { - throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript') - } - - prevOutType = input.prevOutType - prevOutScript = input.prevOutScript - expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey) - if (!expanded.pubKeys) return - - witness = (input.prevOutType === scriptTypes.P2WPKH) - signType = prevOutType - signScript = prevOutScript - } else { - // console.log('kpPubKey ', kpPubKey); - // prevOutScript = bitcoin.templates.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey)) - prevOutScript = bitcoin.script.compile([ - bitcoin.opcodes.OP_DUP, - bitcoin.opcodes.OP_HASH160, - bitcoin.crypto.hash160(kpPubKey), - bitcoin.opcodes.OP_EQUALVERIFY, - bitcoin.opcodes.OP_CHECKSIG - ]) - - // console.log('else prevOutScript> ', Buffer.from(prevOutScript).toString('hex')) - expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey) - - prevOutType = scriptTypes.P2PKH - witness = false - signType = prevOutType - signScript = prevOutScript - } - - if (signType === scriptTypes.P2WPKH) { - // signScript = bitcoin.templates.pubKeyHash.output.encode(bitcoin.templates.witnessPubKeyHash.output.decode(signScript)) - - signScript = bitcoin.script.compile([ - bitcoin.opcodes.OP_DUP, - bitcoin.opcodes.OP_HASH160, - signScript.slice(2), - bitcoin.opcodes.OP_EQUALVERIFY, - bitcoin.opcodes.OP_CHECKSIG - ]) - - } - - if (p2sh) { - input.redeemScript = redeemScript - input.redeemScriptType = p2shType - } - - if (p2wsh) { - input.witnessScript = witnessScript - input.witnessScriptType = witnessType - } - - input.pubKeys = expanded.pubKeys - input.signatures = expanded.signatures - input.signScript = signScript - input.signType = signType - input.prevOutScript = prevOutScript - input.prevOutType = prevOutType - input.witness = witness - - // console.log('prepareInput ', input); -} - -function expandOutput (script, scriptType, ourPubKey) { - - - var scriptChunks = bitcoin.script.decompile(script) - if (!scriptType) { - scriptType = bitcoin.templates.classifyOutput(script) - } - - var pubKeys = [] - - switch (scriptType) { - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2PKH: - if (!ourPubKey) break - - var pkh1 = scriptChunks[2] - var pkh2 = bitcoin.crypto.hash160(ourPubKey) - if (pkh1.equals(pkh2)) pubKeys = [ourPubKey] - break - - // does our hash160(pubKey) match the output scripts? - case scriptTypes.P2WPKH: - if (!ourPubKey) break - - var wpkh1 = scriptChunks[1] - var wpkh2 = bitcoin.crypto.hash160(ourPubKey) - if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey] - break - - case scriptTypes.P2PK: - pubKeys = scriptChunks.slice(0, 1) - break - - case scriptTypes.MULTISIG: - pubKeys = scriptChunks.slice(1, -2) - break - - default: return { scriptType: scriptType } - } - - return { - pubKeys: pubKeys, - scriptType: scriptType, - signatures: pubKeys.map(function () { return undefined }) - } -} - -bitcoin.TransactionBuilder.prototype.prepareTx = function (vin, kpPubKey, redeemScript, hashType, witnessValue, witnessScript) { - // transform - - kpPubKey = Buffer.from('03' + kpPubKey.slice(0, 64), 'hex'); - - // console.log("---- sign ------"); - - // TODO: remove keyPair.network matching in 4.0.0 - // if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network') - if (!this.inputs[vin]) throw new Error('No input at index: ' + vin) - hashType = hashType || bitcoin.Transaction.SIGHASH_ALL - - var input = this.inputs[vin] - - // console.log('--->>> input before --< ', input); - - // if redeemScript was previously provided, enforce consistency - if (input.redeemScript !== undefined && - redeemScript && - !input.redeemScript.equals(redeemScript)) { - throw new Error('Inconsistent redeemScript') - } - - // var kpPubKey = keyPair.publicKey || keyPair.getPublicKeyBuffer() - if (!canSign(input)) { - if (witnessValue !== undefined) { - if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue') - typeforce(types.Satoshi, witnessValue) - input.value = witnessValue - } - - if (!canSign(input)) prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript) // first sha256 and got signScript - if (!canSign(input)) throw Error(input.prevOutType + ' not supported') - } -} - - -bitcoin.TransactionBuilder.prototype.buildTxKeychain = async function (keyInstance, publicKey) { - - // this.tx.prepareTxKeychain(this.inputs, bitcoin.Transaction.SIGHASH_ALL); - var txTmp = this.tx.clone() - const hashType = bitcoin.Transaction.SIGHASH_ALL; - - this.inputs.forEach((input, inIndex) => { - const prevOutScript = input.signScript; - - // - var ourScript = bitcoin.script.compile(bitcoin.script.decompile(prevOutScript).filter(function (x) { - return x !== bitcoin.opcodes.OP_CODESEPARATOR - })) - - // console.log('bitcoin ourScript>', ourScript) - // console.log('prepareTxKeychain ', this) - - - // SIGHASH_NONE: ignore all outputs? (wildcard payee) - if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_NONE) { - txTmp.outs = [] - - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, i) { - if (i === inIndex) return - - input.sequence = 0 - }) - - // SIGHASH_SINGLE: ignore all outputs, except at the same index? - } else if ((hashType & 0x1f) === bitcoin.Transaction.SIGHASH_SINGLE) { - // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 - if (inIndex >= this.outs.length) return ONE - - // truncate outputs after - txTmp.outs.length = inIndex + 1 - - // "blank" outputs before - for (var i = 0; i < inIndex; i++) { - txTmp.outs[i] = BLANK_OUTPUT - } - - // ignore sequence numbers (except at inIndex) - txTmp.ins.forEach(function (input, y) { - if (y === inIndex) return - - input.sequence = 0 - }) - } - - // SIGHASH_ANYONECANPAY: ignore inputs entirely? - if (hashType & bitcoin.Transaction.SIGHASH_ANYONECANPAY) { - txTmp.ins = [txTmp.ins[inIndex]] - txTmp.ins[0].script = ourScript - - // SIGHASH_ALL: only ignore input scripts - } else { - // "blank" others input scripts - txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) - txTmp.ins[inIndex].script = ourScript - } - - }) - - var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) - buffer.writeInt32LE(hashType, buffer.length - 4) - txTmp.__toBuffer(buffer, 0, false) - - - - const bufferHex = Buffer.from(buffer).toString('hex'); - // console.log('in bufferHex', bufferHex) - const res = await keyInstance.signHex(bufferHex, publicKey, 'bitcoin'); - - await keyInstance.term(); - return res.result; -} - - -module.exports = bitcoin; - - -},{"./keychain":108,"bitcoinjs-lib":19,"safe-buffer":117}],107:[function(require,module,exports){ -const EthereumTx = require('ethereumjs-tx'); -const Keychain = require('./keychain'); -const bitcoin = require('./bitcoin'); -const pubToAddress = require('ethereumjs-util').pubToAddress; - -const rsv = (signature, chainId) => { - const ret = {}; - ret.r = `0x${signature.slice(0, 64)}`; - ret.s = `0x${signature.slice(64, 128)}`; - const recovery = parseInt(signature.slice(128, 130), 16); - let tmpV = recovery + 27; - if (chainId > 0) { - tmpV += chainId * 2 + 8; - } - let hexString = tmpV.toString(16); - if (hexString.length % 2) { - hexString = '0' + hexString; - } - ret.v = `0x${hexString}`; - return ret; -}; - -web3Override = (web3) => { - - const sign = async(data, publicKey) => { - const keychain = await Keychain.create(); - const prefix = "\x19Ethereum Signed Message:\n" + data.length; - const messageHash = web3.utils.sha3(prefix + data).substr(2); - - const result = await keychain.signHash(messageHash, publicKey); - const signature = result.result; - const ret = rsv(signature, 0); - const signatureAdapted = signature.slice(0, -2) + ret.v.slice(2); // replace the last two chars with v to get the same result as web3 returns - return { - message: data, - messageHash: '0x' + messageHash, - v: ret.v, - r: ret.r, - s: ret.s, - signature: '0x' + signatureAdapted - }; - }; - - const signTransaction = async (txParams, publicKey) => { - if (!txParams.chainId) { - txParams.chainId = await web3.eth.net.getId(); - } - if (!txParams.nonce) { - const address = '0x' + pubToAddress('0x' + publicKey).toString('hex'); - txParams.nonce = await web3.eth.getTransactionCount(address); - } - if (!txParams.gasPrice) { - txParams.gasPrice = await web3.eth.getGasPrice(); - } - txParams.value = Number(txParams.value); - txParams.gasPrice = Number(txParams.gasPrice); - - const keychain = await Keychain.create(); - - const buildTxSinature = async (txParams) => { - const rsv = {r: '0x00', s: '0x00', v: txParams.chainId}; - const tx = Object.assign({}, txParams, rsv); // {...txParams, ...rsv}; - const ethTx = new EthereumTx(tx); - const buffer = ethTx.serialize(); - const rawTransaction = buffer.toString('hex'); - const messageHash = ethTx.hash().toString('hex'); - return { hex: rawTransaction, messageHash } ; - }; - - const buildRawTransaction = async (txParams) => { - const tx = new EthereumTx(txParams); - const buffer = tx.serialize(); - return buffer.toString('hex'); - }; - - const result = await buildTxSinature(txParams); - const rawHex = result.hex; - const messageHash = '0x' + result.messageHash; - const data = await keychain.signHex(rawHex, publicKey, 'ethereum'); - const ret = rsv(data.result, txParams.chainId); - let rawParams = Object.assign({}, txParams, ret); - - const raw = await buildRawTransaction(rawParams); - const rawTransaction = `0x${raw}`; - - return { - messageHash, - v: ret.v, - r: ret.r, - s: ret.s, - rawTransaction - }; - }; - - return { sign, signTransaction }; -}; - - -module.exports = { web3Override, bitcoin, Keychain }; - -},{"./bitcoin":106,"./keychain":108,"ethereumjs-tx":80,"ethereumjs-util":82}],108:[function(require,module,exports){ -const W3CWebSocket = require('websocket').w3cwebsocket; -const WebSocketAsPromised = require('websocket-as-promised'); - -class Keychain { - constructor() { - this.wsp = new WebSocketAsPromised('ws://localhost:16384/', { - createWebSocket: url => new W3CWebSocket(url) - }); - this.wsp.onMessage.addListener((response) => { - const call = this.queue.shift(); - call(JSON.parse(response)); - }); - this.queue = []; - } - - async initialize() { - await this.wsp.open(); - } - - async term() { - await this.wsp.close(); - } - - static async create() { - const keychainInstance = new Keychain(); - await keychainInstance.initialize(); - return keychainInstance; - } - - method(request) { - return new Promise((resolve, reject) => { - this.queue.push(resolve); - this.wsp.send(JSON.stringify(request)); - }); - }; - - signHex(data, publicKey, blockchainType) { - const params = { - transaction: data, - blockchain_type: blockchainType, - public_key: publicKey - }; - return this.method({ - command: 'sign_hex', - params - }); - } - - signHash(hash, publicKey) { - const params = { - hash, - public_key: publicKey - }; - return this.method({ - command: 'sign_hash', - params - }); - } - - selectKey() { - return this.method({ command: 'select_key' }); - } - -} - -module.exports = Keychain; - -},{"websocket":139,"websocket-as-promised":138}],109:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var HashBase = require('hash-base') -var Buffer = require('safe-buffer').Buffer - -var ARRAY16 = new Array(16) - -function MD5 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 -} - -inherits(MD5, HashBase) - -MD5.prototype._update = function () { - var M = ARRAY16 - for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) - - var a = this._a - var b = this._b - var c = this._c - var d = this._d - - a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) - d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) - c = fnF(c, d, a, b, M[2], 0x242070db, 17) - b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) - a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) - d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) - c = fnF(c, d, a, b, M[6], 0xa8304613, 17) - b = fnF(b, c, d, a, M[7], 0xfd469501, 22) - a = fnF(a, b, c, d, M[8], 0x698098d8, 7) - d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) - c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) - b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) - a = fnF(a, b, c, d, M[12], 0x6b901122, 7) - d = fnF(d, a, b, c, M[13], 0xfd987193, 12) - c = fnF(c, d, a, b, M[14], 0xa679438e, 17) - b = fnF(b, c, d, a, M[15], 0x49b40821, 22) - - a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) - d = fnG(d, a, b, c, M[6], 0xc040b340, 9) - c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) - b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) - a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) - d = fnG(d, a, b, c, M[10], 0x02441453, 9) - c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) - b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) - a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) - d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) - c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) - b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) - a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) - d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) - c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) - b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) - - a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) - d = fnH(d, a, b, c, M[8], 0x8771f681, 11) - c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) - b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) - a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) - d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) - c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) - b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) - a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) - d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) - c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) - b = fnH(b, c, d, a, M[6], 0x04881d05, 23) - a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) - d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) - c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) - b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) - - a = fnI(a, b, c, d, M[0], 0xf4292244, 6) - d = fnI(d, a, b, c, M[7], 0x432aff97, 10) - c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) - b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) - a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) - d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) - c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) - b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) - a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) - d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) - c = fnI(c, d, a, b, M[6], 0xa3014314, 15) - b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) - a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) - d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) - c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) - b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) - - this._a = (this._a + a) | 0 - this._b = (this._b + b) | 0 - this._c = (this._c + c) | 0 - this._d = (this._d + d) | 0 -} - -MD5.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.allocUnsafe(16) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fnF (a, b, c, d, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 -} - -function fnG (a, b, c, d, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 -} - -function fnH (a, b, c, d, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 -} - -function fnI (a, b, c, d, m, k, s) { - return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 -} - -module.exports = MD5 - -},{"hash-base":84,"inherits":98,"safe-buffer":117}],110:[function(require,module,exports){ -(function (Buffer){ -// constant-space merkle root calculation algorithm -module.exports = function fastRoot (values, digestFn) { - if (!Array.isArray(values)) throw TypeError('Expected values Array') - if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') - - var length = values.length - var results = values.concat() - - while (length > 1) { - var j = 0 - - for (var i = 0; i < length; i += 2, ++j) { - var left = results[i] - var right = i + 1 === length ? left : results[i + 1] - var data = Buffer.concat([left, right]) - - results[j] = digestFn(data) - } - - length = j - } - - return results[0] -} - -}).call(this,require("buffer").Buffer) -},{"buffer":149}],111:[function(require,module,exports){ -module.exports = assert; - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -assert.equal = function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -}; - -},{}],112:[function(require,module,exports){ -'use strict'; - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg !== 'string') { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - return res; - } - if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } else { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } - return res; -} -utils.toArray = toArray; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; - -},{}],113:[function(require,module,exports){ -var OPS = require('bitcoin-ops') - -function encodingLength (i) { - return i < OPS.OP_PUSHDATA1 ? 1 - : i <= 0xff ? 2 - : i <= 0xffff ? 3 - : 5 -} - -function encode (buffer, number, offset) { - var size = encodingLength(number) - - // ~6 bit - if (size === 1) { - buffer.writeUInt8(number, offset) - - // 8 bit - } else if (size === 2) { - buffer.writeUInt8(OPS.OP_PUSHDATA1, offset) - buffer.writeUInt8(number, offset + 1) - - // 16 bit - } else if (size === 3) { - buffer.writeUInt8(OPS.OP_PUSHDATA2, offset) - buffer.writeUInt16LE(number, offset + 1) - - // 32 bit - } else { - buffer.writeUInt8(OPS.OP_PUSHDATA4, offset) - buffer.writeUInt32LE(number, offset + 1) - } - - return size -} - -function decode (buffer, offset) { - var opcode = buffer.readUInt8(offset) - var number, size - - // ~6 bit - if (opcode < OPS.OP_PUSHDATA1) { - number = opcode - size = 1 - - // 8 bit - } else if (opcode === OPS.OP_PUSHDATA1) { - if (offset + 2 > buffer.length) return null - number = buffer.readUInt8(offset + 1) - size = 2 - - // 16 bit - } else if (opcode === OPS.OP_PUSHDATA2) { - if (offset + 3 > buffer.length) return null - number = buffer.readUInt16LE(offset + 1) - size = 3 - - // 32 bit - } else { - if (offset + 5 > buffer.length) return null - if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode') - - number = buffer.readUInt32LE(offset + 1) - size = 5 - } - - return { - opcode: opcode, - number: number, - size: size - } -} - -module.exports = { - encodingLength: encodingLength, - encode: encode, - decode: decode -} - -},{"bitcoin-ops":9}],114:[function(require,module,exports){ -(function (process,global){ -'use strict' - -// limit of Crypto.getRandomValues() -// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues -var MAX_BYTES = 65536 - -// Node supports requesting up to this number of bytes -// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48 -var MAX_UINT32 = 4294967295 - -function oldBrowser () { - throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11') -} - -var Buffer = require('safe-buffer').Buffer -var crypto = global.crypto || global.msCrypto - -if (crypto && crypto.getRandomValues) { - module.exports = randomBytes -} else { - module.exports = oldBrowser -} - -function randomBytes (size, cb) { - // phantomjs needs to throw - if (size > MAX_UINT32) throw new RangeError('requested too many random bytes') - - var bytes = Buffer.allocUnsafe(size) - - if (size > 0) { // getRandomValues fails on IE if size == 0 - if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues - // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues - for (var generated = 0; generated < size; generated += MAX_BYTES) { - // buffer.slice automatically checks if the end is past the end of - // the buffer so we don't have to here - crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES)) - } - } else { - crypto.getRandomValues(bytes) - } - } - - if (typeof cb === 'function') { - return process.nextTick(function () { - cb(null, bytes) - }) - } - - return bytes -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":157,"safe-buffer":117}],115:[function(require,module,exports){ -'use strict' -var Buffer = require('buffer').Buffer -var inherits = require('inherits') -var HashBase = require('hash-base') - -var ARRAY16 = new Array(16) - -var zl = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -] - -var zr = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -] - -var sl = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -] - -var sr = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -] - -var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e] -var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000] - -function RIPEMD160 () { - HashBase.call(this, 64) - - // state - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 -} - -inherits(RIPEMD160, HashBase) - -RIPEMD160.prototype._update = function () { - var words = ARRAY16 - for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4) - - var al = this._a | 0 - var bl = this._b | 0 - var cl = this._c | 0 - var dl = this._d | 0 - var el = this._e | 0 - - var ar = this._a | 0 - var br = this._b | 0 - var cr = this._c | 0 - var dr = this._d | 0 - var er = this._e | 0 - - // computation - for (var i = 0; i < 80; i += 1) { - var tl - var tr - if (i < 16) { - tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i]) - tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i]) - } else if (i < 32) { - tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i]) - tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i]) - } else if (i < 48) { - tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i]) - tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i]) - } else if (i < 64) { - tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i]) - tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i]) - } else { // if (i<80) { - tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i]) - tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i]) - } - - al = el - el = dl - dl = rotl(cl, 10) - cl = bl - bl = tl - - ar = er - er = dr - dr = rotl(cr, 10) - cr = br - br = tr - } - - // update state - var t = (this._b + cl + dr) | 0 - this._b = (this._c + dl + er) | 0 - this._c = (this._d + el + ar) | 0 - this._d = (this._e + al + br) | 0 - this._e = (this._a + bl + cr) | 0 - this._a = t -} - -RIPEMD160.prototype._digest = function () { - // create padding and handle blocks - this._block[this._blockOffset++] = 0x80 - if (this._blockOffset > 56) { - this._block.fill(0, this._blockOffset, 64) - this._update() - this._blockOffset = 0 - } - - this._block.fill(0, this._blockOffset, 56) - this._block.writeUInt32LE(this._length[0], 56) - this._block.writeUInt32LE(this._length[1], 60) - this._update() - - // produce result - var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20) - buffer.writeInt32LE(this._a, 0) - buffer.writeInt32LE(this._b, 4) - buffer.writeInt32LE(this._c, 8) - buffer.writeInt32LE(this._d, 12) - buffer.writeInt32LE(this._e, 16) - return buffer -} - -function rotl (x, n) { - return (x << n) | (x >>> (32 - n)) -} - -function fn1 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn2 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 -} - -function fn3 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 -} - -function fn4 (a, b, c, d, e, m, k, s) { - return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 -} - -function fn5 (a, b, c, d, e, m, k, s) { - return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 -} - -module.exports = RIPEMD160 - -},{"buffer":149,"hash-base":84,"inherits":98}],116:[function(require,module,exports){ -(function (Buffer){ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -var BN = require("bn.js"); -/** - * RLP Encoding based on: https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP - * This function takes in a data, convert it to buffer if not, and a length for recursion - * @param input - will be converted to buffer - * @returns returns buffer of encoded data - **/ -function encode(input) { - if (input instanceof Array) { - var output = []; - for (var i = 0; i < input.length; i++) { - output.push(encode(input[i])); - } - var buf = Buffer.concat(output); - return Buffer.concat([encodeLength(buf.length, 192), buf]); - } - else { - var inputBuf = toBuffer(input); - return inputBuf.length === 1 && inputBuf[0] < 128 - ? inputBuf - : Buffer.concat([encodeLength(inputBuf.length, 128), inputBuf]); - } -} -exports.encode = encode; -/** - * Parse integers. Check if there is no leading zeros - * @param v The value to parse - * @param base The base to parse the integer into - */ -function safeParseInt(v, base) { - if (v.slice(0, 2) === '00') { - throw new Error('invalid RLP: extra zeros'); - } - return parseInt(v, base); -} -function encodeLength(len, offset) { - if (len < 56) { - return Buffer.from([len + offset]); - } - else { - var hexLength = intToHex(len); - var lLength = hexLength.length / 2; - var firstByte = intToHex(offset + 55 + lLength); - return Buffer.from(firstByte + hexLength, 'hex'); - } -} -function decode(input, stream) { - if (stream === void 0) { stream = false; } - if (!input || input.length === 0) { - return Buffer.from([]); - } - var inputBuffer = toBuffer(input); - var decoded = _decode(inputBuffer); - if (stream) { - return decoded; - } - if (decoded.remainder.length !== 0) { - throw new Error('invalid remainder'); - } - return decoded.data; -} -exports.decode = decode; -/** - * Get the length of the RLP input - * @param input - * @returns The length of the input or an empty Buffer if no input - */ -function getLength(input) { - if (!input || input.length === 0) { - return Buffer.from([]); - } - var inputBuffer = toBuffer(input); - var firstByte = inputBuffer[0]; - if (firstByte <= 0x7f) { - return inputBuffer.length; - } - else if (firstByte <= 0xb7) { - return firstByte - 0x7f; - } - else if (firstByte <= 0xbf) { - return firstByte - 0xb6; - } - else if (firstByte <= 0xf7) { - // a list between 0-55 bytes long - return firstByte - 0xbf; - } - else { - // a list over 55 bytes long - var llength = firstByte - 0xf6; - var length = safeParseInt(inputBuffer.slice(1, llength).toString('hex'), 16); - return llength + length; - } -} -exports.getLength = getLength; -/** Decode an input with RLP */ -function _decode(input) { - var length, llength, data, innerRemainder, d; - var decoded = []; - var firstByte = input[0]; - if (firstByte <= 0x7f) { - // a single byte whose value is in the [0x00, 0x7f] range, that byte is its own RLP encoding. - return { - data: input.slice(0, 1), - remainder: input.slice(1), - }; - } - else if (firstByte <= 0xb7) { - // string is 0-55 bytes long. A single byte with value 0x80 plus the length of the string followed by the string - // The range of the first byte is [0x80, 0xb7] - length = firstByte - 0x7f; - // set 0x80 null to 0 - if (firstByte === 0x80) { - data = Buffer.from([]); - } - else { - data = input.slice(1, length); - } - if (length === 2 && data[0] < 0x80) { - throw new Error('invalid rlp encoding: byte must be less 0x80'); - } - return { - data: data, - remainder: input.slice(length), - }; - } - else if (firstByte <= 0xbf) { - llength = firstByte - 0xb6; - length = safeParseInt(input.slice(1, llength).toString('hex'), 16); - data = input.slice(llength, length + llength); - if (data.length < length) { - throw new Error('invalid RLP'); - } - return { - data: data, - remainder: input.slice(length + llength), - }; - } - else if (firstByte <= 0xf7) { - // a list between 0-55 bytes long - length = firstByte - 0xbf; - innerRemainder = input.slice(1, length); - while (innerRemainder.length) { - d = _decode(innerRemainder); - decoded.push(d.data); - innerRemainder = d.remainder; - } - return { - data: decoded, - remainder: input.slice(length), - }; - } - else { - // a list over 55 bytes long - llength = firstByte - 0xf6; - length = safeParseInt(input.slice(1, llength).toString('hex'), 16); - var totalLength = llength + length; - if (totalLength > input.length) { - throw new Error('invalid rlp: total length is larger than the data'); - } - innerRemainder = input.slice(llength, totalLength); - if (innerRemainder.length === 0) { - throw new Error('invalid rlp, List has a invalid length'); - } - while (innerRemainder.length) { - d = _decode(innerRemainder); - decoded.push(d.data); - innerRemainder = d.remainder; - } - return { - data: decoded, - remainder: input.slice(totalLength), - }; - } -} -/** Check if a string is prefixed by 0x */ -function isHexPrefixed(str) { - return str.slice(0, 2) === '0x'; -} -/** Removes 0x from a given String */ -function stripHexPrefix(str) { - if (typeof str !== 'string') { - return str; - } - return isHexPrefixed(str) ? str.slice(2) : str; -} -/** Transform an integer into its hexadecimal value */ -function intToHex(integer) { - var hex = integer.toString(16); - return hex.length % 2 ? "0" + hex : hex; -} -/** Pad a string to be even */ -function padToEven(a) { - return a.length % 2 ? "0" + a : a; -} -/** Transform an integer into a Buffer */ -function intToBuffer(integer) { - var hex = intToHex(integer); - return Buffer.from(hex, 'hex'); -} -/** Transform anything into a Buffer */ -function toBuffer(v) { - if (!Buffer.isBuffer(v)) { - if (typeof v === 'string') { - if (isHexPrefixed(v)) { - return Buffer.from(padToEven(stripHexPrefix(v)), 'hex'); - } - else { - return Buffer.from(v); - } - } - else if (typeof v === 'number') { - if (!v) { - return Buffer.from([]); - } - else { - return intToBuffer(v); - } - } - else if (v === null || v === undefined) { - return Buffer.from([]); - } - else if (v instanceof Uint8Array) { - return Buffer.from(v); - } - else if (BN.isBN(v)) { - // converts a BN to a Buffer - return Buffer.from(v.toArray()); - } - else { - throw new Error('invalid type'); - } - } - return v; -} - -}).call(this,require("buffer").Buffer) -},{"bn.js":48,"buffer":149}],117:[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) -} - -// 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":149}],118:[function(require,module,exports){ -'use strict' -module.exports = require('./lib')(require('./lib/elliptic')) - -},{"./lib":122,"./lib/elliptic":121}],119:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var toString = Object.prototype.toString - -// TypeError -exports.isArray = function (value, message) { - if (!Array.isArray(value)) throw TypeError(message) -} - -exports.isBoolean = function (value, message) { - if (toString.call(value) !== '[object Boolean]') throw TypeError(message) -} - -exports.isBuffer = function (value, message) { - if (!Buffer.isBuffer(value)) throw TypeError(message) -} - -exports.isFunction = function (value, message) { - if (toString.call(value) !== '[object Function]') throw TypeError(message) -} - -exports.isNumber = function (value, message) { - if (toString.call(value) !== '[object Number]') throw TypeError(message) -} - -exports.isObject = function (value, message) { - if (toString.call(value) !== '[object Object]') throw TypeError(message) -} - -// RangeError -exports.isBufferLength = function (buffer, length, message) { - if (buffer.length !== length) throw RangeError(message) -} - -exports.isBufferLength2 = function (buffer, length1, length2, message) { - if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message) -} - -exports.isLengthGTZero = function (value, message) { - if (value.length === 0) throw RangeError(message) -} - -exports.isNumberInInterval = function (number, x, y, message) { - if (number <= x || number >= y) throw RangeError(message) -} - -}).call(this,{"isBuffer":require("../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) -},{"../../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":154}],120:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var bip66 = require('bip66') - -var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([ - // begin - 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20, - // private key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // middle - 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, - 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, - 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, - 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, - 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, - 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, - // public key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00 -]) - -var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ - // begin - 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, - // private key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - // middle - 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, - 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, - 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, - 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, - 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, - 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, - 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, - 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, - // public key - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00 -]) - -exports.privateKeyExport = function (privateKey, publicKey, compressed) { - var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED) - privateKey.copy(result, compressed ? 8 : 9) - publicKey.copy(result, compressed ? 181 : 214) - return result -} - -exports.privateKeyImport = function (privateKey) { - var length = privateKey.length - - // sequence header - var index = 0 - if (length < index + 1 || privateKey[index] !== 0x30) return - index += 1 - - // sequence length constructor - if (length < index + 1 || !(privateKey[index] & 0x80)) return - - var lenb = privateKey[index] & 0x7f - index += 1 - if (lenb < 1 || lenb > 2) return - if (length < index + lenb) return - - // sequence length - var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) - index += lenb - if (length < index + len) return - - // sequence element 0: version number (=1) - if (length < index + 3 || - privateKey[index] !== 0x02 || - privateKey[index + 1] !== 0x01 || - privateKey[index + 2] !== 0x01) { - return - } - index += 3 - - // sequence element 1: octet string, up to 32 bytes - if (length < index + 2 || - privateKey[index] !== 0x04 || - privateKey[index + 1] > 0x20 || - length < index + 2 + privateKey[index + 1]) { - return - } - - return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) -} - -exports.signatureExport = function (sigObj) { - var r = Buffer.concat([Buffer.from([0]), sigObj.r]) - for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR); - - var s = Buffer.concat([Buffer.from([0]), sigObj.s]) - for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); - - return bip66.encode(r.slice(posR), s.slice(posS)) -} - -exports.signatureImport = function (sig) { - var r = Buffer.alloc(32, 0) - var s = Buffer.alloc(32, 0) - - try { - var sigObj = bip66.decode(sig) - if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) - if (sigObj.r.length > 32) throw new Error('R length is too long') - if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) - if (sigObj.s.length > 32) throw new Error('S length is too long') - } catch (err) { - return - } - - sigObj.r.copy(r, 32 - sigObj.r.length) - sigObj.s.copy(s, 32 - sigObj.s.length) - - return { r: r, s: s } -} - -exports.signatureImportLax = function (sig) { - var r = Buffer.alloc(32, 0) - var s = Buffer.alloc(32, 0) - - var length = sig.length - var index = 0 - - // sequence tag byte - if (sig[index++] !== 0x30) return - - // sequence length byte - var lenbyte = sig[index++] - if (lenbyte & 0x80) { - index += lenbyte - 0x80 - if (index > length) return - } - - // sequence tag byte for r - if (sig[index++] !== 0x02) return - - // length for r - var rlen = sig[index++] - if (rlen & 0x80) { - lenbyte = rlen - 0x80 - if (index + lenbyte > length) return - for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); - for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] - } - if (rlen > length - index) return - var rindex = index - index += rlen - - // sequence tag byte for s - if (sig[index++] !== 0x02) return - - // length for s - var slen = sig[index++] - if (slen & 0x80) { - lenbyte = slen - 0x80 - if (index + lenbyte > length) return - for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); - for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] - } - if (slen > length - index) return - var sindex = index - index += slen - - // ignore leading zeros in r - for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); - // copy r value - if (rlen > 32) return - var rvalue = sig.slice(rindex, rindex + rlen) - rvalue.copy(r, 32 - rvalue.length) - - // ignore leading zeros in s - for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); - // copy s value - if (slen > 32) return - var svalue = sig.slice(sindex, sindex + slen) - svalue.copy(s, 32 - svalue.length) - - return { r: r, s: s } -} - -},{"bip66":8,"safe-buffer":117}],121:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer -var createHash = require('create-hash') -var BN = require('bn.js') -var EC = require('elliptic').ec - -var messages = require('../messages.json') - -var ec = new EC('secp256k1') -var ecparams = ec.curve - -function loadCompressedPublicKey (first, xBuffer) { - var x = new BN(xBuffer) - - // overflow - if (x.cmp(ecparams.p) >= 0) return null - x = x.toRed(ecparams.red) - - // compute corresponding Y - var y = x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt() - if ((first === 0x03) !== y.isOdd()) y = y.redNeg() - - return ec.keyPair({ pub: { x: x, y: y } }) -} - -function loadUncompressedPublicKey (first, xBuffer, yBuffer) { - var x = new BN(xBuffer) - var y = new BN(yBuffer) - - // overflow - if (x.cmp(ecparams.p) >= 0 || y.cmp(ecparams.p) >= 0) return null - - x = x.toRed(ecparams.red) - y = y.toRed(ecparams.red) - - // is odd flag - if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null - - // x*x*x + b = y*y - var x3 = x.redSqr().redIMul(x) - if (!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()) return null - - return ec.keyPair({ pub: { x: x, y: y } }) -} - -function loadPublicKey (publicKey) { - var first = publicKey[0] - switch (first) { - case 0x02: - case 0x03: - if (publicKey.length !== 33) return null - return loadCompressedPublicKey(first, publicKey.slice(1, 33)) - case 0x04: - case 0x06: - case 0x07: - if (publicKey.length !== 65) return null - return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65)) - default: - return null - } -} - -exports.privateKeyVerify = function (privateKey) { - var bn = new BN(privateKey) - return bn.cmp(ecparams.n) < 0 && !bn.isZero() -} - -exports.privateKeyExport = function (privateKey, compressed) { - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL) - - return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) -} - -exports.privateKeyNegate = function (privateKey) { - var bn = new BN(privateKey) - return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyModInverse = function (privateKey) { - var bn = new BN(privateKey) - if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID) - - return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyTweakAdd = function (privateKey, tweak) { - var bn = new BN(tweak) - if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - bn.iadd(new BN(privateKey)) - if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n) - if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) - - return bn.toArrayLike(Buffer, 'be', 32) -} - -exports.privateKeyTweakMul = function (privateKey, tweak) { - var bn = new BN(tweak) - if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL) - - bn.imul(new BN(privateKey)) - if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n) - - return bn.toArrayLike(Buffer, 'be', 32) -} - -exports.publicKeyCreate = function (privateKey, compressed) { - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL) - - return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) -} - -exports.publicKeyConvert = function (publicKey, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - return Buffer.from(pair.getPublic(compressed, true)) -} - -exports.publicKeyVerify = function (publicKey) { - return loadPublicKey(publicKey) !== null -} - -exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = new BN(tweak) - if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - var point = ecparams.g.mul(tweak).add(pair.pub) - if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) - - return Buffer.from(point.encode(true, compressed)) -} - -exports.publicKeyTweakMul = function (publicKey, tweak, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - tweak = new BN(tweak) - if (tweak.cmp(ecparams.n) >= 0 || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL) - - return Buffer.from(pair.pub.mul(tweak).encode(true, compressed)) -} - -exports.publicKeyCombine = function (publicKeys, compressed) { - var pairs = new Array(publicKeys.length) - for (var i = 0; i < publicKeys.length; ++i) { - pairs[i] = loadPublicKey(publicKeys[i]) - if (pairs[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - } - - var point = pairs[0].pub - for (var j = 1; j < pairs.length; ++j) point = point.add(pairs[j].pub) - if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL) - - return Buffer.from(point.encode(true, compressed)) -} - -exports.signatureNormalize = function (signature) { - var r = new BN(signature.slice(0, 32)) - var s = new BN(signature.slice(32, 64)) - if (r.cmp(ecparams.n) >= 0 || s.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - var result = Buffer.from(signature) - if (s.cmp(ec.nh) === 1) ecparams.n.sub(s).toArrayLike(Buffer, 'be', 32).copy(result, 32) - - return result -} - -exports.signatureExport = function (signature) { - var r = signature.slice(0, 32) - var s = signature.slice(32, 64) - if (new BN(r).cmp(ecparams.n) >= 0 || new BN(s).cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - return { r: r, s: s } -} - -exports.signatureImport = function (sigObj) { - var r = new BN(sigObj.r) - if (r.cmp(ecparams.n) >= 0) r = new BN(0) - - var s = new BN(sigObj.s) - if (s.cmp(ecparams.n) >= 0) s = new BN(0) - - return Buffer.concat([ - r.toArrayLike(Buffer, 'be', 32), - s.toArrayLike(Buffer, 'be', 32) - ]) -} - -exports.sign = function (message, privateKey, noncefn, data) { - if (typeof noncefn === 'function') { - var getNonce = noncefn - noncefn = function (counter) { - var nonce = getNonce(message, privateKey, null, data, counter) - if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL) - - return new BN(nonce) - } - } - - var d = new BN(privateKey) - if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL) - - var result = ec.sign(message, privateKey, { canonical: true, k: noncefn, pers: data }) - return { - signature: Buffer.concat([ - result.r.toArrayLike(Buffer, 'be', 32), - result.s.toArrayLike(Buffer, 'be', 32) - ]), - recovery: result.recoveryParam - } -} - -exports.verify = function (message, signature, publicKey) { - var sigObj = { r: signature.slice(0, 32), s: signature.slice(32, 64) } - - var sigr = new BN(sigObj.r) - var sigs = new BN(sigObj.s) - if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false - - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - return ec.verify(message, sigObj, { x: pair.pub.x, y: pair.pub.y }) -} - -exports.recover = function (message, signature, recovery, compressed) { - var sigObj = { r: signature.slice(0, 32), s: signature.slice(32, 64) } - - var sigr = new BN(sigObj.r) - var sigs = new BN(sigObj.s) - if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) - - try { - if (sigr.isZero() || sigs.isZero()) throw new Error() - - var point = ec.recoverPubKey(message, sigObj, recovery) - return Buffer.from(point.encode(true, compressed)) - } catch (err) { - throw new Error(messages.ECDSA_RECOVER_FAIL) - } -} - -exports.ecdh = function (publicKey, privateKey) { - var shared = exports.ecdhUnsafe(publicKey, privateKey, true) - return createHash('sha256').update(shared).digest() -} - -exports.ecdhUnsafe = function (publicKey, privateKey, compressed) { - var pair = loadPublicKey(publicKey) - if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) - - var scalar = new BN(privateKey) - if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL) - - return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) -} - -},{"../messages.json":123,"bn.js":48,"create-hash":54,"elliptic":63,"safe-buffer":117}],122:[function(require,module,exports){ -'use strict' -var assert = require('./assert') -var der = require('./der') -var messages = require('./messages.json') - -function initCompressedValue (value, defaultValue) { - if (value === undefined) return defaultValue - - assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID) - return value -} - -module.exports = function (secp256k1) { - return { - privateKeyVerify: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey) - }, - - privateKeyExport: function (privateKey, compressed) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - var publicKey = secp256k1.privateKeyExport(privateKey, compressed) - - return der.privateKeyExport(privateKey, publicKey, compressed) - }, - - privateKeyImport: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - - privateKey = der.privateKeyImport(privateKey) - if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey - - throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL) - }, - - privateKeyNegate: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.privateKeyNegate(privateKey) - }, - - privateKeyModInverse: function (privateKey) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.privateKeyModInverse(privateKey) - }, - - privateKeyTweakAdd: function (privateKey, tweak) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - return secp256k1.privateKeyTweakAdd(privateKey, tweak) - }, - - privateKeyTweakMul: function (privateKey, tweak) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - return secp256k1.privateKeyTweakMul(privateKey, tweak) - }, - - publicKeyCreate: function (privateKey, compressed) { - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyCreate(privateKey, compressed) - }, - - publicKeyConvert: function (publicKey, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyConvert(publicKey, compressed) - }, - - publicKeyVerify: function (publicKey) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - return secp256k1.publicKeyVerify(publicKey) - }, - - publicKeyTweakAdd: function (publicKey, tweak, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed) - }, - - publicKeyTweakMul: function (publicKey, tweak, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) - assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed) - }, - - publicKeyCombine: function (publicKeys, compressed) { - assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID) - assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID) - for (var i = 0; i < publicKeys.length; ++i) { - assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - } - - compressed = initCompressedValue(compressed, true) - - return secp256k1.publicKeyCombine(publicKeys, compressed) - }, - - signatureNormalize: function (signature) { - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - return secp256k1.signatureNormalize(signature) - }, - - signatureExport: function (signature) { - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = secp256k1.signatureExport(signature) - return der.signatureExport(sigObj) - }, - - signatureImport: function (sig) { - assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = der.signatureImport(sig) - if (sigObj) return secp256k1.signatureImport(sigObj) - - throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) - }, - - signatureImportLax: function (sig) { - assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - var sigObj = der.signatureImportLax(sig) - if (sigObj) return secp256k1.signatureImport(sigObj) - - throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) - }, - - sign: function (message, privateKey, options) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - var data = null - var noncefn = null - if (options !== undefined) { - assert.isObject(options, messages.OPTIONS_TYPE_INVALID) - - if (options.data !== undefined) { - assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) - assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) - data = options.data - } - - if (options.noncefn !== undefined) { - assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) - noncefn = options.noncefn - } - } - - return secp256k1.sign(message, privateKey, noncefn, data) - }, - - verify: function (message, signature, publicKey) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - return secp256k1.verify(message, signature, publicKey) - }, - - recover: function (message, signature, recovery, compressed) { - assert.isBuffer(message, messages.MSG32_TYPE_INVALID) - assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) - - assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) - assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) - - assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) - assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.recover(message, signature, recovery, compressed) - }, - - ecdh: function (publicKey, privateKey) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - return secp256k1.ecdh(publicKey, privateKey) - }, - - ecdhUnsafe: function (publicKey, privateKey, compressed) { - assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) - assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) - - assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) - assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) - - compressed = initCompressedValue(compressed, true) - - return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) - } - } -} - -},{"./assert":119,"./der":120,"./messages.json":123}],123:[function(require,module,exports){ -module.exports={ - "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", - "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer", - "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid", - "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid", - "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid", - "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range", - "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format", - "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format", - "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array", - "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element", - "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer", - "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid", - "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid", - "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again", - "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid", - "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range", - "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid", - "ECDH_FAIL": "scalar was invalid (zero or overflow)", - "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer", - "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid", - "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature", - "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature", - "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format", - "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid", - "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature", - "MSG32_TYPE_INVALID": "message should be a Buffer", - "MSG32_LENGTH_INVALID": "message length is invalid", - "OPTIONS_TYPE_INVALID": "options should be an Object", - "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer", - "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid", - "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function", - "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number", - "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4", - "TWEAK_TYPE_INVALID": "tweak should be a Buffer", - "TWEAK_LENGTH_INVALID": "tweak length is invalid" -} - -},{}],124:[function(require,module,exports){ -var Buffer = require('safe-buffer').Buffer - -// prototype class for hash functions -function Hash (blockSize, finalSize) { - this._block = Buffer.alloc(blockSize) - this._finalSize = finalSize - this._blockSize = blockSize - this._len = 0 -} - -Hash.prototype.update = function (data, enc) { - if (typeof data === 'string') { - enc = enc || 'utf8' - data = Buffer.from(data, enc) - } - - var block = this._block - var blockSize = this._blockSize - var length = data.length - var accum = this._len - - for (var offset = 0; offset < length;) { - var assigned = accum % blockSize - var remainder = Math.min(length - offset, blockSize - assigned) - - for (var i = 0; i < remainder; i++) { - block[assigned + i] = data[offset + i] - } - - accum += remainder - offset += remainder - - if ((accum % blockSize) === 0) { - this._update(block) - } - } - - this._len += length - return this -} - -Hash.prototype.digest = function (enc) { - var rem = this._len % this._blockSize - - this._block[rem] = 0x80 - - // zero (rem + 1) trailing bits, where (rem + 1) is the smallest - // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize - this._block.fill(0, rem + 1) - - if (rem >= this._finalSize) { - this._update(this._block) - this._block.fill(0) - } - - var bits = this._len * 8 - - // uint32 - if (bits <= 0xffffffff) { - this._block.writeUInt32BE(bits, this._blockSize - 4) - - // uint64 - } else { - var lowBits = (bits & 0xffffffff) >>> 0 - var highBits = (bits - lowBits) / 0x100000000 - - this._block.writeUInt32BE(highBits, this._blockSize - 8) - this._block.writeUInt32BE(lowBits, this._blockSize - 4) - } - - this._update(this._block) - var hash = this._hash() - - return enc ? hash.toString(enc) : hash -} - -Hash.prototype._update = function () { - throw new Error('_update must be implemented by subclass') -} - -module.exports = Hash - -},{"safe-buffer":117}],125:[function(require,module,exports){ -var exports = module.exports = function SHA (algorithm) { - algorithm = algorithm.toLowerCase() - - var Algorithm = exports[algorithm] - if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') - - return new Algorithm() -} - -exports.sha = require('./sha') -exports.sha1 = require('./sha1') -exports.sha224 = require('./sha224') -exports.sha256 = require('./sha256') -exports.sha384 = require('./sha384') -exports.sha512 = require('./sha512') - -},{"./sha":126,"./sha1":127,"./sha224":128,"./sha256":129,"./sha384":130,"./sha512":131}],126:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined - * in FIPS PUB 180-1 - * This source code is derived from sha1.js of the same repository. - * The difference between SHA-0 and SHA-1 is just a bitwise rotate left - * operation was added. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha, Hash) - -Sha.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha - -},{"./hash":124,"inherits":98,"safe-buffer":117}],127:[function(require,module,exports){ -/* - * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined - * in FIPS PUB 180-1 - * Version 2.1a Copyright Paul Johnston 2000 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for details. - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 -] - -var W = new Array(80) - -function Sha1 () { - this.init() - this._w = W - - Hash.call(this, 64, 56) -} - -inherits(Sha1, Hash) - -Sha1.prototype.init = function () { - this._a = 0x67452301 - this._b = 0xefcdab89 - this._c = 0x98badcfe - this._d = 0x10325476 - this._e = 0xc3d2e1f0 - - return this -} - -function rotl1 (num) { - return (num << 1) | (num >>> 31) -} - -function rotl5 (num) { - return (num << 5) | (num >>> 27) -} - -function rotl30 (num) { - return (num << 30) | (num >>> 2) -} - -function ft (s, b, c, d) { - if (s === 0) return (b & c) | ((~b) & d) - if (s === 2) return (b & c) | (b & d) | (c & d) - return b ^ c ^ d -} - -Sha1.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) - - for (var j = 0; j < 80; ++j) { - var s = ~~(j / 20) - var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 - - e = d - d = c - c = rotl30(b) - b = a - a = t - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 -} - -Sha1.prototype._hash = function () { - var H = Buffer.allocUnsafe(20) - - H.writeInt32BE(this._a | 0, 0) - H.writeInt32BE(this._b | 0, 4) - H.writeInt32BE(this._c | 0, 8) - H.writeInt32BE(this._d | 0, 12) - H.writeInt32BE(this._e | 0, 16) - - return H -} - -module.exports = Sha1 - -},{"./hash":124,"inherits":98,"safe-buffer":117}],128:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Sha256 = require('./sha256') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(64) - -function Sha224 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha224, Sha256) - -Sha224.prototype.init = function () { - this._a = 0xc1059ed8 - this._b = 0x367cd507 - this._c = 0x3070dd17 - this._d = 0xf70e5939 - this._e = 0xffc00b31 - this._f = 0x68581511 - this._g = 0x64f98fa7 - this._h = 0xbefa4fa4 - - return this -} - -Sha224.prototype._hash = function () { - var H = Buffer.allocUnsafe(28) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - - return H -} - -module.exports = Sha224 - -},{"./hash":124,"./sha256":129,"inherits":98,"safe-buffer":117}],129:[function(require,module,exports){ -/** - * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined - * in FIPS 180-2 - * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * - */ - -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, - 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, - 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, - 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, - 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, - 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, - 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, - 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, - 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, - 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, - 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, - 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, - 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, - 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, - 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, - 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 -] - -var W = new Array(64) - -function Sha256 () { - this.init() - - this._w = W // new Array(64) - - Hash.call(this, 64, 56) -} - -inherits(Sha256, Hash) - -Sha256.prototype.init = function () { - this._a = 0x6a09e667 - this._b = 0xbb67ae85 - this._c = 0x3c6ef372 - this._d = 0xa54ff53a - this._e = 0x510e527f - this._f = 0x9b05688c - this._g = 0x1f83d9ab - this._h = 0x5be0cd19 - - return this -} - -function ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x) { - return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) -} - -function sigma1 (x) { - return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) -} - -function gamma0 (x) { - return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) -} - -function gamma1 (x) { - return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) -} - -Sha256.prototype._update = function (M) { - var W = this._w - - var a = this._a | 0 - var b = this._b | 0 - var c = this._c | 0 - var d = this._d | 0 - var e = this._e | 0 - var f = this._f | 0 - var g = this._g | 0 - var h = this._h | 0 - - for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) - for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 - - for (var j = 0; j < 64; ++j) { - var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 - var T2 = (sigma0(a) + maj(a, b, c)) | 0 - - h = g - g = f - f = e - e = (d + T1) | 0 - d = c - c = b - b = a - a = (T1 + T2) | 0 - } - - this._a = (a + this._a) | 0 - this._b = (b + this._b) | 0 - this._c = (c + this._c) | 0 - this._d = (d + this._d) | 0 - this._e = (e + this._e) | 0 - this._f = (f + this._f) | 0 - this._g = (g + this._g) | 0 - this._h = (h + this._h) | 0 -} - -Sha256.prototype._hash = function () { - var H = Buffer.allocUnsafe(32) - - H.writeInt32BE(this._a, 0) - H.writeInt32BE(this._b, 4) - H.writeInt32BE(this._c, 8) - H.writeInt32BE(this._d, 12) - H.writeInt32BE(this._e, 16) - H.writeInt32BE(this._f, 20) - H.writeInt32BE(this._g, 24) - H.writeInt32BE(this._h, 28) - - return H -} - -module.exports = Sha256 - -},{"./hash":124,"inherits":98,"safe-buffer":117}],130:[function(require,module,exports){ -var inherits = require('inherits') -var SHA512 = require('./sha512') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var W = new Array(160) - -function Sha384 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha384, SHA512) - -Sha384.prototype.init = function () { - this._ah = 0xcbbb9d5d - this._bh = 0x629a292a - this._ch = 0x9159015a - this._dh = 0x152fecd8 - this._eh = 0x67332667 - this._fh = 0x8eb44a87 - this._gh = 0xdb0c2e0d - this._hh = 0x47b5481d - - this._al = 0xc1059ed8 - this._bl = 0x367cd507 - this._cl = 0x3070dd17 - this._dl = 0xf70e5939 - this._el = 0xffc00b31 - this._fl = 0x68581511 - this._gl = 0x64f98fa7 - this._hl = 0xbefa4fa4 - - return this -} - -Sha384.prototype._hash = function () { - var H = Buffer.allocUnsafe(48) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - - return H -} - -module.exports = Sha384 - -},{"./hash":124,"./sha512":131,"inherits":98,"safe-buffer":117}],131:[function(require,module,exports){ -var inherits = require('inherits') -var Hash = require('./hash') -var Buffer = require('safe-buffer').Buffer - -var K = [ - 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, - 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, - 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, - 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, - 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, - 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, - 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, - 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, - 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, - 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, - 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, - 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, - 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, - 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, - 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, - 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, - 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, - 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, - 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, - 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, - 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, - 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, - 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, - 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, - 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, - 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, - 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, - 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, - 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, - 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, - 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, - 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, - 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, - 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, - 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, - 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, - 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, - 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, - 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, - 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 -] - -var W = new Array(160) - -function Sha512 () { - this.init() - this._w = W - - Hash.call(this, 128, 112) -} - -inherits(Sha512, Hash) - -Sha512.prototype.init = function () { - this._ah = 0x6a09e667 - this._bh = 0xbb67ae85 - this._ch = 0x3c6ef372 - this._dh = 0xa54ff53a - this._eh = 0x510e527f - this._fh = 0x9b05688c - this._gh = 0x1f83d9ab - this._hh = 0x5be0cd19 - - this._al = 0xf3bcc908 - this._bl = 0x84caa73b - this._cl = 0xfe94f82b - this._dl = 0x5f1d36f1 - this._el = 0xade682d1 - this._fl = 0x2b3e6c1f - this._gl = 0xfb41bd6b - this._hl = 0x137e2179 - - return this -} - -function Ch (x, y, z) { - return z ^ (x & (y ^ z)) -} - -function maj (x, y, z) { - return (x & y) | (z & (x | y)) -} - -function sigma0 (x, xl) { - return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) -} - -function sigma1 (x, xl) { - return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) -} - -function Gamma0 (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) -} - -function Gamma0l (x, xl) { - return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) -} - -function Gamma1 (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) -} - -function Gamma1l (x, xl) { - return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) -} - -function getCarry (a, b) { - return (a >>> 0) < (b >>> 0) ? 1 : 0 -} - -Sha512.prototype._update = function (M) { - var W = this._w - - var ah = this._ah | 0 - var bh = this._bh | 0 - var ch = this._ch | 0 - var dh = this._dh | 0 - var eh = this._eh | 0 - var fh = this._fh | 0 - var gh = this._gh | 0 - var hh = this._hh | 0 - - var al = this._al | 0 - var bl = this._bl | 0 - var cl = this._cl | 0 - var dl = this._dl | 0 - var el = this._el | 0 - var fl = this._fl | 0 - var gl = this._gl | 0 - var hl = this._hl | 0 - - for (var i = 0; i < 32; i += 2) { - W[i] = M.readInt32BE(i * 4) - W[i + 1] = M.readInt32BE(i * 4 + 4) - } - for (; i < 160; i += 2) { - var xh = W[i - 15 * 2] - var xl = W[i - 15 * 2 + 1] - var gamma0 = Gamma0(xh, xl) - var gamma0l = Gamma0l(xl, xh) - - xh = W[i - 2 * 2] - xl = W[i - 2 * 2 + 1] - var gamma1 = Gamma1(xh, xl) - var gamma1l = Gamma1l(xl, xh) - - // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] - var Wi7h = W[i - 7 * 2] - var Wi7l = W[i - 7 * 2 + 1] - - var Wi16h = W[i - 16 * 2] - var Wi16l = W[i - 16 * 2 + 1] - - var Wil = (gamma0l + Wi7l) | 0 - var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 - Wil = (Wil + gamma1l) | 0 - Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 - Wil = (Wil + Wi16l) | 0 - Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 - - W[i] = Wih - W[i + 1] = Wil - } - - for (var j = 0; j < 160; j += 2) { - Wih = W[j] - Wil = W[j + 1] - - var majh = maj(ah, bh, ch) - var majl = maj(al, bl, cl) - - var sigma0h = sigma0(ah, al) - var sigma0l = sigma0(al, ah) - var sigma1h = sigma1(eh, el) - var sigma1l = sigma1(el, eh) - - // t1 = h + sigma1 + ch + K[j] + W[j] - var Kih = K[j] - var Kil = K[j + 1] - - var chh = Ch(eh, fh, gh) - var chl = Ch(el, fl, gl) - - var t1l = (hl + sigma1l) | 0 - var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 - t1l = (t1l + chl) | 0 - t1h = (t1h + chh + getCarry(t1l, chl)) | 0 - t1l = (t1l + Kil) | 0 - t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 - t1l = (t1l + Wil) | 0 - t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 - - // t2 = sigma0 + maj - var t2l = (sigma0l + majl) | 0 - var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 - - hh = gh - hl = gl - gh = fh - gl = fl - fh = eh - fl = el - el = (dl + t1l) | 0 - eh = (dh + t1h + getCarry(el, dl)) | 0 - dh = ch - dl = cl - ch = bh - cl = bl - bh = ah - bl = al - al = (t1l + t2l) | 0 - ah = (t1h + t2h + getCarry(al, t1l)) | 0 - } - - this._al = (this._al + al) | 0 - this._bl = (this._bl + bl) | 0 - this._cl = (this._cl + cl) | 0 - this._dl = (this._dl + dl) | 0 - this._el = (this._el + el) | 0 - this._fl = (this._fl + fl) | 0 - this._gl = (this._gl + gl) | 0 - this._hl = (this._hl + hl) | 0 - - this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 - this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 - this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 - this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 - this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 - this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 - this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 - this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 -} - -Sha512.prototype._hash = function () { - var H = Buffer.allocUnsafe(64) - - function writeInt64BE (h, l, offset) { - H.writeInt32BE(h, offset) - H.writeInt32BE(l, offset + 4) - } - - writeInt64BE(this._ah, this._al, 0) - writeInt64BE(this._bh, this._bl, 8) - writeInt64BE(this._ch, this._cl, 16) - writeInt64BE(this._dh, this._dl, 24) - writeInt64BE(this._eh, this._el, 32) - writeInt64BE(this._fh, this._fl, 40) - writeInt64BE(this._gh, this._gl, 48) - writeInt64BE(this._hh, this._hl, 56) - - return H -} - -module.exports = Sha512 - -},{"./hash":124,"inherits":98,"safe-buffer":117}],132:[function(require,module,exports){ -var isHexPrefixed = require('is-hex-prefixed'); - -/** - * Removes '0x' from a given `String` is present - * @param {String} str the string value - * @return {String|Optional} a string by pass if necessary - */ -module.exports = function stripHexPrefix(str) { - if (typeof str !== 'string') { - return str; - } - - return isHexPrefixed(str) ? str.slice(2) : str; -} - -},{"is-hex-prefixed":99}],133:[function(require,module,exports){ -var native = require('./native') - -function getTypeName (fn) { - return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] -} - -function getValueTypeName (value) { - return native.Nil(value) ? '' : getTypeName(value.constructor) -} - -function getValue (value) { - if (native.Function(value)) return '' - if (native.String(value)) return JSON.stringify(value) - if (value && native.Object(value)) return '' - return value -} - -function captureStackTrace (e, t) { - if (Error.captureStackTrace) { - Error.captureStackTrace(e, t) - } -} - -function tfJSON (type) { - if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) - if (native.Array(type)) return 'Array' - if (type && native.Object(type)) return 'Object' - - return type !== undefined ? type : '' -} - -function tfErrorString (type, value, valueTypeName) { - var valueJson = getValue(value) - - return 'Expected ' + tfJSON(type) + ', got' + - (valueTypeName !== '' ? ' ' + valueTypeName : '') + - (valueJson !== '' ? ' ' + valueJson : '') -} - -function TfTypeError (type, value, valueTypeName) { - valueTypeName = valueTypeName || getValueTypeName(value) - this.message = tfErrorString(type, value, valueTypeName) - - captureStackTrace(this, TfTypeError) - this.__type = type - this.__value = value - this.__valueTypeName = valueTypeName -} - -TfTypeError.prototype = Object.create(Error.prototype) -TfTypeError.prototype.constructor = TfTypeError - -function tfPropertyErrorString (type, label, name, value, valueTypeName) { - var description = '" of type ' - if (label === 'key') description = '" with key type ' - - return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName) -} - -function TfPropertyTypeError (type, property, label, value, valueTypeName) { - if (type) { - valueTypeName = valueTypeName || getValueTypeName(value) - this.message = tfPropertyErrorString(type, label, property, value, valueTypeName) - } else { - this.message = 'Unexpected property "' + property + '"' - } - - captureStackTrace(this, TfTypeError) - this.__label = label - this.__property = property - this.__type = type - this.__value = value - this.__valueTypeName = valueTypeName -} - -TfPropertyTypeError.prototype = Object.create(Error.prototype) -TfPropertyTypeError.prototype.constructor = TfTypeError - -function tfCustomError (expected, actual) { - return new TfTypeError(expected, {}, actual) -} - -function tfSubError (e, property, label) { - // sub child? - if (e instanceof TfPropertyTypeError) { - property = property + '.' + e.__property - - e = new TfPropertyTypeError( - e.__type, property, e.__label, e.__value, e.__valueTypeName - ) - - // child? - } else if (e instanceof TfTypeError) { - e = new TfPropertyTypeError( - e.__type, property, label, e.__value, e.__valueTypeName - ) - } - - captureStackTrace(e) - return e -} - -module.exports = { - TfTypeError: TfTypeError, - TfPropertyTypeError: TfPropertyTypeError, - tfCustomError: tfCustomError, - tfSubError: tfSubError, - tfJSON: tfJSON, - getValueTypeName: getValueTypeName -} - -},{"./native":136}],134:[function(require,module,exports){ -(function (Buffer){ -var NATIVE = require('./native') -var ERRORS = require('./errors') - -function _Buffer (value) { - return Buffer.isBuffer(value) -} - -function Hex (value) { - return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) -} - -function _LengthN (type, length) { - var name = type.toJSON() - - function Length (value) { - if (!type(value)) return false - if (value.length === length) return true - - throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') - } - Length.toJSON = function () { return name } - - return Length -} - -var _ArrayN = _LengthN.bind(null, NATIVE.Array) -var _BufferN = _LengthN.bind(null, _Buffer) -var _HexN = _LengthN.bind(null, Hex) -var _StringN = _LengthN.bind(null, NATIVE.String) - -function Range (a, b, f) { - f = f || NATIVE.Number - function _range (value, strict) { - return f(value, strict) && (value > a) && (value < b) - } - _range.toJSON = function () { - return `${f.toJSON()} between [${a}, ${b}]` - } - return _range -} - -var INT53_MAX = Math.pow(2, 53) - 1 - -function Finite (value) { - return typeof value === 'number' && isFinite(value) -} -function Int8 (value) { return ((value << 24) >> 24) === value } -function Int16 (value) { return ((value << 16) >> 16) === value } -function Int32 (value) { return (value | 0) === value } -function Int53 (value) { - return typeof value === 'number' && - value >= -INT53_MAX && - value <= INT53_MAX && - Math.floor(value) === value -} -function UInt8 (value) { return (value & 0xff) === value } -function UInt16 (value) { return (value & 0xffff) === value } -function UInt32 (value) { return (value >>> 0) === value } -function UInt53 (value) { - return typeof value === 'number' && - value >= 0 && - value <= INT53_MAX && - Math.floor(value) === value -} - -var types = { - ArrayN: _ArrayN, - Buffer: _Buffer, - BufferN: _BufferN, - Finite: Finite, - Hex: Hex, - HexN: _HexN, - Int8: Int8, - Int16: Int16, - Int32: Int32, - Int53: Int53, - Range: Range, - StringN: _StringN, - UInt8: UInt8, - UInt16: UInt16, - UInt32: UInt32, - UInt53: UInt53 -} - -for (var typeName in types) { - types[typeName].toJSON = function (t) { - return t - }.bind(null, typeName) -} - -module.exports = types - -}).call(this,{"isBuffer":require("../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) -},{"../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":154,"./errors":133,"./native":136}],135:[function(require,module,exports){ -var ERRORS = require('./errors') -var NATIVE = require('./native') - -// short-hand -var tfJSON = ERRORS.tfJSON -var TfTypeError = ERRORS.TfTypeError -var TfPropertyTypeError = ERRORS.TfPropertyTypeError -var tfSubError = ERRORS.tfSubError -var getValueTypeName = ERRORS.getValueTypeName - -var TYPES = { - arrayOf: function arrayOf (type, options) { - type = compile(type) - options = options || {} - - function _arrayOf (array, strict) { - if (!NATIVE.Array(array)) return false - if (NATIVE.Nil(array)) return false - if (options.minLength !== undefined && array.length < options.minLength) return false - if (options.maxLength !== undefined && array.length > options.maxLength) return false - if (options.length !== undefined && array.length !== options.length) return false - - return array.every(function (value, i) { - try { - return typeforce(type, value, strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _arrayOf.toJSON = function () { - var str = '[' + tfJSON(type) + ']' - if (options.length !== undefined) { - str += '{' + options.length + '}' - } else if (options.minLength !== undefined || options.maxLength !== undefined) { - str += '{' + - (options.minLength === undefined ? 0 : options.minLength) + ',' + - (options.maxLength === undefined ? Infinity : options.maxLength) + '}' - } - return str - } - - return _arrayOf - }, - - maybe: function maybe (type) { - type = compile(type) - - function _maybe (value, strict) { - return NATIVE.Nil(value) || type(value, strict, maybe) - } - _maybe.toJSON = function () { return '?' + tfJSON(type) } - - return _maybe - }, - - map: function map (propertyType, propertyKeyType) { - propertyType = compile(propertyType) - if (propertyKeyType) propertyKeyType = compile(propertyKeyType) - - function _map (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - for (var propertyName in value) { - try { - if (propertyKeyType) { - typeforce(propertyKeyType, propertyName, strict) - } - } catch (e) { - throw tfSubError(e, propertyName, 'key') - } - - try { - var propertyValue = value[propertyName] - typeforce(propertyType, propertyValue, strict) - } catch (e) { - throw tfSubError(e, propertyName) - } - } - - return true - } - - if (propertyKeyType) { - _map.toJSON = function () { - return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' - } - } else { - _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' } - } - - return _map - }, - - object: function object (uncompiled) { - var type = {} - - for (var typePropertyName in uncompiled) { - type[typePropertyName] = compile(uncompiled[typePropertyName]) - } - - function _object (value, strict) { - if (!NATIVE.Object(value)) return false - if (NATIVE.Nil(value)) return false - - var propertyName - - try { - for (propertyName in type) { - var propertyType = type[propertyName] - var propertyValue = value[propertyName] - - typeforce(propertyType, propertyValue, strict) - } - } catch (e) { - throw tfSubError(e, propertyName) - } - - if (strict) { - for (propertyName in value) { - if (type[propertyName]) continue - - throw new TfPropertyTypeError(undefined, propertyName) - } - } - - return true - } - _object.toJSON = function () { return tfJSON(type) } - - return _object - }, - - anyOf: function anyOf () { - var types = [].slice.call(arguments).map(compile) - - function _anyOf (value, strict) { - return types.some(function (type) { - try { - return typeforce(type, value, strict) - } catch (e) { - return false - } - }) - } - _anyOf.toJSON = function () { return types.map(tfJSON).join('|') } - - return _anyOf - }, - - allOf: function allOf () { - var types = [].slice.call(arguments).map(compile) - - function _allOf (value, strict) { - return types.every(function (type) { - try { - return typeforce(type, value, strict) - } catch (e) { - return false - } - }) - } - _allOf.toJSON = function () { return types.map(tfJSON).join(' & ') } - - return _allOf - }, - - quacksLike: function quacksLike (type) { - function _quacksLike (value) { - return type === getValueTypeName(value) - } - _quacksLike.toJSON = function () { return type } - - return _quacksLike - }, - - tuple: function tuple () { - var types = [].slice.call(arguments).map(compile) - - function _tuple (values, strict) { - if (NATIVE.Nil(values)) return false - if (NATIVE.Nil(values.length)) return false - if (strict && (values.length !== types.length)) return false - - return types.every(function (type, i) { - try { - return typeforce(type, values[i], strict) - } catch (e) { - throw tfSubError(e, i) - } - }) - } - _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' } - - return _tuple - }, - - value: function value (expected) { - function _value (actual) { - return actual === expected - } - _value.toJSON = function () { return expected } - - return _value - } -} - -// TODO: deprecate -TYPES.oneOf = TYPES.anyOf - -function compile (type) { - if (NATIVE.String(type)) { - if (type[0] === '?') return TYPES.maybe(type.slice(1)) - - return NATIVE[type] || TYPES.quacksLike(type) - } else if (type && NATIVE.Object(type)) { - if (NATIVE.Array(type)) { - if (type.length !== 1) throw new TypeError('Expected compile() parameter of type Array of length 1') - return TYPES.arrayOf(type[0]) - } - - return TYPES.object(type) - } else if (NATIVE.Function(type)) { - return type - } - - return TYPES.value(type) -} - -function typeforce (type, value, strict, surrogate) { - if (NATIVE.Function(type)) { - if (type(value, strict)) return true - - throw new TfTypeError(surrogate || type, value) - } - - // JIT - return typeforce(compile(type), value, strict) -} - -// assign types to typeforce function -for (var typeName in NATIVE) { - typeforce[typeName] = NATIVE[typeName] -} - -for (typeName in TYPES) { - typeforce[typeName] = TYPES[typeName] -} - -var EXTRA = require('./extra') -for (typeName in EXTRA) { - typeforce[typeName] = EXTRA[typeName] -} - -typeforce.compile = compile -typeforce.TfTypeError = TfTypeError -typeforce.TfPropertyTypeError = TfPropertyTypeError - -module.exports = typeforce - -},{"./errors":133,"./extra":134,"./native":136}],136:[function(require,module,exports){ -var types = { - Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, - Boolean: function (value) { return typeof value === 'boolean' }, - Function: function (value) { return typeof value === 'function' }, - Nil: function (value) { return value === undefined || value === null }, - Number: function (value) { return typeof value === 'number' }, - Object: function (value) { return typeof value === 'object' }, - String: function (value) { return typeof value === 'string' }, - '': function () { return true } -} - -// TODO: deprecate -types.Null = types.Nil - -for (var typeName in types) { - types[typeName].toJSON = function (t) { - return t - }.bind(null, typeName) -} - -module.exports = types - -},{}],137:[function(require,module,exports){ -'use strict' -var Buffer = require('safe-buffer').Buffer - -// Number.MAX_SAFE_INTEGER -var MAX_SAFE_INTEGER = 9007199254740991 - -function checkUInt53 (n) { - if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range') -} - -function encode (number, buffer, offset) { - checkUInt53(number) - - if (!buffer) buffer = Buffer.allocUnsafe(encodingLength(number)) - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0 - - // 8 bit - if (number < 0xfd) { - buffer.writeUInt8(number, offset) - encode.bytes = 1 - - // 16 bit - } else if (number <= 0xffff) { - buffer.writeUInt8(0xfd, offset) - buffer.writeUInt16LE(number, offset + 1) - encode.bytes = 3 - - // 32 bit - } else if (number <= 0xffffffff) { - buffer.writeUInt8(0xfe, offset) - buffer.writeUInt32LE(number, offset + 1) - encode.bytes = 5 - - // 64 bit - } else { - buffer.writeUInt8(0xff, offset) - buffer.writeUInt32LE(number >>> 0, offset + 1) - buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5) - encode.bytes = 9 - } - - return buffer -} - -function decode (buffer, offset) { - if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') - if (!offset) offset = 0 - - var first = buffer.readUInt8(offset) - - // 8 bit - if (first < 0xfd) { - decode.bytes = 1 - return first - - // 16 bit - } else if (first === 0xfd) { - decode.bytes = 3 - return buffer.readUInt16LE(offset + 1) - - // 32 bit - } else if (first === 0xfe) { - decode.bytes = 5 - return buffer.readUInt32LE(offset + 1) - - // 64 bit - } else { - decode.bytes = 9 - var lo = buffer.readUInt32LE(offset + 1) - var hi = buffer.readUInt32LE(offset + 5) - var number = hi * 0x0100000000 + lo - checkUInt53(number) - - return number - } -} - -function encodingLength (number) { - checkUInt53(number) - - return ( - number < 0xfd ? 1 - : number <= 0xffff ? 3 - : number <= 0xffffffff ? 5 - : 9 - ) -} - -module.exports = { encode: encode, decode: decode, encodingLength: encodingLength } - -},{"safe-buffer":117}],138:[function(require,module,exports){ -/*! websocket-as-promised v0.8.0 */ -!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.WebSocketAsPromised=t():e.WebSocketAsPromised=t()}(this,function(){return function(e){var t={};function n(r){if(t[r])return t[r].exports;var o=t[r]={i:r,l:!1,exports:{}};return e[r].call(o.exports,o,o.exports,n),o.l=!0,o.exports}return n.m=e,n.c=t,n.d=function(e,t,r){n.o(e,t)||Object.defineProperty(e,t,{enumerable:!0,get:r})},n.r=function(e){"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},n.t=function(e,t){if(1&t&&(e=n(e)),8&t)return e;if(4&t&&"object"==typeof e&&e&&e.__esModule)return e;var r=Object.create(null);if(n.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:e}),2&t&&"string"!=typeof e)for(var o in e)n.d(r,o,function(t){return e[t]}.bind(null,o));return r},n.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return n.d(t,"a",t),t},n.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},n.p="",n(n.s=16)}([function(e,t,n){"use strict";var r=n(24);e.exports=Function.prototype.bind||r},function(e,t,n){"use strict";e.exports=function(){if("function"!=typeof Promise)throw new TypeError("`Promise.prototype.finally` requires a global `Promise` be available.")}},function(e,t,n){var r=n(0);e.exports=r.call(Function.call,Object.prototype.hasOwnProperty)},function(e,t,n){"use strict";var r=Function.prototype.toString,o=/^\s*class /,i=function(e){try{var t=r.call(e).replace(/\/\/.*\n/g,"").replace(/\/\*[.\s\S]*\*\//g,"").replace(/\n/gm," ").replace(/ {2}/g," ");return o.test(t)}catch(e){return!1}},s=Object.prototype.toString,u="function"==typeof Symbol&&"symbol"==typeof Symbol.toStringTag;e.exports=function(e){if(!e)return!1;if("function"!=typeof e&&"object"!=typeof e)return!1;if(u)return function(e){try{return!i(e)&&(r.call(e),!0)}catch(e){return!1}}(e);if(i(e))return!1;var t=s.call(e);return"[object Function]"===t||"[object GeneratorFunction]"===t}},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n=0&&this._spliceListener(n)}},{key:"removeAllListeners",value:function(){for(;this.hasListeners();)this._spliceListener(0)}},{key:"hasListener",value:function(e,t){return this._ensureFunction(e),this._indexOfListener(e,t)>=0}},{key:"hasListeners",value:function(){return this._listeners.length>0}},{key:"dispatch",value:function(){for(var e=arguments.length,t=Array(e),n=0;n0&&void 0!==arguments[0]?arguments[0]:{};this._mute=!0,e.accumulate?this._accumulate=!0:(this._accumulate=!1,this._accumulatedEvents=[])}},{key:"unmute",value:function(){this._mute=!1,this._accumulate&&(this._dispatchAccumulated(),this._accumulate=!1)}},{key:"_invokeListeners",value:function(){var e=this,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{args:[],async:!1};this._mute?this._accumulate&&this._accumulatedEvents.push(t):this._listeners.slice().forEach(function(n){e._invokeListener(n,t),n.once&&e.removeListener(n.callback,n.context)})}},{key:"_invokeListener",value:function(e,t){t.async?setTimeout(function(){return e.callback.apply(e.context,t.args)},0):e.callback.apply(e.context,t.args)}},{key:"_ensureFunction",value:function(e){if("function"!=typeof e)throw new Error("Channel "+this._name+": listener is not a function")}},{key:"_dispatchInnerAddEvents",value:function(){this._noInnerEvents||(this.onListenerAdded.dispatch.apply(this.onListenerAdded,arguments),1===this._listeners.length&&this.onFirstListenerAdded.dispatch.apply(this.onFirstListenerAdded,arguments))}},{key:"_dispatchInnerRemoveEvents",value:function(){this._noInnerEvents||(this.onListenerRemoved.dispatch.apply(this.onListenerRemoved,arguments),0===this._listeners.length&&this.onLastListenerRemoved.dispatch.apply(this.onLastListenerRemoved,arguments))}},{key:"_indexOfListener",value:function(e,t){for(var n=0;n2?arguments[2]:{},s=r(t);i&&(s=s.concat(Object.getOwnPropertySymbols(t))),o(s,function(r){a(e,r,t[r],n[r])})};c.supportsDescriptors=!!u,e.exports=c},function(e,t,n){"use strict";n(1)();var r=n(28),o=n(0),i=function(e,t){return new e(function(e){e(t)})},s=Promise,u=o.call(Function.call,s.prototype.then),a=function(e){u(this,null,function(){});var t=r.SpeciesConstructor(this,s),n=e,o=e;return r.IsCallable(e)&&(n=function(e,t){return function(n){var r=t();return i(e,r).then(function(){return n})}}(t,e),o=function(e,t){return function(n){var r=t();return i(e,r).then(function(){throw n})}}(t,e)),this.then(n,o)};if(Object.getOwnPropertyDescriptor){var c=Object.getOwnPropertyDescriptor(a,"name");c&&c.configurable&&Object.defineProperty(a,"name",{configurable:!0,value:"finally"})}e.exports=a},function(e,t){e.exports=function(e){return null===e||"function"!=typeof e&&"object"!=typeof e}},function(e,t){e.exports=Number.isNaN||function(e){return e!=e}},function(e,t){var n=Number.isNaN||function(e){return e!=e};e.exports=Number.isFinite||function(e){return"number"==typeof e&&!n(e)&&e!==1/0&&e!==-1/0}},function(e,t){var n=Object.prototype.hasOwnProperty;e.exports=function(e,t){if(Object.assign)return Object.assign(e,t);for(var r in t)n.call(t,r)&&(e[r]=t[r]);return e}},function(e,t){e.exports=function(e){return e>=0?1:-1}},function(e,t){e.exports=function(e,t){var n=e%t;return Math.floor(n>=0?n:n+t)}},function(e,t,n){"use strict";var r=n(1),o=n(8);e.exports=function(){return r(),"function"==typeof Promise.prototype.finally?Promise.prototype.finally:o}},function(e,t,n){"use strict";var r=function(){function e(e,t){for(var n=0;n1&&void 0!==arguments[1]?arguments[1]:{},r=n.requestId||""+Math.random(),o=void 0!==n.timeout?n.timeout:this._options.timeout;return this._requests.create(r,function(){t._assertRequestIdHandlers();var n=t._options.attachRequestId(e,r);t.sendPacked(n)},o)}},{key:"sendPacked",value:function(e){this._assertPackingHandlers();var t=this._options.packMessage(e);this.send(t)}},{key:"send",value:function(e){c(!this.isOpened,"Can't send data because WebSocket is not opened."),this._ws.send(e),this._onSend.dispatchAsync(e)}},{key:"close",value:function(){var e=this;return this.isClosed?Promise.resolve(this._closing.value):this._closing.call(function(){return e._ws.close()})}},{key:"removeAllListeners",value:function(){this._onOpen.removeAllListeners(),this._onMessage.removeAllListeners(),this._onUnpackedMessage.removeAllListeners(),this._onResponse.removeAllListeners(),this._onSend.removeAllListeners(),this._onClose.removeAllListeners(),this._onError.removeAllListeners()}},{key:"_createOpeningController",value:function(){var e=this._options.connectionTimeout||this._options.timeout;this._opening=new i({timeout:e,timeoutReason:"Can't open WebSocket within allowed timeout: "+e+" ms."})}},{key:"_createClosingController",value:function(){var e=this._options.timeout;this._closing=new i({timeout:e,timeoutReason:"Can't close WebSocket within allowed timeout: "+e+" ms."})}},{key:"_createChannels",value:function(){this._onOpen=new o,this._onMessage=new o,this._onUnpackedMessage=new o,this._onResponse=new o,this._onSend=new o,this._onClose=new o,this._onError=new o}},{key:"_createWS",value:function(){var e=this;this._ws=this._options.createWebSocket(this._url),this._wsSubscription=new o.Subscription([{channel:this._ws,event:"open",listener:function(t){return e._handleOpen(t)}},{channel:this._ws,event:"message",listener:function(t){return e._handleMessage(t)}},{channel:this._ws,event:"error",listener:function(t){return e._handleError(t)}},{channel:this._ws,event:"close",listener:function(t){return e._handleClose(t)}}]).on()}},{key:"_handleOpen",value:function(e){this._onOpen.dispatchAsync(e),this._opening.resolve(e)}},{key:"_handleMessage",value:function(e){var t=e.data;this._onMessage.dispatchAsync(t),this._handleUnpackedMessage(t)}},{key:"_handleUnpackedMessage",value:function(e){if(this._options.unpackMessage){var t=this._options.unpackMessage(e);void 0!==t&&(this._onUnpackedMessage.dispatchAsync(t),this._handleResponse(t))}}},{key:"_handleResponse",value:function(e){if(this._options.extractRequestId){var t=this._options.extractRequestId(e);t&&(this._onResponse.dispatchAsync(e,t),this._requests.resolve(t,e))}}},{key:"_handleError",value:function(e){this._onError.dispatchAsync(e)}},{key:"_handleClose",value:function(e){this._onClose.dispatchAsync(e),this._closing.resolve(e);var t=new Error("WebSocket closed with reason: "+e.reason+" ("+e.code+").");this._opening.isPending&&this._opening.reject(t),this._cleanup(t)}},{key:"_cleanupWS",value:function(){this._wsSubscription&&(this._wsSubscription.off(),this._wsSubscription=null),this._ws=null}},{key:"_cleanup",value:function(e){this._cleanupWS(),this._requests.rejectAll(e)}},{key:"_assertPackingHandlers",value:function(){var e=this._options,t=e.packMessage,n=e.unpackMessage;c(!t||!n,"Please define 'options.packMessage / options.unpackMessage' for sending packed messages.")}},{key:"_assertRequestIdHandlers",value:function(){var e=this._options,t=e.attachRequestId,n=e.extractRequestId;c(!t||!n,"Please define 'options.attachRequestId / options.extractRequestId' for sending requests.")}},{key:"ws",get:function(){return this._ws}},{key:"isOpening",get:function(){return Boolean(this._ws&&this._ws.readyState===l)}},{key:"isOpened",get:function(){return Boolean(this._ws&&this._ws.readyState===f)}},{key:"isClosing",get:function(){return Boolean(this._ws&&this._ws.readyState===p)}},{key:"isClosed",get:function(){return Boolean(!this._ws||this._ws.readyState===h)}},{key:"onOpen",get:function(){return this._onOpen}},{key:"onSend",get:function(){return this._onSend}},{key:"onMessage",get:function(){return this._onMessage}},{key:"onPackedMessage",get:function(){throw new Error(["Websocket-as-promised 'onPackedMessage' was renamed into 'onUnpackedMessage' to match the argument","passed to the listener. Please just use 'onUnpackedMessage' instead."].join(" "))}},{key:"onUnpackedMessage",get:function(){return this._onUnpackedMessage}},{key:"onResponse",get:function(){return this._onResponse}},{key:"onClose",get:function(){return this._onClose}},{key:"onError",get:function(){return this._onError}}]),e}();e.exports=y},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=u(n(4)),o=u(n(18)),i=u(n(5)),s=u(n(20));function u(e){return e&&e.__esModule?e:{default:e}}var a=r.default;a.EventEmitter=o.default,a.Subscription=i.default,a.ReactSubscription=s.default,t.default=a,e.exports=t.default},function(e,t,n){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=function(){function e(e,t){for(var n=0;n1?n-1:0),o=1;o1?t-1:0),r=1;r0&&!r.call(e,0))for(var b=0;b0)for(var v=0;v=0&&"[object Function]"===r.call(e.callee)),n}},function(e,t){var n=Object.prototype.hasOwnProperty,r=Object.prototype.toString;e.exports=function(e,t,o){if("[object Function]"!==r.call(t))throw new TypeError("iterator must be a function");var i=e.length;if(i===+i)for(var s=0;s2?arguments[2]:[];if(!this.IsCallable(e))throw new TypeError(e+" is not a function");return e.apply(t,n)},ToPrimitive:o,ToNumber:function(e){var t=h(e)?e:o(e,Number);if("symbol"==typeof t)throw new TypeError("Cannot convert a Symbol value to a number");if("string"==typeof t){if(m(t))return this.ToNumber(y(d(t,2),2));if(_(t))return this.ToNumber(y(d(t,2),8));if(O(t)||k(t))return NaN;var n=function(e){return P(e,S,"")}(t);if(n!==t)return this.ToNumber(n)}return Number(t)},ToInt16:function(e){var t=this.ToUint16(e);return t>=32768?t-65536:t},ToInt8:function(e){var t=this.ToUint8(e);return t>=128?t-256:t},ToUint8:function(e){var t=this.ToNumber(e);if(u(t)||0===t||!a(t))return 0;var n=f(t)*Math.floor(Math.abs(t));return p(n,256)},ToUint8Clamp:function(e){var t=this.ToNumber(e);if(u(t)||t<=0)return 0;if(t>=255)return 255;var n=Math.floor(e);return n+.5c?c:t},CanonicalNumericIndexString:function(e){if("[object String]"!==i.call(e))throw new TypeError("must be a string");if("-0"===e)return-0;var t=this.ToNumber(e);return this.SameValue(this.ToString(t),e)?t:void 0},RequireObjectCoercible:E.CheckObjectCoercible,IsArray:Array.isArray||function(e){return"[object Array]"===i.call(e)},IsConstructor:function(e){return"function"==typeof e&&!!e.prototype},IsExtensible:function(e){return!Object.preventExtensions||!h(e)&&Object.isExtensible(e)},IsInteger:function(e){if("number"!=typeof e||u(e)||!a(e))return!1;var t=Math.abs(e);return Math.floor(t)===t},IsPropertyKey:function(e){return"string"==typeof e||"symbol"==typeof e},IsRegExp:function(e){if(!e||"object"!=typeof e)return!1;if(s){var t=e[Symbol.match];if(void 0!==t)return E.ToBoolean(t)}return x(e)},SameValueZero:function(e,t){return e===t||u(e)&&u(t)},GetV:function(e,t){if(!this.IsPropertyKey(t))throw new TypeError("Assertion failed: IsPropertyKey(P) is not true");return this.ToObject(e)[t]},GetMethod:function(e,t){if(!this.IsPropertyKey(t))throw new TypeError("Assertion failed: IsPropertyKey(P) is not true");var n=this.GetV(e,t);if(null!=n){if(!this.IsCallable(n))throw new TypeError(t+"is not a function");return n}},Get:function(e,t){if("Object"!==this.Type(e))throw new TypeError("Assertion failed: Type(O) is not Object");if(!this.IsPropertyKey(t))throw new TypeError("Assertion failed: IsPropertyKey(P) is not true");return e[t]},Type:function(e){return"symbol"==typeof e?"Symbol":E.Type(e)},SpeciesConstructor:function(e,t){if("Object"!==this.Type(e))throw new TypeError("Assertion failed: Type(O) is not Object");var n=e.constructor;if(void 0===n)return t;if("Object"!==this.Type(n))throw new TypeError("O.constructor is not an Object");var r=s&&Symbol.species?n[Symbol.species]:void 0;if(null==r)return t;if(this.IsConstructor(r))return r;throw new TypeError("no constructor found")},CompletePropertyDescriptor:function(e){if(!this.IsPropertyDescriptor(e))throw new TypeError("Desc must be a Property Descriptor");return this.IsGenericDescriptor(e)||this.IsDataDescriptor(e)?(r(e,"[[Value]]")||(e["[[Value]]"]=void 0),r(e,"[[Writable]]")||(e["[[Writable]]"]=!1)):(r(e,"[[Get]]")||(e["[[Get]]"]=void 0),r(e,"[[Set]]")||(e["[[Set]]"]=void 0)),r(e,"[[Enumerable]]")||(e["[[Enumerable]]"]=!1),r(e,"[[Configurable]]")||(e["[[Configurable]]"]=!1),e},Set:function(e,t,n,r){if("Object"!==this.Type(e))throw new TypeError("O must be an Object");if(!this.IsPropertyKey(t))throw new TypeError("P must be a Property Key");if("Boolean"!==this.Type(r))throw new TypeError("Throw must be a Boolean");if(r)return e[t]=n,!0;try{e[t]=n}catch(e){return!1}},HasOwnProperty:function(e,t){if("Object"!==this.Type(e))throw new TypeError("O must be an Object");if(!this.IsPropertyKey(t))throw new TypeError("P must be a Property Key");return r(e,t)},HasProperty:function(e,t){if("Object"!==this.Type(e))throw new TypeError("O must be an Object");if(!this.IsPropertyKey(t))throw new TypeError("P must be a Property Key");return t in e},IsConcatSpreadable:function(e){if("Object"!==this.Type(e))return!1;if(s&&"symbol"==typeof Symbol.isConcatSpreadable){var t=this.Get(e,Symbol.isConcatSpreadable);if(void 0!==t)return this.ToBoolean(t)}return this.IsArray(e)},Invoke:function(e,t){if(!this.IsPropertyKey(t))throw new TypeError("P must be a Property Key");var n=v(arguments,2),r=this.GetV(e,t);return this.Call(r,e,n)},CreateIterResultObject:function(e,t){if("Boolean"!==this.Type(t))throw new TypeError("Assertion failed: Type(done) is not Boolean");return{value:e,done:t}},RegExpExec:function(e,t){if("Object"!==this.Type(e))throw new TypeError("R must be an Object");if("String"!==this.Type(t))throw new TypeError("S must be a String");var n=this.Get(e,"exec");if(this.IsCallable(n)){var r=this.Call(n,e,[t]);if(null===r||"Object"===this.Type(r))return r;throw new TypeError('"exec" method must return `null` or an Object')}return g(e,t)},ArraySpeciesCreate:function(e,t){if(!this.IsInteger(t)||t<0)throw new TypeError("Assertion failed: length must be an integer >= 0");var n,r=0===t?0:t;if(this.IsArray(e)&&(n=this.Get(e,"constructor"),"Object"===this.Type(n)&&s&&Symbol.species&&null===(n=this.Get(n,Symbol.species))&&(n=void 0)),void 0===n)return Array(r);if(!this.IsConstructor(n))throw new TypeError("C must be a constructor");return new n(r)},CreateDataProperty:function(e,t,n){if("Object"!==this.Type(e))throw new TypeError("Assertion failed: Type(O) is not Object");if(!this.IsPropertyKey(t))throw new TypeError("Assertion failed: IsPropertyKey(P) is not true");var r=Object.getOwnPropertyDescriptor(e,t),o=r||"function"!=typeof Object.isExtensible||Object.isExtensible(e);if(r&&(!r.writable||!r.configurable)||!o)return!1;var i={configurable:!0,enumerable:!0,value:n,writable:!0};return Object.defineProperty(e,t,i),!0},CreateDataPropertyOrThrow:function(e,t,n){if("Object"!==this.Type(e))throw new TypeError("Assertion failed: Type(O) is not Object");if(!this.IsPropertyKey(t))throw new TypeError("Assertion failed: IsPropertyKey(P) is not true");var r=this.CreateDataProperty(e,t,n);if(!r)throw new TypeError("unable to create data property");return r},AdvanceStringIndex:function(e,t,n){if("String"!==this.Type(e))throw new TypeError("Assertion failed: Type(S) is not String");if(!this.IsInteger(t))throw new TypeError("Assertion failed: length must be an integer >= 0 and <= (2**53 - 1)");if(t<0||t>c)throw new RangeError("Assertion failed: length must be an integer >= 0 and <= (2**53 - 1)");if("Boolean"!==this.Type(n))throw new TypeError("Assertion failed: Type(unicode) is not Boolean");if(!n)return t+1;if(t+1>=e.length)return t+1;var r=e.charCodeAt(t);if(r<55296||r>56319)return t+1;var o=e.charCodeAt(t+1);return o<56320||o>57343?t+1:t+2}});delete C.CheckObjectCoercible,e.exports=C},function(e,t,n){"use strict";var r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator,o=n(9),i=n(3),s=n(32),u=n(33);e.exports=function(e,t){if(o(e))return e;var n,a="default";if(arguments.length>1&&(t===String?a="string":t===Number&&(a="number")),r&&(Symbol.toPrimitive?n=function(e,t){var n=e[t];if(null!==n&&void 0!==n){if(!i(n))throw new TypeError(n+" returned for property "+t+" of object "+e+" is not a function");return n}}(e,Symbol.toPrimitive):u(e)&&(n=Symbol.prototype.valueOf)),void 0!==n){var c=n.call(e,a);if(o(c))return c;throw new TypeError("unable to convert exotic object to primitive")}return"default"===a&&(s(e)||u(e))&&(a="string"),function(e,t){if(void 0===e||null===e)throw new TypeError("Cannot call method on "+e);if("string"!=typeof t||"number"!==t&&"string"!==t)throw new TypeError('hint must be "string" or "number"');var n,r,s,u="string"===t?["toString","valueOf"]:["valueOf","toString"];for(s=0;s>0},ToUint32:function(e){return this.ToNumber(e)>>>0},ToUint16:function(e){var t=this.ToNumber(e);if(r(t)||0===t||!o(t))return 0;var n=i(t)*Math.floor(Math.abs(t));return s(n,65536)},ToString:function(e){return String(e)},ToObject:function(e){return this.CheckObjectCoercible(e),Object(e)},CheckObjectCoercible:function(e,t){if(null==e)throw new TypeError(t||"Cannot call method on "+e);return e},IsCallable:u,SameValue:function(e,t){return e===t?0!==e||1/e==1/t:r(e)&&r(t)},Type:function(e){return null===e?"Null":void 0===e?"Undefined":"function"==typeof e||"object"==typeof e?"Object":"number"==typeof e?"Number":"boolean"==typeof e?"Boolean":"string"==typeof e?"String":void 0},IsPropertyDescriptor:function(e){if("Object"!==this.Type(e))return!1;var t={"[[Configurable]]":!0,"[[Enumerable]]":!0,"[[Get]]":!0,"[[Set]]":!0,"[[Value]]":!0,"[[Writable]]":!0};for(var n in e)if(c(e,n)&&!t[n])return!1;var r=c(e,"[[Value]]"),o=c(e,"[[Get]]")||c(e,"[[Set]]");if(r&&o)throw new TypeError("Property Descriptors may not be both accessor and data descriptors");return!0},IsAccessorDescriptor:function(e){if(void 0===e)return!1;if(!this.IsPropertyDescriptor(e))throw new TypeError("Desc must be a Property Descriptor");return!(!c(e,"[[Get]]")&&!c(e,"[[Set]]"))},IsDataDescriptor:function(e){if(void 0===e)return!1;if(!this.IsPropertyDescriptor(e))throw new TypeError("Desc must be a Property Descriptor");return!(!c(e,"[[Value]]")&&!c(e,"[[Writable]]"))},IsGenericDescriptor:function(e){if(void 0===e)return!1;if(!this.IsPropertyDescriptor(e))throw new TypeError("Desc must be a Property Descriptor");return!this.IsAccessorDescriptor(e)&&!this.IsDataDescriptor(e)},FromPropertyDescriptor:function(e){if(void 0===e)return e;if(!this.IsPropertyDescriptor(e))throw new TypeError("Desc must be a Property Descriptor");if(this.IsDataDescriptor(e))return{value:e["[[Value]]"],writable:!!e["[[Writable]]"],enumerable:!!e["[[Enumerable]]"],configurable:!!e["[[Configurable]]"]};if(this.IsAccessorDescriptor(e))return{get:e["[[Get]]"],set:e["[[Set]]"],enumerable:!!e["[[Enumerable]]"],configurable:!!e["[[Configurable]]"]};throw new TypeError("FromPropertyDescriptor must be called with a fully populated Property Descriptor")},ToPropertyDescriptor:function(e){if("Object"!==this.Type(e))throw new TypeError("ToPropertyDescriptor requires an object");var t={};if(c(e,"enumerable")&&(t["[[Enumerable]]"]=this.ToBoolean(e.enumerable)),c(e,"configurable")&&(t["[[Configurable]]"]=this.ToBoolean(e.configurable)),c(e,"value")&&(t["[[Value]]"]=e.value),c(e,"writable")&&(t["[[Writable]]"]=this.ToBoolean(e.writable)),c(e,"get")){var n=e.get;if(void 0!==n&&!this.IsCallable(n))throw new TypeError("getter must be a function");t["[[Get]]"]=n}if(c(e,"set")){var r=e.set;if(void 0!==r&&!this.IsCallable(r))throw new TypeError("setter must be a function");t["[[Set]]"]=r}if((c(t,"[[Get]]")||c(t,"[[Set]]"))&&(c(t,"[[Value]]")||c(t,"[[Writable]]")))throw new TypeError("Invalid property descriptor. Cannot both specify accessors and a value or writable attribute");return t}};e.exports=l},function(e,t,n){"use strict";var r=Object.prototype.toString,o=n(9),i=n(3),s=function(e,t){var n=t||("[object Date]"===r.call(e)?String:Number);if(n===String||n===Number){var s,u,a=n===String?["toString","valueOf"]:["valueOf","toString"];for(u=0;u=0.10.0" - }, - "homepage": "https://github.com/theturtle32/WebSocket-Node", - "keywords": [ - "websocket", - "websockets", - "socket", - "networking", - "comet", - "push", - "RFC-6455", - "realtime", - "server", - "client" - ], - "license": "Apache-2.0", - "main": "index", - "name": "websocket", - "repository": { - "type": "git", - "url": "git+https://github.com/theturtle32/WebSocket-Node.git" - }, - "scripts": { - "gulp": "gulp", - "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", - "test": "faucet test/unit" - }, - "version": "1.0.28" -} - -},{}],142:[function(require,module,exports){ -(function (Buffer){ -var bs58check = require('bs58check') - -function decodeRaw (buffer, version) { - // check version only if defined - if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') - - // uncompressed - if (buffer.length === 33) { - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: false - } - } - - // invalid length - if (buffer.length !== 34) throw new Error('Invalid WIF length') - - // invalid compression flag - if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') - - return { - version: buffer[0], - privateKey: buffer.slice(1, 33), - compressed: true - } -} - -function encodeRaw (version, privateKey, compressed) { - var result = new Buffer(compressed ? 34 : 33) - - result.writeUInt8(version, 0) - privateKey.copy(result, 1) - - if (compressed) { - result[33] = 0x01 - } - - return result -} - -function decode (string, version) { - return decodeRaw(bs58check.decode(string), version) -} - -function encode (version, privateKey, compressed) { - if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed)) - - return bs58check.encode( - encodeRaw( - version.version, - version.privateKey, - version.compressed - ) - ) -} - -module.exports = { - decode: decode, - decodeRaw: decodeRaw, - encode: encode, - encodeRaw: encodeRaw -} - -}).call(this,require("buffer").Buffer) -},{"bs58check":52,"buffer":149}],143:[function(require,module,exports){ -(function (global){ -'use strict'; - -// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js -// original notice: - -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -function compare(a, b) { - if (a === b) { - return 0; - } - - var x = a.length; - var y = b.length; - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - - if (x < y) { - return -1; - } - if (y < x) { - return 1; - } - return 0; -} -function isBuffer(b) { - if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { - return global.Buffer.isBuffer(b); - } - return !!(b != null && b._isBuffer); -} - -// based on node assert, original notice: - -// http://wiki.commonjs.org/wiki/Unit_Testing/1.0 -// -// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! -// -// Originally from narwhal.js (http://narwhaljs.org) -// Copyright (c) 2009 Thomas Robinson <280north.com> -// -// 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 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 util = require('util/'); -var hasOwn = Object.prototype.hasOwnProperty; -var pSlice = Array.prototype.slice; -var functionsHaveNames = (function () { - return function foo() {}.name === 'foo'; -}()); -function pToString (obj) { - return Object.prototype.toString.call(obj); -} -function isView(arrbuf) { - if (isBuffer(arrbuf)) { - return false; - } - if (typeof global.ArrayBuffer !== 'function') { - return false; - } - if (typeof ArrayBuffer.isView === 'function') { - return ArrayBuffer.isView(arrbuf); - } - if (!arrbuf) { - return false; - } - if (arrbuf instanceof DataView) { - return true; - } - if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { - return true; - } - return false; -} -// 1. The assert module provides functions that throw -// AssertionError's when particular conditions are not met. The -// assert module must conform to the following interface. - -var assert = module.exports = ok; - -// 2. The AssertionError is defined in assert. -// new assert.AssertionError({ message: message, -// actual: actual, -// expected: expected }) - -var regex = /\s*function\s+([^\(\s]*)\s*/; -// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js -function getName(func) { - if (!util.isFunction(func)) { - return; - } - if (functionsHaveNames) { - return func.name; - } - var str = func.toString(); - var match = str.match(regex); - return match && match[1]; -} -assert.AssertionError = function AssertionError(options) { - this.name = 'AssertionError'; - this.actual = options.actual; - this.expected = options.expected; - this.operator = options.operator; - if (options.message) { - this.message = options.message; - this.generatedMessage = false; - } else { - this.message = getMessage(this); - this.generatedMessage = true; - } - var stackStartFunction = options.stackStartFunction || fail; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, stackStartFunction); - } else { - // non v8 browsers so we can have a stacktrace - var err = new Error(); - if (err.stack) { - var out = err.stack; - - // try to strip useless frames - var fn_name = getName(stackStartFunction); - var idx = out.indexOf('\n' + fn_name); - if (idx >= 0) { - // once we have located the function frame - // we need to strip out everything before it (and its line) - var next_line = out.indexOf('\n', idx + 1); - out = out.substring(next_line + 1); - } - - this.stack = out; - } - } -}; - -// assert.AssertionError instanceof Error -util.inherits(assert.AssertionError, Error); - -function truncate(s, n) { - if (typeof s === 'string') { - return s.length < n ? s : s.slice(0, n); - } else { - return s; - } -} -function inspect(something) { - if (functionsHaveNames || !util.isFunction(something)) { - return util.inspect(something); - } - var rawname = getName(something); - var name = rawname ? ': ' + rawname : ''; - return '[Function' + name + ']'; -} -function getMessage(self) { - return truncate(inspect(self.actual), 128) + ' ' + - self.operator + ' ' + - truncate(inspect(self.expected), 128); -} - -// At present only the three keys mentioned above are used and -// understood by the spec. Implementations or sub modules can pass -// other keys to the AssertionError's constructor - they will be -// ignored. - -// 3. All of the following functions must throw an AssertionError -// when a corresponding condition is not met, with a message that -// may be undefined if not provided. All assertion methods provide -// both the actual and expected values to the assertion error for -// display purposes. - -function fail(actual, expected, message, operator, stackStartFunction) { - throw new assert.AssertionError({ - message: message, - actual: actual, - expected: expected, - operator: operator, - stackStartFunction: stackStartFunction - }); -} - -// EXTENSION! allows for well behaved errors defined elsewhere. -assert.fail = fail; - -// 4. Pure assertion tests whether a value is truthy, as determined -// by !!guard. -// assert.ok(guard, message_opt); -// This statement is equivalent to assert.equal(true, !!guard, -// message_opt);. To test strictly for the value true, use -// assert.strictEqual(true, guard, message_opt);. - -function ok(value, message) { - if (!value) fail(value, true, message, '==', assert.ok); -} -assert.ok = ok; - -// 5. The equality assertion tests shallow, coercive equality with -// ==. -// assert.equal(actual, expected, message_opt); - -assert.equal = function equal(actual, expected, message) { - if (actual != expected) fail(actual, expected, message, '==', assert.equal); -}; - -// 6. The non-equality assertion tests for whether two objects are not equal -// with != assert.notEqual(actual, expected, message_opt); - -assert.notEqual = function notEqual(actual, expected, message) { - if (actual == expected) { - fail(actual, expected, message, '!=', assert.notEqual); - } -}; - -// 7. The equivalence assertion tests a deep equality relation. -// assert.deepEqual(actual, expected, message_opt); - -assert.deepEqual = function deepEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'deepEqual', assert.deepEqual); - } -}; - -assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { - if (!_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); - } -}; - -function _deepEqual(actual, expected, strict, memos) { - // 7.1. All identical values are equivalent, as determined by ===. - if (actual === expected) { - return true; - } else if (isBuffer(actual) && isBuffer(expected)) { - return compare(actual, expected) === 0; - - // 7.2. If the expected value is a Date object, the actual value is - // equivalent if it is also a Date object that refers to the same time. - } else if (util.isDate(actual) && util.isDate(expected)) { - return actual.getTime() === expected.getTime(); - - // 7.3 If the expected value is a RegExp object, the actual value is - // equivalent if it is also a RegExp object with the same source and - // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). - } else if (util.isRegExp(actual) && util.isRegExp(expected)) { - return actual.source === expected.source && - actual.global === expected.global && - actual.multiline === expected.multiline && - actual.lastIndex === expected.lastIndex && - actual.ignoreCase === expected.ignoreCase; - - // 7.4. Other pairs that do not both pass typeof value == 'object', - // equivalence is determined by ==. - } else if ((actual === null || typeof actual !== 'object') && - (expected === null || typeof expected !== 'object')) { - return strict ? actual === expected : actual == expected; - - // If both values are instances of typed arrays, wrap their underlying - // ArrayBuffers in a Buffer each to increase performance - // This optimization requires the arrays to have the same type as checked by - // Object.prototype.toString (aka pToString). Never perform binary - // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their - // bit patterns are not identical. - } else if (isView(actual) && isView(expected) && - pToString(actual) === pToString(expected) && - !(actual instanceof Float32Array || - actual instanceof Float64Array)) { - return compare(new Uint8Array(actual.buffer), - new Uint8Array(expected.buffer)) === 0; - - // 7.5 For all other Object pairs, including Array objects, equivalence is - // determined by having the same number of owned properties (as verified - // with Object.prototype.hasOwnProperty.call), the same set of keys - // (although not necessarily the same order), equivalent values for every - // corresponding key, and an identical 'prototype' property. Note: this - // accounts for both named and indexed properties on Arrays. - } else if (isBuffer(actual) !== isBuffer(expected)) { - return false; - } else { - memos = memos || {actual: [], expected: []}; - - var actualIndex = memos.actual.indexOf(actual); - if (actualIndex !== -1) { - if (actualIndex === memos.expected.indexOf(expected)) { - return true; - } - } - - memos.actual.push(actual); - memos.expected.push(expected); - - return objEquiv(actual, expected, strict, memos); - } -} - -function isArguments(object) { - return Object.prototype.toString.call(object) == '[object Arguments]'; -} - -function objEquiv(a, b, strict, actualVisitedObjects) { - if (a === null || a === undefined || b === null || b === undefined) - return false; - // if one is a primitive, the other must be same - if (util.isPrimitive(a) || util.isPrimitive(b)) - return a === b; - if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) - return false; - var aIsArgs = isArguments(a); - var bIsArgs = isArguments(b); - if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) - return false; - if (aIsArgs) { - a = pSlice.call(a); - b = pSlice.call(b); - return _deepEqual(a, b, strict); - } - var ka = objectKeys(a); - var kb = objectKeys(b); - var key, i; - // having the same number of owned properties (keys incorporates - // hasOwnProperty) - if (ka.length !== kb.length) - return false; - //the same set of keys (although not necessarily the same order), - ka.sort(); - kb.sort(); - //~~~cheap key test - for (i = ka.length - 1; i >= 0; i--) { - if (ka[i] !== kb[i]) - return false; - } - //equivalent values for every corresponding key, and - //~~~possibly expensive deep test - for (i = ka.length - 1; i >= 0; i--) { - key = ka[i]; - if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) - return false; - } - return true; -} - -// 8. The non-equivalence assertion tests for any deep inequality. -// assert.notDeepEqual(actual, expected, message_opt); - -assert.notDeepEqual = function notDeepEqual(actual, expected, message) { - if (_deepEqual(actual, expected, false)) { - fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); - } -}; - -assert.notDeepStrictEqual = notDeepStrictEqual; -function notDeepStrictEqual(actual, expected, message) { - if (_deepEqual(actual, expected, true)) { - fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); - } -} - - -// 9. The strict equality assertion tests strict equality, as determined by ===. -// assert.strictEqual(actual, expected, message_opt); - -assert.strictEqual = function strictEqual(actual, expected, message) { - if (actual !== expected) { - fail(actual, expected, message, '===', assert.strictEqual); - } -}; - -// 10. The strict non-equality assertion tests for strict inequality, as -// determined by !==. assert.notStrictEqual(actual, expected, message_opt); - -assert.notStrictEqual = function notStrictEqual(actual, expected, message) { - if (actual === expected) { - fail(actual, expected, message, '!==', assert.notStrictEqual); - } -}; - -function expectedException(actual, expected) { - if (!actual || !expected) { - return false; - } - - if (Object.prototype.toString.call(expected) == '[object RegExp]') { - return expected.test(actual); - } - - try { - if (actual instanceof expected) { - return true; - } - } catch (e) { - // Ignore. The instanceof check doesn't work for arrow functions. - } - - if (Error.isPrototypeOf(expected)) { - return false; - } - - return expected.call({}, actual) === true; -} - -function _tryBlock(block) { - var error; - try { - block(); - } catch (e) { - error = e; - } - return error; -} - -function _throws(shouldThrow, block, expected, message) { - var actual; - - if (typeof block !== 'function') { - throw new TypeError('"block" argument must be a function'); - } - - if (typeof expected === 'string') { - message = expected; - expected = null; - } - - actual = _tryBlock(block); - - message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + - (message ? ' ' + message : '.'); - - if (shouldThrow && !actual) { - fail(actual, expected, 'Missing expected exception' + message); - } - - var userProvidedMessage = typeof message === 'string'; - var isUnwantedException = !shouldThrow && util.isError(actual); - var isUnexpectedException = !shouldThrow && actual && !expected; - - if ((isUnwantedException && - userProvidedMessage && - expectedException(actual, expected)) || - isUnexpectedException) { - fail(actual, expected, 'Got unwanted exception' + message); - } - - if ((shouldThrow && actual && expected && - !expectedException(actual, expected)) || (!shouldThrow && actual)) { - throw actual; - } -} - -// 11. Expected to throw an error: -// assert.throws(block, Error_opt, message_opt); - -assert.throws = function(block, /*optional*/error, /*optional*/message) { - _throws(true, block, error, message); -}; - -// EXTENSION! This is annoying to write outside this module. -assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { - _throws(false, block, error, message); -}; - -assert.ifError = function(err) { if (err) throw err; }; - -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - if (hasOwn.call(obj, key)) keys.push(key); - } - return keys; -}; - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"util/":146}],144:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],145:[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'; -} -},{}],146:[function(require,module,exports){ -(function (process,global){ -// 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. - -var formatRegExp = /%[sdj%]/g; -exports.format = function(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; -}; - - -// Mark that a method should not be used. -// Returns a modified function which warns once by default. -// If --no-deprecation is set, then it is a no-op. -exports.deprecate = function(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global.process)) { - return function() { - return exports.deprecate(fn, msg).apply(this, arguments); - }; - } - - if (process.noDeprecation === true) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (process.throwDeprecation) { - throw new Error(msg); - } else if (process.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -}; - - -var debugs = {}; -var debugEnviron; -exports.debuglog = function(set) { - if (isUndefined(debugEnviron)) - debugEnviron = process.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = process.pid; - debugs[set] = function() { - var msg = exports.format.apply(exports, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; -}; - - -/** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ -/* legacy: obj, showHidden, depth, colors*/ -function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - exports._extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); -} -exports.inspect = inspect; - - -// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics -inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] -}; - -// Don't use 'blue' not visible on cmd.exe -inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' -}; - - -function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; - - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } -} - - -function stylizeNoColor(str, styleType) { - return str; -} - - -function arrayToHash(array) { - var hash = {}; - - array.forEach(function(val, idx) { - hash[val] = true; - }); - - return hash; -} - - -function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== exports.inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } - - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } - - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); - - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } - - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } - - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } - - var base = '', array = false, braces = ['{', '}']; - - // Make Array say that they are Array - if (isArray(value)) { - array = true; - braces = ['[', ']']; - } - - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } - - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } - - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } - - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } - - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } - - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } - - ctx.seen.push(value); - - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } - - ctx.seen.pop(); - - return reduceToSingleString(output, base, braces); -} - - -function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); -} - - -function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; -} - - -function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; -} - - -function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } - - return name + ': ' + str; -} - - -function reduceToSingleString(output, base, braces) { - var numLinesEst = 0; - var length = output.reduce(function(prev, cur) { - numLinesEst++; - if (cur.indexOf('\n') >= 0) numLinesEst++; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } - - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; -} - - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. -function isArray(ar) { - return Array.isArray(ar); -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = require('./support/isBuffer'); - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - - -function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); -} - - -var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; - -// 26 Feb 16:19:34 -function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); -} - - -// log is just a thin wrapper to console.log that prepends a timestamp -exports.log = function() { - console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); -}; - - -/** - * Inherit the prototype methods from one constructor into another. - * - * The Function.prototype.inherits from lang.js rewritten as a standalone - * function (not on Function.prototype). NOTE: If this file is to be loaded - * during bootstrapping this function needs to be rewritten using some native - * functions as prototype setup using normal JavaScript does not work as - * expected during bootstrapping (see mirror.js in r114903). - * - * @param {function} ctor Constructor function which needs to inherit the - * prototype. - * @param {function} superCtor Constructor function to inherit prototype from. - */ -exports.inherits = require('inherits'); - -exports._extend = function(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; - - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; -}; - -function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); -} - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./support/isBuffer":145,"_process":157,"inherits":144}],147:[function(require,module,exports){ -'use strict' - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - for (var i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk( - uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) - )) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - -},{}],148:[function(require,module,exports){ - -},{}],149:[function(require,module,exports){ -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -/* eslint-disable no-proto */ - -'use strict' - -var base64 = require('base64-js') -var ieee754 = require('ieee754') - -exports.Buffer = Buffer -exports.SlowBuffer = SlowBuffer -exports.INSPECT_MAX_BYTES = 50 - -var K_MAX_LENGTH = 0x7fffffff -exports.kMaxLength = K_MAX_LENGTH - -/** - * If `Buffer.TYPED_ARRAY_SUPPORT`: - * === true Use Uint8Array implementation (fastest) - * === false Print warning and recommend using `buffer` v4.x which has an Object - * implementation (most compatible, even IE6) - * - * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, - * Opera 11.6+, iOS 4.2+. - * - * We report that the browser does not support typed arrays if the are not subclassable - * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` - * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support - * for __proto__ and has a buggy typed array implementation. - */ -Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() - -if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && - typeof console.error === 'function') { - console.error( - 'This browser lacks typed array (Uint8Array) support which is required by ' + - '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' - ) -} - -function typedArraySupport () { - // Can typed array instances can be augmented? - try { - var arr = new Uint8Array(1) - arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} - return arr.foo() === 42 - } catch (e) { - return false - } -} - -Object.defineProperty(Buffer.prototype, 'parent', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.buffer - } -}) - -Object.defineProperty(Buffer.prototype, 'offset', { - enumerable: true, - get: function () { - if (!Buffer.isBuffer(this)) return undefined - return this.byteOffset - } -}) - -function createBuffer (length) { - if (length > K_MAX_LENGTH) { - throw new RangeError('The value "' + length + '" is invalid for option "size"') - } - // Return an augmented `Uint8Array` instance - var buf = new Uint8Array(length) - buf.__proto__ = Buffer.prototype - return buf -} - -/** - * The Buffer constructor returns instances of `Uint8Array` that have their - * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of - * `Uint8Array`, so the returned instances will have all the node `Buffer` methods - * and the `Uint8Array` methods. Square bracket notation works as expected -- it - * returns a single octet. - * - * The `Uint8Array` prototype remains unmodified. - */ - -function Buffer (arg, encodingOrOffset, length) { - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ) - } - return allocUnsafe(arg) - } - return from(arg, encodingOrOffset, length) -} - -// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 -if (typeof Symbol !== 'undefined' && Symbol.species != null && - Buffer[Symbol.species] === Buffer) { - Object.defineProperty(Buffer, Symbol.species, { - value: null, - configurable: true, - enumerable: false, - writable: false - }) -} - -Buffer.poolSize = 8192 // not used by this implementation - -function from (value, encodingOrOffset, length) { - if (typeof value === 'string') { - return fromString(value, encodingOrOffset) - } - - if (ArrayBuffer.isView(value)) { - return fromArrayLike(value) - } - - if (value == null) { - throw TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) - } - - if (isInstance(value, ArrayBuffer) || - (value && isInstance(value.buffer, ArrayBuffer))) { - return fromArrayBuffer(value, encodingOrOffset, length) - } - - if (typeof value === 'number') { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ) - } - - var valueOf = value.valueOf && value.valueOf() - if (valueOf != null && valueOf !== value) { - return Buffer.from(valueOf, encodingOrOffset, length) - } - - var b = fromObject(value) - if (b) return b - - if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && - typeof value[Symbol.toPrimitive] === 'function') { - return Buffer.from( - value[Symbol.toPrimitive]('string'), encodingOrOffset, length - ) - } - - throw new TypeError( - 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + - 'or Array-like Object. Received type ' + (typeof value) - ) -} - -/** - * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError - * if value is a number. - * Buffer.from(str[, encoding]) - * Buffer.from(array) - * Buffer.from(buffer) - * Buffer.from(arrayBuffer[, byteOffset[, length]]) - **/ -Buffer.from = function (value, encodingOrOffset, length) { - return from(value, encodingOrOffset, length) -} - -// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: -// https://github.com/feross/buffer/pull/148 -Buffer.prototype.__proto__ = Uint8Array.prototype -Buffer.__proto__ = Uint8Array - -function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be of type number') - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"') - } -} - -function alloc (size, fill, encoding) { - assertSize(size) - if (size <= 0) { - return createBuffer(size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(size).fill(fill, encoding) - : createBuffer(size).fill(fill) - } - return createBuffer(size) -} - -/** - * Creates a new filled Buffer instance. - * alloc(size[, fill[, encoding]]) - **/ -Buffer.alloc = function (size, fill, encoding) { - return alloc(size, fill, encoding) -} - -function allocUnsafe (size) { - assertSize(size) - return createBuffer(size < 0 ? 0 : checked(size) | 0) -} - -/** - * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. - * */ -Buffer.allocUnsafe = function (size) { - return allocUnsafe(size) -} -/** - * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. - */ -Buffer.allocUnsafeSlow = function (size) { - return allocUnsafe(size) -} - -function fromString (string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8' - } - - if (!Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - - var length = byteLength(string, encoding) | 0 - var buf = createBuffer(length) - - var actual = buf.write(string, encoding) - - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - buf = buf.slice(0, actual) - } - - return buf -} - -function fromArrayLike (array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0 - var buf = createBuffer(length) - for (var i = 0; i < length; i += 1) { - buf[i] = array[i] & 255 - } - return buf -} - -function fromArrayBuffer (array, byteOffset, length) { - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds') - } - - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('"length" is outside of buffer bounds') - } - - var buf - if (byteOffset === undefined && length === undefined) { - buf = new Uint8Array(array) - } else if (length === undefined) { - buf = new Uint8Array(array, byteOffset) - } else { - buf = new Uint8Array(array, byteOffset, length) - } - - // Return an augmented `Uint8Array` instance - buf.__proto__ = Buffer.prototype - return buf -} - -function fromObject (obj) { - if (Buffer.isBuffer(obj)) { - var len = checked(obj.length) | 0 - var buf = createBuffer(len) - - if (buf.length === 0) { - return buf - } - - obj.copy(buf, 0, 0, len) - return buf - } - - if (obj.length !== undefined) { - if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { - return createBuffer(0) - } - return fromArrayLike(obj) - } - - if (obj.type === 'Buffer' && Array.isArray(obj.data)) { - return fromArrayLike(obj.data) - } -} - -function checked (length) { - // Note: cannot use `length < K_MAX_LENGTH` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= K_MAX_LENGTH) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') - } - return length | 0 -} - -function SlowBuffer (length) { - if (+length != length) { // eslint-disable-line eqeqeq - length = 0 - } - return Buffer.alloc(+length) -} - -Buffer.isBuffer = function isBuffer (b) { - return b != null && b._isBuffer === true && - b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false -} - -Buffer.compare = function compare (a, b) { - if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength) - if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength) - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ) - } - - if (a === b) return 0 - - var x = a.length - var y = b.length - - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i] - y = b[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -Buffer.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } -} - -Buffer.concat = function concat (list, length) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - - if (list.length === 0) { - return Buffer.alloc(0) - } - - var i - if (length === undefined) { - length = 0 - for (i = 0; i < list.length; ++i) { - length += list[i].length - } - } - - var buffer = Buffer.allocUnsafe(length) - var pos = 0 - for (i = 0; i < list.length; ++i) { - var buf = list[i] - if (isInstance(buf, Uint8Array)) { - buf = Buffer.from(buf) - } - if (!Buffer.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos) - pos += buf.length - } - return buffer -} - -function byteLength (string, encoding) { - if (Buffer.isBuffer(string)) { - return string.length - } - if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + - 'Received type ' + typeof string - ) - } - - var len = string.length - var mustMatch = (arguments.length > 2 && arguments[2] === true) - if (!mustMatch && len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 - } - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} -Buffer.byteLength = byteLength - -function slowToString (encoding, start, end) { - var loweredCase = false - - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. - - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0 - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } - - if (end === undefined || end > this.length) { - end = this.length - } - - if (end <= 0) { - return '' - } - - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0 - start >>>= 0 - - if (end <= start) { - return '' - } - - if (!encoding) encoding = 'utf8' - - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) - - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) - - case 'ascii': - return asciiSlice(this, start, end) - - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) - - case 'base64': - return base64Slice(this, start, end) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase() - loweredCase = true - } - } -} - -// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) -// to detect a Buffer instance. It's not possible to use `instanceof Buffer` -// reliably in a browserify context because there could be multiple different -// copies of the 'buffer' package in use. This method works even for Buffer -// instances that were created from another copy of the `buffer` package. -// See: https://github.com/feross/buffer/issues/154 -Buffer.prototype._isBuffer = true - -function swap (b, n, m) { - var i = b[n] - b[n] = b[m] - b[m] = i -} - -Buffer.prototype.swap16 = function swap16 () { - var len = this.length - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1) - } - return this -} - -Buffer.prototype.swap32 = function swap32 () { - var len = this.length - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3) - swap(this, i + 1, i + 2) - } - return this -} - -Buffer.prototype.swap64 = function swap64 () { - var len = this.length - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7) - swap(this, i + 1, i + 6) - swap(this, i + 2, i + 5) - swap(this, i + 3, i + 4) - } - return this -} - -Buffer.prototype.toString = function toString () { - var length = this.length - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) -} - -Buffer.prototype.toLocaleString = Buffer.prototype.toString - -Buffer.prototype.equals = function equals (b) { - if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer.compare(this, b) === 0 -} - -Buffer.prototype.inspect = function inspect () { - var str = '' - var max = exports.INSPECT_MAX_BYTES - str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim() - if (this.length > max) str += ' ... ' - return '' -} - -Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer.from(target, target.offset, target.byteLength) - } - if (!Buffer.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. ' + - 'Received type ' + (typeof target) - ) - } - - if (start === undefined) { - start = 0 - } - if (end === undefined) { - end = target ? target.length : 0 - } - if (thisStart === undefined) { - thisStart = 0 - } - if (thisEnd === undefined) { - thisEnd = this.length - } - - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } - - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } - - start >>>= 0 - end >>>= 0 - thisStart >>>= 0 - thisEnd >>>= 0 - - if (this === target) return 0 - - var x = thisEnd - thisStart - var y = end - start - var len = Math.min(x, y) - - var thisCopy = this.slice(thisStart, thisEnd) - var targetCopy = target.slice(start, end) - - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i] - y = targetCopy[i] - break - } - } - - if (x < y) return -1 - if (y < x) return 1 - return 0 -} - -// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, -// OR the last index of `val` in `buffer` at offset <= `byteOffset`. -// -// Arguments: -// - buffer - a Buffer to search -// - val - a string, Buffer, or number -// - byteOffset - an index into `buffer`; will be clamped to an int32 -// - encoding - an optional encoding, relevant is val is a string -// - dir - true for indexOf, false for lastIndexOf -function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset - byteOffset = 0 - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000 - } - byteOffset = +byteOffset // Coerce to Number. - if (numberIsNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1) - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1 - } else if (byteOffset < 0) { - if (dir) byteOffset = 0 - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer.from(val, encoding) - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (Buffer.isBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF // Search for a byte value [0-255] - if (typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } - - throw new TypeError('val must be string, number or Buffer') -} - -function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1 - var arrLength = arr.length - var valLength = val.length - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase() - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2 - arrLength /= 2 - valLength /= 2 - byteOffset /= 2 - } - } - - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } - - var i - if (dir) { - var foundIndex = -1 - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex - foundIndex = -1 - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength - for (i = byteOffset; i >= 0; i--) { - var found = true - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false - break - } - } - if (found) return i - } - } - - return -1 -} - -Buffer.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 -} - -Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) -} - -Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) -} - -function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0 - var remaining = buf.length - offset - if (!length) { - length = remaining - } else { - length = Number(length) - if (length > remaining) { - length = remaining - } - } - - var strLen = string.length - - if (length > strLen / 2) { - length = strLen / 2 - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16) - if (numberIsNaN(parsed)) return i - buf[offset + i] = parsed - } - return i -} - -function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) -} - -function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) -} - -function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) -} - -function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) -} - -function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) -} - -Buffer.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8' - length = this.length - offset = 0 - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset - length = this.length - offset = 0 - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset >>> 0 - if (isFinite(length)) { - length = length >>> 0 - if (encoding === undefined) encoding = 'utf8' - } else { - encoding = length - length = undefined - } - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } - - var remaining = this.length - offset - if (length === undefined || length > remaining) length = remaining - - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } - - if (!encoding) encoding = 'utf8' - - var loweredCase = false - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) - - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) - - case 'ascii': - return asciiWrite(this, string, offset, length) - - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) - - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) - - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) - - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase() - loweredCase = true - } - } -} - -Buffer.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } -} - -function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf) - } else { - return base64.fromByteArray(buf.slice(start, end)) - } -} - -function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end) - var res = [] - - var i = start - while (i < end) { - var firstByte = buf[i] - var codePoint = null - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1 - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte - } - break - case 2: - secondByte = buf[i + 1] - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint - } - } - break - case 3: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint - } - } - break - case 4: - secondByte = buf[i + 1] - thirdByte = buf[i + 2] - fourthByte = buf[i + 3] - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD - bytesPerSequence = 1 - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000 - res.push(codePoint >>> 10 & 0x3FF | 0xD800) - codePoint = 0xDC00 | codePoint & 0x3FF - } - - res.push(codePoint) - i += bytesPerSequence - } - - return decodeCodePointsArray(res) -} - -// Based on http://stackoverflow.com/a/22747272/680742, the browser with -// the lowest limit is Chrome, with 0x10000 args. -// We go 1 magnitude less, for safety -var MAX_ARGUMENTS_LENGTH = 0x1000 - -function decodeCodePointsArray (codePoints) { - var len = codePoints.length - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } - - // Decode in chunks to avoid "call stack size exceeded". - var res = '' - var i = 0 - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ) - } - return res -} - -function asciiSlice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F) - } - return ret -} - -function latin1Slice (buf, start, end) { - var ret = '' - end = Math.min(buf.length, end) - - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]) - } - return ret -} - -function hexSlice (buf, start, end) { - var len = buf.length - - if (!start || start < 0) start = 0 - if (!end || end < 0 || end > len) end = len - - var out = '' - for (var i = start; i < end; ++i) { - out += toHex(buf[i]) - } - return out -} - -function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end) - var res = '' - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) - } - return res -} - -Buffer.prototype.slice = function slice (start, end) { - var len = this.length - start = ~~start - end = end === undefined ? len : ~~end - - if (start < 0) { - start += len - if (start < 0) start = 0 - } else if (start > len) { - start = len - } - - if (end < 0) { - end += len - if (end < 0) end = 0 - } else if (end > len) { - end = len - } - - if (end < start) end = start - - var newBuf = this.subarray(start, end) - // Return an augmented `Uint8Array` instance - newBuf.__proto__ = Buffer.prototype - return newBuf -} - -/* - * Need to make sure that buffer isn't trying to write out of bounds. - */ -function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') -} - -Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - - return val -} - -Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - checkOffset(offset, byteLength, this.length) - } - - var val = this[offset + --byteLength] - var mul = 1 - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul - } - - return val -} - -Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - return this[offset] -} - -Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return this[offset] | (this[offset + 1] << 8) -} - -Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - return (this[offset] << 8) | this[offset + 1] -} - -Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) -} - -Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) -} - -Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var val = this[offset] - var mul = 1 - var i = 0 - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) checkOffset(offset, byteLength, this.length) - - var i = byteLength - var mul = 1 - var val = this[offset + --i] - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul - } - mul *= 0x80 - - if (val >= mul) val -= Math.pow(2, 8 * byteLength) - - return val -} - -Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 1, this.length) - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) -} - -Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset] | (this[offset + 1] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 2, this.length) - var val = this[offset + 1] | (this[offset] << 8) - return (val & 0x8000) ? val | 0xFFFF0000 : val -} - -Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) -} - -Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) -} - -Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, true, 23, 4) -} - -Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 4, this.length) - return ieee754.read(this, offset, false, 23, 4) -} - -Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, true, 52, 8) -} - -Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - offset = offset >>> 0 - if (!noAssert) checkOffset(offset, 8, this.length) - return ieee754.read(this, offset, false, 52, 8) -} - -function checkInt (buf, value, offset, ext, max, min) { - if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') -} - -Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var mul = 1 - var i = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - byteLength = byteLength >>> 0 - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1 - checkInt(this, value, offset, byteLength, maxBytes, 0) - } - - var i = byteLength - 1 - var mul = 1 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset + 3] = (value >>> 24) - this[offset + 2] = (value >>> 16) - this[offset + 1] = (value >>> 8) - this[offset] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = 0 - var mul = 1 - var sub = 0 - this[offset] = value & 0xFF - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - var limit = Math.pow(2, (8 * byteLength) - 1) - - checkInt(this, value, offset, byteLength, limit - 1, -limit) - } - - var i = byteLength - 1 - var mul = 1 - var sub = 0 - this[offset + i] = value & 0xFF - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1 - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF - } - - return offset + byteLength -} - -Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) - if (value < 0) value = 0xff + value + 1 - this[offset] = (value & 0xff) - return offset + 1 -} - -Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - return offset + 2 -} - -Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) - this[offset] = (value >>> 8) - this[offset + 1] = (value & 0xff) - return offset + 2 -} - -Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - this[offset] = (value & 0xff) - this[offset + 1] = (value >>> 8) - this[offset + 2] = (value >>> 16) - this[offset + 3] = (value >>> 24) - return offset + 4 -} - -Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) - if (value < 0) value = 0xffffffff + value + 1 - this[offset] = (value >>> 24) - this[offset + 1] = (value >>> 16) - this[offset + 2] = (value >>> 8) - this[offset + 3] = (value & 0xff) - return offset + 4 -} - -function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') -} - -function writeFloat (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) - } - ieee754.write(buf, value, offset, littleEndian, 23, 4) - return offset + 4 -} - -Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) -} - -function writeDouble (buf, value, offset, littleEndian, noAssert) { - value = +value - offset = offset >>> 0 - if (!noAssert) { - checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) - } - ieee754.write(buf, value, offset, littleEndian, 52, 8) - return offset + 8 -} - -Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) -} - -Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) -} - -// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) -Buffer.prototype.copy = function copy (target, targetStart, start, end) { - if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') - if (!start) start = 0 - if (!end && end !== 0) end = this.length - if (targetStart >= target.length) targetStart = target.length - if (!targetStart) targetStart = 0 - if (end > 0 && end < start) end = start - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('Index out of range') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start - } - - var len = end - start - - if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { - // Use built-in when available, missing from IE11 - this.copyWithin(targetStart, start, end) - } else if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (var i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start] - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ) - } - - return len -} - -// Usage: -// buffer.fill(number[, offset[, end]]) -// buffer.fill(buffer[, offset[, end]]) -// buffer.fill(string[, offset[, end]][, encoding]) -Buffer.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start - start = 0 - end = this.length - } else if (typeof end === 'string') { - encoding = end - end = this.length - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - if (val.length === 1) { - var code = val.charCodeAt(0) - if ((encoding === 'utf8' && code < 128) || - encoding === 'latin1') { - // Fast path: If `val` fits into a single byte, use that numeric value. - val = code - } - } - } else if (typeof val === 'number') { - val = val & 255 - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } - - start = start >>> 0 - end = end === undefined ? this.length : end >>> 0 - - if (!val) val = 0 - - var i - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val - } - } else { - var bytes = Buffer.isBuffer(val) - ? val - : Buffer.from(val, encoding) - var len = bytes.length - if (len === 0) { - throw new TypeError('The value "' + val + - '" is invalid for argument "value"') - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len] - } - } - - return this -} - -// HELPER FUNCTIONS -// ================ - -var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - -function base64clean (str) { - // Node takes equal signs as end of the Base64 encoding - str = str.split('=')[0] - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = str.trim().replace(INVALID_BASE64_RE, '') - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '=' - } - return str -} - -function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) -} - -function utf8ToBytes (string, units) { - units = units || Infinity - var codePoint - var length = string.length - var leadSurrogate = null - var bytes = [] - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i) - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - continue - } - - // valid lead - leadSurrogate = codePoint - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - leadSurrogate = codePoint - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) - } - - leadSurrogate = null - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint) - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ) - } else { - throw new Error('Invalid code point') - } - } - - return bytes -} - -function asciiToBytes (str) { - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF) - } - return byteArray -} - -function utf16leToBytes (str, units) { - var c, hi, lo - var byteArray = [] - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i) - hi = c >> 8 - lo = c % 256 - byteArray.push(lo) - byteArray.push(hi) - } - - return byteArray -} - -function base64ToBytes (str) { - return base64.toByteArray(base64clean(str)) -} - -function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i] - } - return i -} - -// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass -// the `instanceof` check but they should be treated as of that type. -// See: https://github.com/feross/buffer/issues/166 -function isInstance (obj, type) { - return obj instanceof type || - (obj != null && obj.constructor != null && obj.constructor.name != null && - obj.constructor.name === type.name) -} -function numberIsNaN (obj) { - // For IE11 support - return obj !== obj // eslint-disable-line no-self-compare -} - -},{"base64-js":147,"ieee754":152}],150:[function(require,module,exports){ -(function (Buffer){ -// 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. - -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. - -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; - -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; - -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; - -function isNullOrUndefined(arg) { - return arg == null; -} -exports.isNullOrUndefined = isNullOrUndefined; - -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; - -function isString(arg) { - return typeof arg === 'string'; -} -exports.isString = isString; - -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; - -function isUndefined(arg) { - return arg === void 0; -} -exports.isUndefined = isUndefined; - -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; - -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; - -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; - -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; - -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; - -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; - -exports.isBuffer = Buffer.isBuffer; - -function objectToString(o) { - return Object.prototype.toString.call(o); -} - -}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) -},{"../../is-buffer/index.js":154}],151:[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. - -var objectCreate = Object.create || objectCreatePolyfill -var objectKeys = Object.keys || objectKeysPolyfill -var bind = Function.prototype.bind || functionBindPolyfill - -function EventEmitter() { - if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) { - this._events = objectCreate(null); - this._eventsCount = 0; - } - - this._maxListeners = this._maxListeners || undefined; -} -module.exports = EventEmitter; - -// Backwards-compat with node 0.10.x -EventEmitter.EventEmitter = EventEmitter; - -EventEmitter.prototype._events = undefined; -EventEmitter.prototype._maxListeners = undefined; - -// By default EventEmitters will print a warning if more than 10 listeners are -// added to it. This is a useful default which helps finding memory leaks. -var defaultMaxListeners = 10; - -var hasDefineProperty; -try { - var o = {}; - if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 }); - hasDefineProperty = o.x === 0; -} catch (err) { hasDefineProperty = false } -if (hasDefineProperty) { - Object.defineProperty(EventEmitter, 'defaultMaxListeners', { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - // check whether the input is a positive number (whose value is zero or - // greater and not a NaN). - if (typeof arg !== 'number' || arg < 0 || arg !== arg) - throw new TypeError('"defaultMaxListeners" must be a positive number'); - defaultMaxListeners = arg; - } - }); -} else { - EventEmitter.defaultMaxListeners = defaultMaxListeners; -} - -// Obviously not all Emitters should be limited to 10. This function allows -// that to be increased. Set to zero for unlimited. -EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== 'number' || n < 0 || isNaN(n)) - throw new TypeError('"n" argument must be a positive number'); - this._maxListeners = n; - return this; -}; - -function $getMaxListeners(that) { - if (that._maxListeners === undefined) - return EventEmitter.defaultMaxListeners; - return that._maxListeners; -} - -EventEmitter.prototype.getMaxListeners = function getMaxListeners() { - return $getMaxListeners(this); -}; - -// These standalone emit* functions are used to optimize calling of event -// handlers for fast cases because emit() itself often has a variable number of -// arguments and can be deoptimized because of that. These functions always have -// the same number of arguments and thus do not get deoptimized, so the code -// inside them can execute faster. -function emitNone(handler, isFn, self) { - if (isFn) - handler.call(self); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self); - } -} -function emitOne(handler, isFn, self, arg1) { - if (isFn) - handler.call(self, arg1); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1); - } -} -function emitTwo(handler, isFn, self, arg1, arg2) { - if (isFn) - handler.call(self, arg1, arg2); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2); - } -} -function emitThree(handler, isFn, self, arg1, arg2, arg3) { - if (isFn) - handler.call(self, arg1, arg2, arg3); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].call(self, arg1, arg2, arg3); - } -} - -function emitMany(handler, isFn, self, args) { - if (isFn) - handler.apply(self, args); - else { - var len = handler.length; - var listeners = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - listeners[i].apply(self, args); - } -} - -EventEmitter.prototype.emit = function emit(type) { - var er, handler, len, args, i, events; - var doError = (type === 'error'); - - events = this._events; - if (events) - doError = (doError && events.error == null); - else if (!doError) - return false; - - // If there is no 'error' event listener then throw. - if (doError) { - if (arguments.length > 1) - er = arguments[1]; - if (er instanceof Error) { - throw er; // Unhandled 'error' event - } else { - // At least give some kind of context to the user - var err = new Error('Unhandled "error" event. (' + er + ')'); - err.context = er; - throw err; - } - return false; - } - - handler = events[type]; - - if (!handler) - return false; - - var isFn = typeof handler === 'function'; - len = arguments.length; - switch (len) { - // fast cases - case 1: - emitNone(handler, isFn, this); - break; - case 2: - emitOne(handler, isFn, this, arguments[1]); - break; - case 3: - emitTwo(handler, isFn, this, arguments[1], arguments[2]); - break; - case 4: - emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); - break; - // slower - default: - args = new Array(len - 1); - for (i = 1; i < len; i++) - args[i - 1] = arguments[i]; - emitMany(handler, isFn, this, args); - } - - return true; -}; - -function _addListener(target, type, listener, prepend) { - var m; - var events; - var existing; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = target._events; - if (!events) { - events = target._events = objectCreate(null); - target._eventsCount = 0; - } else { - // To avoid recursion in the case that type === "newListener"! Before - // adding it to the listeners, first emit "newListener". - if (events.newListener) { - target.emit('newListener', type, - listener.listener ? listener.listener : listener); - - // Re-assign `events` because a newListener handler could have caused the - // this._events to be assigned to a new object - events = target._events; - } - existing = events[type]; - } - - if (!existing) { - // Optimize the case of one listener. Don't need the extra array object. - existing = events[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === 'function') { - // Adding the second element, need to change to array. - existing = events[type] = - prepend ? [listener, existing] : [existing, listener]; - } else { - // If we've already got an array, just append. - if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - } - - // Check for listener leak - if (!existing.warned) { - m = $getMaxListeners(target); - if (m && m > 0 && existing.length > m) { - existing.warned = true; - var w = new Error('Possible EventEmitter memory leak detected. ' + - existing.length + ' "' + String(type) + '" listeners ' + - 'added. Use emitter.setMaxListeners() to ' + - 'increase limit.'); - w.name = 'MaxListenersExceededWarning'; - w.emitter = target; - w.type = type; - w.count = existing.length; - if (typeof console === 'object' && console.warn) { - console.warn('%s: %s', w.name, w.message); - } - } - } - } - - return target; -} - -EventEmitter.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; - -EventEmitter.prototype.on = EventEmitter.prototype.addListener; - -EventEmitter.prototype.prependListener = - function prependListener(type, listener) { - return _addListener(this, type, listener, true); - }; - -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - switch (arguments.length) { - case 0: - return this.listener.call(this.target); - case 1: - return this.listener.call(this.target, arguments[0]); - case 2: - return this.listener.call(this.target, arguments[0], arguments[1]); - case 3: - return this.listener.call(this.target, arguments[0], arguments[1], - arguments[2]); - default: - var args = new Array(arguments.length); - for (var i = 0; i < args.length; ++i) - args[i] = arguments[i]; - this.listener.apply(this.target, args); - } - } -} - -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; - var wrapped = bind.call(onceWrapper, state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} - -EventEmitter.prototype.once = function once(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; - -EventEmitter.prototype.prependOnceListener = - function prependOnceListener(type, listener) { - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; - }; - -// Emits a 'removeListener' event if and only if the listener was removed. -EventEmitter.prototype.removeListener = - function removeListener(type, listener) { - var list, events, position, i, originalListener; - - if (typeof listener !== 'function') - throw new TypeError('"listener" argument must be a function'); - - events = this._events; - if (!events) - return this; - - list = events[type]; - if (!list) - return this; - - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = objectCreate(null); - else { - delete events[type]; - if (events.removeListener) - this.emit('removeListener', type, list.listener || listener); - } - } else if (typeof list !== 'function') { - position = -1; - - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - - if (position < 0) - return this; - - if (position === 0) - list.shift(); - else - spliceOne(list, position); - - if (list.length === 1) - events[type] = list[0]; - - if (events.removeListener) - this.emit('removeListener', type, originalListener || listener); - } - - return this; - }; - -EventEmitter.prototype.removeAllListeners = - function removeAllListeners(type) { - var listeners, events, i; - - events = this._events; - if (!events) - return this; - - // not listening for removeListener, no need to emit - if (!events.removeListener) { - if (arguments.length === 0) { - this._events = objectCreate(null); - this._eventsCount = 0; - } else if (events[type]) { - if (--this._eventsCount === 0) - this._events = objectCreate(null); - else - delete events[type]; - } - return this; - } - - // emit removeListener for all listeners on all events - if (arguments.length === 0) { - var keys = objectKeys(events); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === 'removeListener') continue; - this.removeAllListeners(key); - } - this.removeAllListeners('removeListener'); - this._events = objectCreate(null); - this._eventsCount = 0; - return this; - } - - listeners = events[type]; - - if (typeof listeners === 'function') { - this.removeListener(type, listeners); - } else if (listeners) { - // LIFO order - for (i = listeners.length - 1; i >= 0; i--) { - this.removeListener(type, listeners[i]); - } - } - - return this; - }; - -function _listeners(target, type, unwrap) { - var events = target._events; - - if (!events) - return []; - - var evlistener = events[type]; - if (!evlistener) - return []; - - if (typeof evlistener === 'function') - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - - return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} - -EventEmitter.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; - -EventEmitter.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; - -EventEmitter.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === 'function') { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; - -EventEmitter.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events = this._events; - - if (events) { - var evlistener = events[type]; - - if (typeof evlistener === 'function') { - return 1; - } else if (evlistener) { - return evlistener.length; - } - } - - return 0; -} - -EventEmitter.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; -}; - -// About 1.5x faster than the two-arg version of Array#splice(). -function spliceOne(list, index) { - for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) - list[i] = list[k]; - list.pop(); -} - -function arrayClone(arr, n) { - var copy = new Array(n); - for (var i = 0; i < n; ++i) - copy[i] = arr[i]; - return copy; -} - -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} - -function objectCreatePolyfill(proto) { - var F = function() {}; - F.prototype = proto; - return new F; -} -function objectKeysPolyfill(obj) { - var keys = []; - for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) { - keys.push(k); - } - return k; -} -function functionBindPolyfill(context) { - var fn = this; - return function () { - return fn.apply(context, arguments); - }; -} - -},{}],152:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = (nBytes * 8) - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = ((value * c) - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],153:[function(require,module,exports){ -arguments[4][98][0].apply(exports,arguments) -},{"dup":98}],154:[function(require,module,exports){ -/*! - * Determine if an object is a Buffer - * - * @author Feross Aboukhadijeh - * @license MIT - */ - -// The _isBuffer check is for Safari 5-7 support, because it's missing -// Object.prototype.constructor. Remove this eventually -module.exports = function (obj) { - return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) -} - -function isBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) -} - -// For Node v0.10 support. Remove this eventually. -function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) -} - -},{}],155:[function(require,module,exports){ -var toString = {}.toString; - -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; - -},{}],156:[function(require,module,exports){ -(function (process){ -'use strict'; - -if (!process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process -} - -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; - } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} - - -}).call(this,require('_process')) -},{"_process":157}],157:[function(require,module,exports){ -// shim for using process in browser -var process = module.exports = {}; - -// cached from whatever global is present so that test runners that stub it -// don't break things. But we need to wrap it in a try catch in case it is -// wrapped in strict mode code which doesn't define any globals. It's inside a -// function because try/catches deoptimize in certain engines. - -var cachedSetTimeout; -var cachedClearTimeout; - -function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); -} -function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); -} -(function () { - try { - if (typeof setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } else { - cachedSetTimeout = defaultSetTimout; - } - } catch (e) { - cachedSetTimeout = defaultSetTimout; - } - try { - if (typeof clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } else { - cachedClearTimeout = defaultClearTimeout; - } - } catch (e) { - cachedClearTimeout = defaultClearTimeout; - } -} ()) -function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } - - -} -function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } - - - -} -var queue = []; -var draining = false; -var currentQueue; -var queueIndex = -1; - -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } -} - -function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; - - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); -} - -process.nextTick = function (fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } -}; - -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - this.fun.apply(null, this.array); -}; -process.title = 'browser'; -process.browser = true; -process.env = {}; -process.argv = []; -process.version = ''; // empty string to avoid regexp issues -process.versions = {}; - -function noop() {} - -process.on = noop; -process.addListener = noop; -process.once = noop; -process.off = noop; -process.removeListener = noop; -process.removeAllListeners = noop; -process.emit = noop; -process.prependListener = noop; -process.prependOnceListener = noop; - -process.listeners = function (name) { return [] } - -process.binding = function (name) { - throw new Error('process.binding is not supported'); -}; - -process.cwd = function () { return '/' }; -process.chdir = function (dir) { - throw new Error('process.chdir is not supported'); -}; -process.umask = function() { return 0; }; - -},{}],158:[function(require,module,exports){ -module.exports = require('./lib/_stream_duplex.js'); - -},{"./lib/_stream_duplex.js":159}],159:[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. - -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. - -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -util.inherits(Duplex, Readable); - -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} - -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - - Readable.call(this, options); - Writable.call(this, options); - - if (options && options.readable === false) this.readable = false; - - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; - - this.once('end', onend); -} - -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; - - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} - -function onEndNT(self) { - self.end(); -} - -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); - -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); - - pna.nextTick(cb, err); -}; -},{"./_stream_readable":161,"./_stream_writable":163,"core-util-is":150,"inherits":153,"process-nextick-args":156}],160:[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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":162,"core-util-is":150,"inherits":153}],161:[function(require,module,exports){ -(function (process,global){ -// 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 pna = require('process-nextick-args'); -/**/ - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = require('events').EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -/**/ - -var Buffer = require('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = require('./internal/streams/BufferList'); -var destroyImpl = require('./internal/streams/destroy'); -var StringDecoder; - -util.inherits(Readable, Stream); - -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; - -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} - -function ReadableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; - - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; - - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; - - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - - // has it been destroyed - this.destroyed = false; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; - - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - - if (!(this instanceof Readable)) return new Readable(options); - - this._readableState = new ReadableState(options, this); - - // legacy - this.readable = true; - - if (options) { - if (typeof options.read === 'function') this._read = options.read; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } - - Stream.call(this); -} - -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); - -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; - -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} - -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; - -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; - -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} - -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; - - if (n !== 0) state.emittedReadable = false; - - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - - n = howMuchToRead(n, state); - - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } - - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. - - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); - - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } - - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; - - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } - - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; - - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } - - if (ret !== null) this.emit('data', ret); - - return ret; -}; - -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; - - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} - -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} - -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', src._readableState.awaitDrain); - src._readableState.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; - -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; - - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; - - if (!dest) dest = state.pipes; - - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, unpipeInfo); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); - - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} - -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; - -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} - -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; - - var state = this._readableState; - var paused = false; - - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } - - _this.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; - - return this; -}; - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - - return ret; -} - -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} - -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} - -function endReadable(stream) { - var state = stream._readableState; - - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} - -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} - -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"./_stream_duplex":159,"./internal/streams/BufferList":164,"./internal/streams/destroy":165,"./internal/streams/stream":166,"_process":157,"core-util-is":150,"events":151,"inherits":153,"isarray":155,"process-nextick-args":156,"safe-buffer":171,"string_decoder/":173,"util":148}],162:[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. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - -'use strict'; - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(Transform, Duplex); - -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; - - var cb = ts.writecb; - - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } - - ts.writechunk = null; - ts.writecb = null; - - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); - - cb(er); - - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} - -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); - - Duplex.call(this, options); - - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; - - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; - - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; - - if (typeof options.flush === 'function') this._flush = options.flush; - } - - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} - -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} - -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; - -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; - -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; - -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; - -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; - - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; - -function done(stream, er, data) { - if (er) return stream.emit('error', er); - - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - - return stream.push(null); -} -},{"./_stream_duplex":159,"core-util-is":150,"inherits":153}],163:[function(require,module,exports){ -(function (process,global,setImmediate){ -// 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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -module.exports = Writable; - -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; -} - -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; - - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -/**/ -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -/**/ - -var Buffer = require('safe-buffer').Buffer; -var OurUint8Array = global.Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} - -/**/ - -var destroyImpl = require('./internal/streams/destroy'); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - options = options || {}; - - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; - - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; - - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); - - // if _final has been called - this.finalCalled = false; - - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; - - // has it been destroyed - this.destroyed = false; - - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; - - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; - - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; - - // a flag to see when we're in the middle of a write. - this.writing = false; - - // when true all writes will be buffered until .uncork() call - this.corked = 0; - - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; - - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; - - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; - - // the amount that is being written when _write is called. - this.writelen = 0; - - this.bufferedRequest = null; - this.lastBufferedRequest = null; - - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; - - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; - - // count buffered requests - this.bufferedRequestCount = 0; - - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} - -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; - -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); - -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; - - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} - -function Writable(options) { - Duplex = Duplex || require('./_stream_duplex'); - - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. - - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } - - this._writableState = new WritableState(options, this); - - // legacy. - this.writable = true; - - if (options) { - if (typeof options.write === 'function') this._write = options.write; - - if (typeof options.writev === 'function') this._writev = options.writev; - - if (typeof options.destroy === 'function') this._destroy = options.destroy; - - if (typeof options.final === 'function') this._final = options.final; - } - - Stream.call(this); -} - -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} - -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; - - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} - -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); - - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } - - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; - - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } - - return ret; -}; - -Writable.prototype.cork = function () { - var state = this._writableState; - - state.corked++; -}; - -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; - -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; - -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; -} - -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); - -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; - - state.length += len; - - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; - - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; - - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} - -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} - -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - - onwriteStateUpdate(state); - - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); - - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } - - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} - -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} - -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} - -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; - - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; - - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; - - doWrite(stream, state, true, state.length, buffer, '', holder.finish); - - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } - - if (entry === null) state.lastBufferedRequest = null; - } - - state.bufferedRequest = entry; - state.bufferProcessing = false; -} - -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } - - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } - - // ignore unnecessary end() calls. - if (!state.ending && !state.finished) endWritable(this, state, cb); -}; - -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} - -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; -} - -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} - -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } - if (state.corkedRequestsFree) { - state.corkedRequestsFree.next = corkReq; - } else { - state.corkedRequestsFree = corkReq; - } -} - -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } - - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); - -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate) -},{"./_stream_duplex":159,"./internal/streams/destroy":165,"./internal/streams/stream":166,"_process":157,"core-util-is":150,"inherits":153,"process-nextick-args":156,"safe-buffer":171,"timers":174,"util-deprecate":175}],164:[function(require,module,exports){ -'use strict'; - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = require('safe-buffer').Buffer; -var util = require('util'); - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - return BufferList; -}(); - -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; -} -},{"safe-buffer":171,"util":148}],165:[function(require,module,exports){ -'use strict'; - -/**/ - -var pna = require('process-nextick-args'); -/**/ - -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; - - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; - - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { - pna.nextTick(emitErrorNT, this, err); - } - return this; - } - - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } - - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } - - this._destroy(err || null, function (err) { - if (!cb && err) { - pna.nextTick(emitErrorNT, _this, err); - if (_this._writableState) { - _this._writableState.errorEmitted = true; - } - } else if (cb) { - cb(err); - } - }); - - return this; -} - -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} - -function emitErrorNT(self, err) { - self.emit('error', err); -} - -module.exports = { - destroy: destroy, - undestroy: undestroy -}; -},{"process-nextick-args":156}],166:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":151}],167:[function(require,module,exports){ -module.exports = require('./readable').PassThrough - -},{"./readable":168}],168:[function(require,module,exports){ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); - -},{"./lib/_stream_duplex.js":159,"./lib/_stream_passthrough.js":160,"./lib/_stream_readable.js":161,"./lib/_stream_transform.js":162,"./lib/_stream_writable.js":163}],169:[function(require,module,exports){ -module.exports = require('./readable').Transform - -},{"./readable":168}],170:[function(require,module,exports){ -module.exports = require('./lib/_stream_writable.js'); - -},{"./lib/_stream_writable.js":163}],171:[function(require,module,exports){ -arguments[4][117][0].apply(exports,arguments) -},{"buffer":149,"dup":117}],172:[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. - -module.exports = Stream; - -var EE = require('events').EventEmitter; -var inherits = require('inherits'); - -inherits(Stream, EE); -Stream.Readable = require('readable-stream/readable.js'); -Stream.Writable = require('readable-stream/writable.js'); -Stream.Duplex = require('readable-stream/duplex.js'); -Stream.Transform = require('readable-stream/transform.js'); -Stream.PassThrough = require('readable-stream/passthrough.js'); - -// Backwards-compat with node 0.4.x -Stream.Stream = Stream; - - - -// old-style streams. Note that the pipe method (the only relevant -// part of this class) is overridden in the Readable class. - -function Stream() { - EE.call(this); -} - -Stream.prototype.pipe = function(dest, options) { - var source = this; - - function ondata(chunk) { - if (dest.writable) { - if (false === dest.write(chunk) && source.pause) { - source.pause(); - } - } - } - - source.on('data', ondata); - - function ondrain() { - if (source.readable && source.resume) { - source.resume(); - } - } - - dest.on('drain', ondrain); - - // If the 'end' option is not supplied, dest.end() will be called when - // source gets the 'end' or 'close' events. Only dest.end() once. - if (!dest._isStdio && (!options || options.end !== false)) { - source.on('end', onend); - source.on('close', onclose); - } - - var didOnEnd = false; - function onend() { - if (didOnEnd) return; - didOnEnd = true; - - dest.end(); - } - - - function onclose() { - if (didOnEnd) return; - didOnEnd = true; - - if (typeof dest.destroy === 'function') dest.destroy(); - } - - // don't leave dangling pipes when there are errors. - function onerror(er) { - cleanup(); - if (EE.listenerCount(this, 'error') === 0) { - throw er; // Unhandled stream error in pipe. - } - } - - source.on('error', onerror); - dest.on('error', onerror); - - // remove all the event listeners that were added. - function cleanup() { - source.removeListener('data', ondata); - dest.removeListener('drain', ondrain); - - source.removeListener('end', onend); - source.removeListener('close', onclose); - - source.removeListener('error', onerror); - dest.removeListener('error', onerror); - - source.removeListener('end', cleanup); - source.removeListener('close', cleanup); - - dest.removeListener('close', cleanup); - } - - source.on('end', cleanup); - source.on('close', cleanup); - - dest.on('close', cleanup); - - dest.emit('pipe', source); - - // Allow for unix-like usage: A.pipe(B).pipe(C) - return dest; -}; - -},{"events":151,"inherits":153,"readable-stream/duplex.js":158,"readable-stream/passthrough.js":167,"readable-stream/readable.js":168,"readable-stream/transform.js":169,"readable-stream/writable.js":170}],173:[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":171}],174:[function(require,module,exports){ -(function (setImmediate,clearImmediate){ -var nextTick = require('process/browser.js').nextTick; -var apply = Function.prototype.apply; -var slice = Array.prototype.slice; -var immediateIds = {}; -var nextImmediateId = 0; - -// DOM APIs, for completeness - -exports.setTimeout = function() { - return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout); -}; -exports.setInterval = function() { - return new Timeout(apply.call(setInterval, window, arguments), clearInterval); -}; -exports.clearTimeout = -exports.clearInterval = function(timeout) { timeout.close(); }; - -function Timeout(id, clearFn) { - this._id = id; - this._clearFn = clearFn; -} -Timeout.prototype.unref = Timeout.prototype.ref = function() {}; -Timeout.prototype.close = function() { - this._clearFn.call(window, this._id); -}; - -// Does not start the time, just sets up the members needed. -exports.enroll = function(item, msecs) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = msecs; -}; - -exports.unenroll = function(item) { - clearTimeout(item._idleTimeoutId); - item._idleTimeout = -1; -}; - -exports._unrefActive = exports.active = function(item) { - clearTimeout(item._idleTimeoutId); - - var msecs = item._idleTimeout; - if (msecs >= 0) { - item._idleTimeoutId = setTimeout(function onTimeout() { - if (item._onTimeout) - item._onTimeout(); - }, msecs); - } -}; - -// That's not how node.js implements it but the exposed api is the same. -exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) { - var id = nextImmediateId++; - var args = arguments.length < 2 ? false : slice.call(arguments, 1); - - immediateIds[id] = true; - - nextTick(function onNextTick() { - if (immediateIds[id]) { - // fn.call() is faster so we optimize for the common use-case - // @see http://jsperf.com/call-apply-segu - if (args) { - fn.apply(null, args); - } else { - fn.call(null); - } - // Prevent ids from leaking - exports.clearImmediate(id); - } - }); - - return id; -}; - -exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) { - delete immediateIds[id]; -}; -}).call(this,require("timers").setImmediate,require("timers").clearImmediate) -},{"process/browser.js":157,"timers":174}],175:[function(require,module,exports){ -(function (global){ - -/** - * Module exports. - */ - -module.exports = deprecate; - -/** - * Mark that a method should not be used. - * Returns a modified function which warns once by default. - * - * If `localStorage.noDeprecation = true` is set, then it is a no-op. - * - * If `localStorage.throwDeprecation = true` is set, then deprecated functions - * will throw an Error when invoked. - * - * If `localStorage.traceDeprecation = true` is set, then deprecated functions - * will invoke `console.trace()` instead of `console.error()`. - * - * @param {Function} fn - the function to deprecate - * @param {String} msg - the string to print to the console when `fn` is invoked - * @returns {Function} a new "deprecated" version of `fn` - * @api public - */ - -function deprecate (fn, msg) { - if (config('noDeprecation')) { - return fn; - } - - var warned = false; - function deprecated() { - if (!warned) { - if (config('throwDeprecation')) { - throw new Error(msg); - } else if (config('traceDeprecation')) { - console.trace(msg); - } else { - console.warn(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } - - return deprecated; -} - -/** - * Checks `localStorage` for boolean values for the given `name`. - * - * @param {String} name - * @returns {Boolean} - * @api private - */ - -function config (name) { - // accessing global.localStorage can trigger a DOMException in sandboxed iframes - try { - if (!global.localStorage) return false; - } catch (_) { - return false; - } - var val = global.localStorage[name]; - if (null == val) return false; - return String(val).toLowerCase() === 'true'; -} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}]},{},[1]); diff --git a/docs/demo/index.html b/docs/demo/index.html index 6bd7edf..2f69f91 100644 --- a/docs/demo/index.html +++ b/docs/demo/index.html @@ -319,17 +319,15 @@
- + + @@ -86,39 +86,31 @@
Documentation: + + + + @@ -86,7 +87,6 @@
Documentation: Documentation: + @@ -93,11 +250,7 @@
Documentation: Date: Tue, 9 Apr 2019 13:08:58 +0300 Subject: [PATCH 63/65] demo docs. unneeded css file removed --- docs/assets/spectre.min.css | 1 - 1 file changed, 1 deletion(-) delete mode 100644 docs/assets/spectre.min.css diff --git a/docs/assets/spectre.min.css b/docs/assets/spectre.min.css deleted file mode 100644 index 7ec2ed2..0000000 --- a/docs/assets/spectre.min.css +++ /dev/null @@ -1 +0,0 @@ -/*! Spectre.css v0.5.6 | MIT License | github.com/picturepan2/spectre */html{font-family:sans-serif;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%}body{margin:0}article,aside,footer,header,nav,section{display:block}h1{font-size:2em;margin:.67em 0}figcaption,figure,main{display:block}hr{box-sizing:content-box;height:0;overflow:visible}a{background-color:transparent;-webkit-text-decoration-skip:objects}a:active,a:hover{outline-width:0}address{font-style:normal}b,strong{font-weight:inherit}b,strong{font-weight:bolder}code,kbd,pre,samp{font-family:"SF Mono","Segoe UI Mono","Roboto Mono",Menlo,Courier,monospace;font-size:1em}dfn{font-style:italic}small{font-size:80%;font-weight:400}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}audio,video{display:inline-block}audio:not([controls]){display:none;height:0}img{border-style:none}svg:not(:root){overflow:hidden}button,input,optgroup,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit;margin:0}button,input{overflow:visible}button,select{text-transform:none}[type=reset],[type=submit],button,html [type=button]{-webkit-appearance:button}[type=button]::-moz-focus-inner,[type=reset]::-moz-focus-inner,[type=submit]::-moz-focus-inner,button::-moz-focus-inner{border-style:none;padding:0}fieldset{border:0;margin:0;padding:0}legend{box-sizing:border-box;color:inherit;display:table;max-width:100%;padding:0;white-space:normal}progress{display:inline-block;vertical-align:baseline}textarea{overflow:auto}[type=checkbox],[type=radio]{box-sizing:border-box;padding:0}[type=number]::-webkit-inner-spin-button,[type=number]::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}[type=search]::-webkit-search-cancel-button,[type=search]::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}details,menu{display:block}summary{display:list-item;outline:0}canvas{display:inline-block}template{display:none}[hidden]{display:none}*,::after,::before{box-sizing:inherit}html{box-sizing:border-box;font-size:20px;line-height:1.5;-webkit-tap-highlight-color:transparent}body{background:#fff;color:#3b4351;font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Helvetica Neue",sans-serif;font-size:.8rem;overflow-x:hidden;text-rendering:optimizeLegibility}a{color:#5755d9;outline:0;text-decoration:none}a:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}a.active,a:active,a:focus,a:hover{color:#302ecd;text-decoration:underline}a:visited{color:#807fe2}h1,h2,h3,h4,h5,h6{color:inherit;font-weight:500;line-height:1.2;margin-bottom:.5em;margin-top:0}.h1,.h2,.h3,.h4,.h5,.h6{font-weight:500}.h1,h1{font-size:2rem}.h2,h2{font-size:1.6rem}.h3,h3{font-size:1.4rem}.h4,h4{font-size:1.2rem}.h5,h5{font-size:1rem}.h6,h6{font-size:.8rem}p{margin:0 0 1.2rem}a,ins,u{-webkit-text-decoration-skip:ink edges;text-decoration-skip:ink edges}abbr[title]{border-bottom:.05rem dotted;cursor:help;text-decoration:none}kbd{background:#303742;border-radius:.1rem;color:#fff;font-size:.7rem;line-height:1.2;padding:.1rem .2rem}mark{background:#ffe9b3;border-bottom:.05rem solid #ffd367;border-radius:.1rem;color:#3b4351;padding:.05rem .1rem 0}blockquote{border-left:.1rem solid #dadee4;margin-left:0;padding:.4rem .8rem}blockquote p:last-child{margin-bottom:0}ol,ul{margin:.8rem 0 .8rem .8rem;padding:0}ol ol,ol ul,ul ol,ul ul{margin:.8rem 0 .8rem .8rem}ol li,ul li{margin-top:.4rem}ul{list-style:disc inside}ul ul{list-style-type:circle}ol{list-style:decimal inside}ol ol{list-style-type:lower-alpha}dl dt{font-weight:700}dl dd{margin:.4rem 0 .8rem 0}.lang-zh,.lang-zh-hans,html:lang(zh),html:lang(zh-Hans){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang SC","Hiragino Sans GB","Microsoft YaHei","Helvetica Neue",sans-serif}.lang-zh-hant,html:lang(zh-Hant){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"PingFang TC","Hiragino Sans CNS","Microsoft JhengHei","Helvetica Neue",sans-serif}.lang-ja,html:lang(ja){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Hiragino Sans","Hiragino Kaku Gothic Pro","Yu Gothic",YuGothic,Meiryo,"Helvetica Neue",sans-serif}.lang-ko,html:lang(ko){font-family:-apple-system,system-ui,BlinkMacSystemFont,"Segoe UI",Roboto,"Malgun Gothic","Helvetica Neue",sans-serif}.lang-cjk ins,.lang-cjk u,:lang(ja) ins,:lang(ja) u,:lang(zh) ins,:lang(zh) u{border-bottom:.05rem solid;text-decoration:none}.lang-cjk del+del,.lang-cjk del+s,.lang-cjk ins+ins,.lang-cjk ins+u,.lang-cjk s+del,.lang-cjk s+s,.lang-cjk u+ins,.lang-cjk u+u,:lang(ja) del+del,:lang(ja) del+s,:lang(ja) ins+ins,:lang(ja) ins+u,:lang(ja) s+del,:lang(ja) s+s,:lang(ja) u+ins,:lang(ja) u+u,:lang(zh) del+del,:lang(zh) del+s,:lang(zh) ins+ins,:lang(zh) ins+u,:lang(zh) s+del,:lang(zh) s+s,:lang(zh) u+ins,:lang(zh) u+u{margin-left:.125em}.table{border-collapse:collapse;border-spacing:0;text-align:left;width:100%}.table.table-striped tbody tr:nth-of-type(odd){background:#f7f8f9}.table tbody tr.active,.table.table-striped tbody tr.active{background:#eef0f3}.table.table-hover tbody tr:hover{background:#eef0f3}.table.table-scroll{display:block;overflow-x:auto;padding-bottom:.75rem;white-space:nowrap}.table td,.table th{border-bottom:.05rem solid #dadee4;padding:.6rem .4rem}.table th{border-bottom-width:.1rem}.btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;border:.05rem solid #5755d9;border-radius:.1rem;color:#5755d9;cursor:pointer;display:inline-block;font-size:.8rem;height:1.8rem;line-height:1.2rem;outline:0;padding:.25rem .4rem;text-align:center;text-decoration:none;transition:background .2s,border .2s,box-shadow .2s,color .2s;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none;vertical-align:middle;white-space:nowrap}.btn:focus{box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.btn:focus,.btn:hover{background:#f1f1fc;border-color:#4b48d6;text-decoration:none}.btn.active,.btn:active{background:#4b48d6;border-color:#3634d2;color:#fff;text-decoration:none}.btn.active.loading::after,.btn:active.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.disabled,.btn:disabled,.btn[disabled]{cursor:default;opacity:.5;pointer-events:none}.btn.btn-primary{background:#5755d9;border-color:#4b48d6;color:#fff}.btn.btn-primary:focus,.btn.btn-primary:hover{background:#4240d4;border-color:#3634d2;color:#fff}.btn.btn-primary.active,.btn.btn-primary:active{background:#3a38d2;border-color:#302ecd;color:#fff}.btn.btn-primary.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-success{background:#32b643;border-color:#2faa3f;color:#fff}.btn.btn-success:focus{box-shadow:0 0 0 .1rem rgba(50,182,67,.2)}.btn.btn-success:focus,.btn.btn-success:hover{background:#30ae40;border-color:#2da23c;color:#fff}.btn.btn-success.active,.btn.btn-success:active{background:#2a9a39;border-color:#278e34;color:#fff}.btn.btn-success.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-error{background:#e85600;border-color:#d95000;color:#fff}.btn.btn-error:focus{box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.btn.btn-error:focus,.btn.btn-error:hover{background:#de5200;border-color:#cf4d00;color:#fff}.btn.btn-error.active,.btn.btn-error:active{background:#c44900;border-color:#b54300;color:#fff}.btn.btn-error.loading::after{border-bottom-color:#fff;border-left-color:#fff}.btn.btn-link{background:0 0;border-color:transparent;color:#5755d9}.btn.btn-link.active,.btn.btn-link:active,.btn.btn-link:focus,.btn.btn-link:hover{color:#302ecd}.btn.btn-sm{font-size:.7rem;height:1.4rem;padding:.05rem .3rem}.btn.btn-lg{font-size:.9rem;height:2rem;padding:.35rem .6rem}.btn.btn-block{display:block;width:100%}.btn.btn-action{padding-left:0;padding-right:0;width:1.8rem}.btn.btn-action.btn-sm{width:1.4rem}.btn.btn-action.btn-lg{width:2rem}.btn.btn-clear{background:0 0;border:0;color:currentColor;height:1rem;line-height:.8rem;margin-left:.2rem;margin-right:-2px;opacity:1;padding:.1rem;text-decoration:none;width:1rem}.btn.btn-clear:focus,.btn.btn-clear:hover{background:rgba(247,248,249,.5);opacity:.95}.btn.btn-clear::before{content:"\2715"}.btn-group{display:inline-flex;display:-ms-inline-flexbox;-ms-flex-wrap:wrap;flex-wrap:wrap}.btn-group .btn{-ms-flex:1 0 auto;flex:1 0 auto}.btn-group .btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group .btn:not(:first-child):not(:last-child){border-radius:0;margin-left:-.05rem}.btn-group .btn:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0;margin-left:-.05rem}.btn-group .btn.active,.btn-group .btn:active,.btn-group .btn:focus,.btn-group .btn:hover{z-index:1}.btn-group.btn-group-block{display:flex;display:-ms-flexbox}.btn-group.btn-group-block .btn{-ms-flex:1 0 0;flex:1 0 0}.form-group:not(:last-child){margin-bottom:.4rem}fieldset{margin-bottom:.8rem}legend{font-size:.9rem;font-weight:500;margin-bottom:.8rem}.form-label{display:block;line-height:1.2rem;padding:.3rem 0}.form-label.label-sm{font-size:.7rem;padding:.1rem 0}.form-label.label-lg{font-size:.9rem;padding:.4rem 0}.form-input{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;background-image:none;border:.05rem solid #bcc3ce;border-radius:.1rem;color:#3b4351;display:block;font-size:.8rem;height:1.8rem;line-height:1.2rem;max-width:100%;outline:0;padding:.25rem .4rem;position:relative;transition:background .2s,border .2s,box-shadow .2s,color .2s;width:100%}.form-input:focus{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-input::-webkit-input-placeholder{color:#bcc3ce}.form-input:-ms-input-placeholder{color:#bcc3ce}.form-input::-ms-input-placeholder{color:#bcc3ce}.form-input::placeholder{color:#bcc3ce}.form-input.input-sm{font-size:.7rem;height:1.4rem;padding:.05rem .3rem}.form-input.input-lg{font-size:.9rem;height:2rem;padding:.35rem .6rem}.form-input.input-inline{display:inline-block;vertical-align:middle;width:auto}.form-input[type=file]{height:auto}textarea.form-input{height:auto}.form-input-hint{color:#bcc3ce;font-size:.7rem;margin-top:.2rem}.has-success .form-input-hint,.is-success+.form-input-hint{color:#32b643}.has-error .form-input-hint,.is-error+.form-input-hint{color:#e85600}.form-select{-webkit-appearance:none;-moz-appearance:none;appearance:none;background:#fff;border:.05rem solid #bcc3ce;border-radius:.1rem;color:inherit;font-size:.8rem;height:1.8rem;line-height:1.2rem;outline:0;padding:.25rem .4rem;vertical-align:middle;width:100%}.form-select:focus{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-select::-ms-expand{display:none}.form-select.select-sm{font-size:.7rem;height:1.4rem;padding:.05rem 1.1rem .05rem .3rem}.form-select.select-lg{font-size:.9rem;height:2rem;padding:.35rem 1.4rem .35rem .6rem}.form-select[multiple],.form-select[size]{height:auto;padding:.25rem .4rem}.form-select[multiple] option,.form-select[size] option{padding:.1rem .2rem}.form-select:not([multiple]):not([size]){background:#fff url("data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%204%205'%3E%3Cpath%20fill='%23667189'%20d='M2%200L0%202h4zm0%205L0%203h4z'/%3E%3C/svg%3E") no-repeat right .35rem center/.4rem .5rem;padding-right:1.2rem}.has-icon-left,.has-icon-right{position:relative}.has-icon-left .form-icon,.has-icon-right .form-icon{height:.8rem;margin:0 .25rem;position:absolute;top:50%;transform:translateY(-50%);width:.8rem;z-index:2}.has-icon-left .form-icon{left:.05rem}.has-icon-left .form-input{padding-left:1.3rem}.has-icon-right .form-icon{right:.05rem}.has-icon-right .form-input{padding-right:1.3rem}.form-checkbox,.form-radio,.form-switch{display:block;line-height:1.2rem;margin:.2rem 0;min-height:1.2rem;padding:.1rem .4rem .1rem 1.2rem;position:relative}.form-checkbox input,.form-radio input,.form-switch input{clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;position:absolute;width:1px}.form-checkbox input:focus+.form-icon,.form-radio input:focus+.form-icon,.form-switch input:focus+.form-icon{border-color:#5755d9;box-shadow:0 0 0 .1rem rgba(87,85,217,.2)}.form-checkbox input:checked+.form-icon,.form-radio input:checked+.form-icon,.form-switch input:checked+.form-icon{background:#5755d9;border-color:#5755d9}.form-checkbox .form-icon,.form-radio .form-icon,.form-switch .form-icon{border:.05rem solid #bcc3ce;cursor:pointer;display:inline-block;position:absolute;transition:background .2s,border .2s,box-shadow .2s,color .2s}.form-checkbox.input-sm,.form-radio.input-sm,.form-switch.input-sm{font-size:.7rem;margin:0}.form-checkbox.input-lg,.form-radio.input-lg,.form-switch.input-lg{font-size:.9rem;margin:.3rem 0}.form-checkbox .form-icon,.form-radio .form-icon{background:#fff;height:.8rem;left:0;top:.3rem;width:.8rem}.form-checkbox input:active+.form-icon,.form-radio input:active+.form-icon{background:#eef0f3}.form-checkbox .form-icon{border-radius:.1rem}.form-checkbox input:checked+.form-icon::before{background-clip:padding-box;border:.1rem solid #fff;border-left-width:0;border-top-width:0;content:"";height:9px;left:50%;margin-left:-3px;margin-top:-6px;position:absolute;top:50%;transform:rotate(45deg);width:6px}.form-checkbox input:indeterminate+.form-icon{background:#5755d9;border-color:#5755d9}.form-checkbox input:indeterminate+.form-icon::before{background:#fff;content:"";height:2px;left:50%;margin-left:-5px;margin-top:-1px;position:absolute;top:50%;width:10px}.form-radio .form-icon{border-radius:50%}.form-radio input:checked+.form-icon::before{background:#fff;border-radius:50%;content:"";height:6px;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);width:6px}.form-switch{padding-left:2rem}.form-switch .form-icon{background:#bcc3ce;background-clip:padding-box;border-radius:.45rem;height:.9rem;left:0;top:.25rem;width:1.6rem}.form-switch .form-icon::before{background:#fff;border-radius:50%;content:"";display:block;height:.8rem;left:0;position:absolute;top:0;transition:background .2s,border .2s,box-shadow .2s,color .2s,left .2s;width:.8rem}.form-switch input:checked+.form-icon::before{left:14px}.form-switch input:active+.form-icon::before{background:#f7f8f9}.input-group{display:flex;display:-ms-flexbox}.input-group .input-group-addon{background:#f7f8f9;border:.05rem solid #bcc3ce;border-radius:.1rem;line-height:1.2rem;padding:.25rem .4rem;white-space:nowrap}.input-group .input-group-addon.addon-sm{font-size:.7rem;padding:.05rem .3rem}.input-group .input-group-addon.addon-lg{font-size:.9rem;padding:.35rem .6rem}.input-group .form-input,.input-group .form-select{-ms-flex:1 1 auto;flex:1 1 auto;width:1%}.input-group .input-group-btn{z-index:1}.input-group .form-input:first-child:not(:last-child),.input-group .form-select:first-child:not(:last-child),.input-group .input-group-addon:first-child:not(:last-child),.input-group .input-group-btn:first-child:not(:last-child){border-bottom-right-radius:0;border-top-right-radius:0}.input-group .form-input:not(:first-child):not(:last-child),.input-group .form-select:not(:first-child):not(:last-child),.input-group .input-group-addon:not(:first-child):not(:last-child),.input-group .input-group-btn:not(:first-child):not(:last-child){border-radius:0;margin-left:-.05rem}.input-group .form-input:last-child:not(:first-child),.input-group .form-select:last-child:not(:first-child),.input-group .input-group-addon:last-child:not(:first-child),.input-group .input-group-btn:last-child:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0;margin-left:-.05rem}.input-group .form-input:focus,.input-group .form-select:focus,.input-group .input-group-addon:focus,.input-group .input-group-btn:focus{z-index:2}.input-group .form-select{width:auto}.input-group.input-inline{display:inline-flex;display:-ms-inline-flexbox}.form-input.is-success,.form-select.is-success,.has-success .form-input,.has-success .form-select{background:#f9fdfa;border-color:#32b643}.form-input.is-success:focus,.form-select.is-success:focus,.has-success .form-input:focus,.has-success .form-select:focus{box-shadow:0 0 0 .1rem rgba(50,182,67,.2)}.form-input.is-error,.form-select.is-error,.has-error .form-input,.has-error .form-select{background:#fffaf7;border-color:#e85600}.form-input.is-error:focus,.form-select.is-error:focus,.has-error .form-input:focus,.has-error .form-select:focus{box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-checkbox.is-error .form-icon,.form-radio.is-error .form-icon,.form-switch.is-error .form-icon,.has-error .form-checkbox .form-icon,.has-error .form-radio .form-icon,.has-error .form-switch .form-icon{border-color:#e85600}.form-checkbox.is-error input:checked+.form-icon,.form-radio.is-error input:checked+.form-icon,.form-switch.is-error input:checked+.form-icon,.has-error .form-checkbox input:checked+.form-icon,.has-error .form-radio input:checked+.form-icon,.has-error .form-switch input:checked+.form-icon{background:#e85600;border-color:#e85600}.form-checkbox.is-error input:focus+.form-icon,.form-radio.is-error input:focus+.form-icon,.form-switch.is-error input:focus+.form-icon,.has-error .form-checkbox input:focus+.form-icon,.has-error .form-radio input:focus+.form-icon,.has-error .form-switch input:focus+.form-icon{border-color:#e85600;box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-checkbox.is-error input:indeterminate+.form-icon,.has-error .form-checkbox input:indeterminate+.form-icon{background:#e85600;border-color:#e85600}.form-input:not(:placeholder-shown):invalid{border-color:#e85600}.form-input:not(:placeholder-shown):invalid:focus{background:#fffaf7;box-shadow:0 0 0 .1rem rgba(232,86,0,.2)}.form-input:not(:placeholder-shown):invalid+.form-input-hint{color:#e85600}.form-input.disabled,.form-input:disabled,.form-select.disabled,.form-select:disabled{background-color:#eef0f3;cursor:not-allowed;opacity:.5}.form-input[readonly]{background-color:#f7f8f9}input.disabled+.form-icon,input:disabled+.form-icon{background:#eef0f3;cursor:not-allowed;opacity:.5}.form-switch input.disabled+.form-icon::before,.form-switch input:disabled+.form-icon::before{background:#fff}.form-horizontal{padding:.4rem 0}.form-horizontal .form-group{display:flex;display:-ms-flexbox;-ms-flex-wrap:wrap;flex-wrap:wrap}.form-inline{display:inline-block}.label{background:#eef0f3;border-radius:.1rem;color:#455060;display:inline-block;line-height:1.2;padding:.1rem .2rem}.label.label-rounded{border-radius:5rem;padding-left:.4rem;padding-right:.4rem}.label.label-primary{background:#5755d9;color:#fff}.label.label-secondary{background:#f1f1fc;color:#5755d9}.label.label-success{background:#32b643;color:#fff}.label.label-warning{background:#ffb700;color:#fff}.label.label-error{background:#e85600;color:#fff}code{background:#fcf2f2;border-radius:.1rem;color:#d73e48;font-size:85%;line-height:1.2;padding:.1rem .2rem}.code{border-radius:.1rem;color:#3b4351;position:relative}.code::before{color:#bcc3ce;content:attr(data-lang);font-size:.7rem;position:absolute;right:.4rem;top:.1rem}.code code{background:#f7f8f9;color:inherit;display:block;line-height:1.5;overflow-x:auto;padding:1rem;width:100%}.img-responsive{display:block;height:auto;max-width:100%}.img-fit-cover{object-fit:cover}.img-fit-contain{object-fit:contain}.video-responsive{display:block;overflow:hidden;padding:0;position:relative;width:100%}.video-responsive::before{content:"";display:block;padding-bottom:56.25%}.video-responsive embed,.video-responsive iframe,.video-responsive object{border:0;bottom:0;height:100%;left:0;position:absolute;right:0;top:0;width:100%}video.video-responsive{height:auto;max-width:100%}video.video-responsive::before{content:none}.video-responsive-4-3::before{padding-bottom:75%}.video-responsive-1-1::before{padding-bottom:100%}.figure{margin:0 0 .4rem 0}.figure .figure-caption{color:#66758c;margin-top:.4rem}.container{margin-left:auto;margin-right:auto;padding-left:.4rem;padding-right:.4rem;width:100%}.container.grid-xl{max-width:1296px}.container.grid-lg{max-width:976px}.container.grid-md{max-width:856px}.container.grid-sm{max-width:616px}.container.grid-xs{max-width:496px}.show-lg,.show-md,.show-sm,.show-xl,.show-xs{display:none!important}.columns{display:flex;display:-ms-flexbox;-ms-flex-wrap:wrap;flex-wrap:wrap;margin-left:-.4rem;margin-right:-.4rem}.columns.col-gapless{margin-left:0;margin-right:0}.columns.col-gapless>.column{padding-left:0;padding-right:0}.columns.col-oneline{-ms-flex-wrap:nowrap;flex-wrap:nowrap;overflow-x:auto}.column{-ms-flex:1;flex:1;max-width:100%;padding-left:.4rem;padding-right:.4rem}.column.col-1,.column.col-10,.column.col-11,.column.col-12,.column.col-2,.column.col-3,.column.col-4,.column.col-5,.column.col-6,.column.col-7,.column.col-8,.column.col-9{-ms-flex:none;flex:none}.col-12{width:100%}.col-11{width:91.66666667%}.col-10{width:83.33333333%}.col-9{width:75%}.col-8{width:66.66666667%}.col-7{width:58.33333333%}.col-6{width:50%}.col-5{width:41.66666667%}.col-4{width:33.33333333%}.col-3{width:25%}.col-2{width:16.66666667%}.col-1{width:8.33333333%}.col-auto{-ms-flex:0 0 auto;flex:0 0 auto;max-width:none;width:auto}.col-mx-auto{margin-left:auto;margin-right:auto}.col-ml-auto{margin-left:auto}.col-mr-auto{margin-right:auto}@media (max-width:1280px){.col-xl-1,.col-xl-10,.col-xl-11,.col-xl-12,.col-xl-2,.col-xl-3,.col-xl-4,.col-xl-5,.col-xl-6,.col-xl-7,.col-xl-8,.col-xl-9{-ms-flex:none;flex:none}.col-xl-12{width:100%}.col-xl-11{width:91.66666667%}.col-xl-10{width:83.33333333%}.col-xl-9{width:75%}.col-xl-8{width:66.66666667%}.col-xl-7{width:58.33333333%}.col-xl-6{width:50%}.col-xl-5{width:41.66666667%}.col-xl-4{width:33.33333333%}.col-xl-3{width:25%}.col-xl-2{width:16.66666667%}.col-xl-1{width:8.33333333%}.hide-xl{display:none!important}.show-xl{display:block!important}}@media (max-width:960px){.col-lg-1,.col-lg-10,.col-lg-11,.col-lg-12,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9{-ms-flex:none;flex:none}.col-lg-12{width:100%}.col-lg-11{width:91.66666667%}.col-lg-10{width:83.33333333%}.col-lg-9{width:75%}.col-lg-8{width:66.66666667%}.col-lg-7{width:58.33333333%}.col-lg-6{width:50%}.col-lg-5{width:41.66666667%}.col-lg-4{width:33.33333333%}.col-lg-3{width:25%}.col-lg-2{width:16.66666667%}.col-lg-1{width:8.33333333%}.hide-lg{display:none!important}.show-lg{display:block!important}}@media (max-width:840px){.col-md-1,.col-md-10,.col-md-11,.col-md-12,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9{-ms-flex:none;flex:none}.col-md-12{width:100%}.col-md-11{width:91.66666667%}.col-md-10{width:83.33333333%}.col-md-9{width:75%}.col-md-8{width:66.66666667%}.col-md-7{width:58.33333333%}.col-md-6{width:50%}.col-md-5{width:41.66666667%}.col-md-4{width:33.33333333%}.col-md-3{width:25%}.col-md-2{width:16.66666667%}.col-md-1{width:8.33333333%}.hide-md{display:none!important}.show-md{display:block!important}}@media (max-width:600px){.col-sm-1,.col-sm-10,.col-sm-11,.col-sm-12,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9{-ms-flex:none;flex:none}.col-sm-12{width:100%}.col-sm-11{width:91.66666667%}.col-sm-10{width:83.33333333%}.col-sm-9{width:75%}.col-sm-8{width:66.66666667%}.col-sm-7{width:58.33333333%}.col-sm-6{width:50%}.col-sm-5{width:41.66666667%}.col-sm-4{width:33.33333333%}.col-sm-3{width:25%}.col-sm-2{width:16.66666667%}.col-sm-1{width:8.33333333%}.hide-sm{display:none!important}.show-sm{display:block!important}}@media (max-width:480px){.col-xs-1,.col-xs-10,.col-xs-11,.col-xs-12,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9{-ms-flex:none;flex:none}.col-xs-12{width:100%}.col-xs-11{width:91.66666667%}.col-xs-10{width:83.33333333%}.col-xs-9{width:75%}.col-xs-8{width:66.66666667%}.col-xs-7{width:58.33333333%}.col-xs-6{width:50%}.col-xs-5{width:41.66666667%}.col-xs-4{width:33.33333333%}.col-xs-3{width:25%}.col-xs-2{width:16.66666667%}.col-xs-1{width:8.33333333%}.hide-xs{display:none!important}.show-xs{display:block!important}}.hero{display:flex;display:-ms-flexbox;-ms-flex-direction:column;flex-direction:column;-ms-flex-pack:justify;justify-content:space-between;padding-bottom:4rem;padding-top:4rem}.hero.hero-sm{padding-bottom:2rem;padding-top:2rem}.hero.hero-lg{padding-bottom:8rem;padding-top:8rem}.hero .hero-body{padding:.4rem}.navbar{align-items:stretch;display:flex;display:-ms-flexbox;-ms-flex-align:stretch;-ms-flex-pack:justify;-ms-flex-wrap:wrap;flex-wrap:wrap;justify-content:space-between}.navbar .navbar-section{align-items:center;display:flex;display:-ms-flexbox;-ms-flex:1 0 0;flex:1 0 0;-ms-flex-align:center}.navbar .navbar-section:not(:first-child):last-child{-ms-flex-pack:end;justify-content:flex-end}.navbar .navbar-center{align-items:center;display:flex;display:-ms-flexbox;-ms-flex:0 0 auto;flex:0 0 auto;-ms-flex-align:center}.navbar .navbar-brand{font-size:.9rem;text-decoration:none}.accordion input:checked~.accordion-header .icon,.accordion[open] .accordion-header .icon{transform:rotate(90deg)}.accordion input:checked~.accordion-body,.accordion[open] .accordion-body{max-height:50rem}.accordion .accordion-header{display:block;padding:.2rem .4rem}.accordion .accordion-header .icon{transition:transform .25s}.accordion .accordion-body{margin-bottom:.4rem;max-height:0;overflow:hidden;transition:max-height .25s}summary.accordion-header::-webkit-details-marker{display:none}.avatar{background:#5755d9;border-radius:50%;color:rgba(255,255,255,.85);display:inline-block;font-size:.8rem;font-weight:300;height:1.6rem;line-height:1.25;margin:0;position:relative;vertical-align:middle;width:1.6rem}.avatar.avatar-xs{font-size:.4rem;height:.8rem;width:.8rem}.avatar.avatar-sm{font-size:.6rem;height:1.2rem;width:1.2rem}.avatar.avatar-lg{font-size:1.2rem;height:2.4rem;width:2.4rem}.avatar.avatar-xl{font-size:1.6rem;height:3.2rem;width:3.2rem}.avatar img{border-radius:50%;height:100%;position:relative;width:100%;z-index:1}.avatar .avatar-icon,.avatar .avatar-presence{background:#fff;bottom:14.64%;height:50%;padding:.1rem;position:absolute;right:14.64%;transform:translate(50%,50%);width:50%;z-index:2}.avatar .avatar-presence{background:#bcc3ce;border-radius:50%;box-shadow:0 0 0 .1rem #fff;height:.5em;width:.5em}.avatar .avatar-presence.online{background:#32b643}.avatar .avatar-presence.busy{background:#e85600}.avatar .avatar-presence.away{background:#ffb700}.avatar[data-initial]::before{color:currentColor;content:attr(data-initial);left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);z-index:1}.badge{position:relative;white-space:nowrap}.badge:not([data-badge])::after,.badge[data-badge]::after{background:#5755d9;background-clip:padding-box;border-radius:.5rem;box-shadow:0 0 0 .1rem #fff;color:#fff;content:attr(data-badge);display:inline-block;transform:translate(-.05rem,-.5rem)}.badge[data-badge]::after{font-size:.7rem;height:.9rem;line-height:1;min-width:.9rem;padding:.1rem .2rem;text-align:center;white-space:nowrap}.badge:not([data-badge])::after,.badge[data-badge=""]::after{height:6px;min-width:6px;padding:0;width:6px}.badge.btn::after{position:absolute;right:0;top:0;transform:translate(50%,-50%)}.badge.avatar::after{position:absolute;right:14.64%;top:14.64%;transform:translate(50%,-50%);z-index:100}.breadcrumb{list-style:none;margin:.2rem 0;padding:.2rem 0}.breadcrumb .breadcrumb-item{color:#66758c;display:inline-block;margin:0;padding:.2rem 0}.breadcrumb .breadcrumb-item:not(:last-child){margin-right:.2rem}.breadcrumb .breadcrumb-item:not(:last-child) a{color:#66758c}.breadcrumb .breadcrumb-item:not(:first-child)::before{color:#66758c;content:"/";padding-right:.4rem}.bar{background:#eef0f3;border-radius:.1rem;display:flex;display:-ms-flexbox;-ms-flex-wrap:nowrap;flex-wrap:nowrap;height:.8rem;width:100%}.bar.bar-sm{height:.2rem}.bar .bar-item{background:#5755d9;color:#fff;display:block;-ms-flex-negative:0;flex-shrink:0;font-size:.7rem;height:100%;line-height:.8rem;position:relative;text-align:center;width:0}.bar .bar-item:first-child{border-bottom-left-radius:.1rem;border-top-left-radius:.1rem}.bar .bar-item:last-child{border-bottom-right-radius:.1rem;border-top-right-radius:.1rem;-ms-flex-negative:1;flex-shrink:1}.bar-slider{height:.1rem;margin:.4rem 0;position:relative}.bar-slider .bar-item{left:0;padding:0;position:absolute}.bar-slider .bar-item:not(:last-child):first-child{background:#eef0f3;z-index:1}.bar-slider .bar-slider-btn{background:#5755d9;border:0;border-radius:50%;height:.6rem;padding:0;position:absolute;right:0;top:50%;transform:translate(50%,-50%);width:.6rem}.bar-slider .bar-slider-btn:active{box-shadow:0 0 0 .1rem #5755d9}.card{background:#fff;border:.05rem solid #dadee4;border-radius:.1rem;display:flex;display:-ms-flexbox;-ms-flex-direction:column;flex-direction:column}.card .card-body,.card .card-footer,.card .card-header{padding:.8rem;padding-bottom:0}.card .card-body:last-child,.card .card-footer:last-child,.card .card-header:last-child{padding-bottom:.8rem}.card .card-body{-ms-flex:1 1 auto;flex:1 1 auto}.card .card-image{padding-top:.8rem}.card .card-image:first-child{padding-top:0}.card .card-image:first-child img{border-top-left-radius:.1rem;border-top-right-radius:.1rem}.card .card-image:last-child img{border-bottom-left-radius:.1rem;border-bottom-right-radius:.1rem}.chip{align-items:center;background:#eef0f3;border-radius:5rem;display:inline-flex;display:-ms-inline-flexbox;-ms-flex-align:center;font-size:90%;height:1.2rem;line-height:.8rem;margin:.1rem;max-width:320px;overflow:hidden;padding:.2rem .4rem;text-decoration:none;text-overflow:ellipsis;vertical-align:middle;white-space:nowrap}.chip.active{background:#5755d9;color:#fff}.chip .avatar{margin-left:-.4rem;margin-right:.2rem}.chip .btn-clear{border-radius:50%;transform:scale(.75)}.dropdown{display:inline-block;position:relative}.dropdown .menu{animation:slide-down .15s ease 1;display:none;left:0;max-height:50vh;overflow-y:auto;position:absolute;top:100%}.dropdown.dropdown-right .menu{left:auto;right:0}.dropdown .dropdown-toggle:focus+.menu,.dropdown .menu:hover,.dropdown.active .menu{display:block}.dropdown .btn-group .dropdown-toggle:nth-last-child(2){border-bottom-right-radius:.1rem;border-top-right-radius:.1rem}.empty{background:#f7f8f9;border-radius:.1rem;color:#66758c;padding:3.2rem 1.6rem;text-align:center}.empty .empty-icon{margin-bottom:.8rem}.empty .empty-subtitle,.empty .empty-title{margin:.4rem auto}.empty .empty-action{margin-top:.8rem}.menu{background:#fff;border-radius:.1rem;box-shadow:0 .05rem .2rem rgba(48,55,66,.3);list-style:none;margin:0;min-width:180px;padding:.4rem;transform:translateY(.2rem);z-index:300}.menu.menu-nav{background:0 0;box-shadow:none}.menu .menu-item{margin-top:0;padding:0 .4rem;text-decoration:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.menu .menu-item>a{border-radius:.1rem;color:inherit;display:block;margin:0 -.4rem;padding:.2rem .4rem;text-decoration:none}.menu .menu-item>a:focus,.menu .menu-item>a:hover{background:#f1f1fc;color:#5755d9}.menu .menu-item>a.active,.menu .menu-item>a:active{background:#f1f1fc;color:#5755d9}.menu .menu-item .form-checkbox,.menu .menu-item .form-radio,.menu .menu-item .form-switch{margin:.1rem 0}.menu .menu-item+.menu-item{margin-top:.2rem}.menu .menu-badge{float:right;padding:.2rem 0}.menu .menu-badge .btn{margin-top:-.1rem}.modal{align-items:center;bottom:0;display:none;-ms-flex-align:center;-ms-flex-pack:center;justify-content:center;left:0;opacity:0;overflow:hidden;padding:.4rem;position:fixed;right:0;top:0}.modal.active,.modal:target{display:flex;display:-ms-flexbox;opacity:1;z-index:400}.modal.active .modal-overlay,.modal:target .modal-overlay{background:rgba(247,248,249,.75);bottom:0;cursor:default;display:block;left:0;position:absolute;right:0;top:0}.modal.active .modal-container,.modal:target .modal-container{animation:slide-down .2s ease 1;z-index:1}.modal.modal-sm .modal-container{max-width:320px;padding:0 .4rem}.modal.modal-lg .modal-overlay{background:#fff}.modal.modal-lg .modal-container{box-shadow:none;max-width:960px}.modal-container{background:#fff;border-radius:.1rem;box-shadow:0 .2rem .5rem rgba(48,55,66,.3);display:flex;display:-ms-flexbox;-ms-flex-direction:column;flex-direction:column;max-height:75vh;max-width:640px;padding:0 .8rem;width:100%}.modal-container.modal-fullheight{max-height:100vh}.modal-container .modal-header{color:#303742;padding:.8rem}.modal-container .modal-body{overflow-y:auto;padding:.8rem;position:relative}.modal-container .modal-footer{padding:.8rem;text-align:right}.nav{display:flex;display:-ms-flexbox;-ms-flex-direction:column;flex-direction:column;list-style:none;margin:.2rem 0}.nav .nav-item a{color:#66758c;padding:.2rem .4rem;text-decoration:none}.nav .nav-item a:focus,.nav .nav-item a:hover{color:#5755d9}.nav .nav-item.active>a{color:#505c6e;font-weight:700}.nav .nav-item.active>a:focus,.nav .nav-item.active>a:hover{color:#5755d9}.nav .nav{margin-bottom:.4rem;margin-left:.8rem}.pagination{display:flex;display:-ms-flexbox;list-style:none;margin:.2rem 0;padding:.2rem 0}.pagination .page-item{margin:.2rem .05rem}.pagination .page-item span{display:inline-block;padding:.2rem .2rem}.pagination .page-item a{border-radius:.1rem;display:inline-block;padding:.2rem .4rem;text-decoration:none}.pagination .page-item a:focus,.pagination .page-item a:hover{color:#5755d9}.pagination .page-item.disabled a{cursor:default;opacity:.5;pointer-events:none}.pagination .page-item.active a{background:#5755d9;color:#fff}.pagination .page-item.page-next,.pagination .page-item.page-prev{-ms-flex:1 0 50%;flex:1 0 50%}.pagination .page-item.page-next{text-align:right}.pagination .page-item .page-item-title{margin:0}.pagination .page-item .page-item-subtitle{margin:0;opacity:.5}.panel{border:.05rem solid #dadee4;border-radius:.1rem;display:flex;display:-ms-flexbox;-ms-flex-direction:column;flex-direction:column}.panel .panel-footer,.panel .panel-header{-ms-flex:0 0 auto;flex:0 0 auto;padding:.8rem}.panel .panel-nav{-ms-flex:0 0 auto;flex:0 0 auto}.panel .panel-body{-ms-flex:1 1 auto;flex:1 1 auto;overflow-y:auto;padding:0 .8rem}.popover{display:inline-block;position:relative}.popover .popover-container{left:50%;opacity:0;padding:.4rem;position:absolute;top:0;transform:translate(-50%,-50%) scale(0);transition:transform .2s;width:320px;z-index:300}.popover :focus+.popover-container,.popover:hover .popover-container{display:block;opacity:1;transform:translate(-50%,-100%) scale(1)}.popover.popover-right .popover-container{left:100%;top:50%}.popover.popover-right :focus+.popover-container,.popover.popover-right:hover .popover-container{transform:translate(0,-50%) scale(1)}.popover.popover-bottom .popover-container{left:50%;top:100%}.popover.popover-bottom :focus+.popover-container,.popover.popover-bottom:hover .popover-container{transform:translate(-50%,0) scale(1)}.popover.popover-left .popover-container{left:0;top:50%}.popover.popover-left :focus+.popover-container,.popover.popover-left:hover .popover-container{transform:translate(-100%,-50%) scale(1)}.popover .card{border:0;box-shadow:0 .2rem .5rem rgba(48,55,66,.3)}.step{display:flex;display:-ms-flexbox;-ms-flex-wrap:nowrap;flex-wrap:nowrap;list-style:none;margin:.2rem 0;width:100%}.step .step-item{-ms-flex:1 1 0;flex:1 1 0;margin-top:0;min-height:1rem;position:relative;text-align:center}.step .step-item:not(:first-child)::before{background:#5755d9;content:"";height:2px;left:-50%;position:absolute;top:9px;width:100%}.step .step-item a{color:#5755d9;display:inline-block;padding:20px 10px 0;text-decoration:none}.step .step-item a::before{background:#5755d9;border:.1rem solid #fff;border-radius:50%;content:"";display:block;height:.6rem;left:50%;position:absolute;top:.2rem;transform:translateX(-50%);width:.6rem;z-index:1}.step .step-item.active a::before{background:#fff;border:.1rem solid #5755d9}.step .step-item.active~.step-item::before{background:#dadee4}.step .step-item.active~.step-item a{color:#bcc3ce}.step .step-item.active~.step-item a::before{background:#dadee4}.tab{align-items:center;border-bottom:.05rem solid #dadee4;display:flex;display:-ms-flexbox;-ms-flex-align:center;-ms-flex-wrap:wrap;flex-wrap:wrap;list-style:none;margin:.2rem 0 .15rem 0}.tab .tab-item{margin-top:0}.tab .tab-item a{border-bottom:.1rem solid transparent;color:inherit;display:block;margin:0 .4rem 0 0;padding:.4rem .2rem .3rem .2rem;text-decoration:none}.tab .tab-item a:focus,.tab .tab-item a:hover{color:#5755d9}.tab .tab-item a.active,.tab .tab-item.active a{border-bottom-color:#5755d9;color:#5755d9}.tab .tab-item.tab-action{-ms-flex:1 0 auto;flex:1 0 auto;text-align:right}.tab .tab-item .btn-clear{margin-top:-.2rem}.tab.tab-block .tab-item{-ms-flex:1 0 0;flex:1 0 0;text-align:center}.tab.tab-block .tab-item a{margin:0}.tab.tab-block .tab-item .badge[data-badge]::after{position:absolute;right:.1rem;top:.1rem;transform:translate(0,0)}.tab:not(.tab-block) .badge{padding-right:0}.tile{align-content:space-between;align-items:flex-start;display:flex;display:-ms-flexbox;-ms-flex-align:start;-ms-flex-line-pack:justify}.tile .tile-action,.tile .tile-icon{-ms-flex:0 0 auto;flex:0 0 auto}.tile .tile-content{-ms-flex:1 1 auto;flex:1 1 auto}.tile .tile-content:not(:first-child){padding-left:.4rem}.tile .tile-content:not(:last-child){padding-right:.4rem}.tile .tile-subtitle,.tile .tile-title{line-height:1.2rem}.tile.tile-centered{align-items:center;-ms-flex-align:center}.tile.tile-centered .tile-content{overflow:hidden}.tile.tile-centered .tile-subtitle,.tile.tile-centered .tile-title{margin-bottom:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.toast{background:rgba(48,55,66,.95);border:.05rem solid #303742;border-color:#303742;border-radius:.1rem;color:#fff;display:block;padding:.4rem;width:100%}.toast.toast-primary{background:rgba(87,85,217,.95);border-color:#5755d9}.toast.toast-success{background:rgba(50,182,67,.95);border-color:#32b643}.toast.toast-warning{background:rgba(255,183,0,.95);border-color:#ffb700}.toast.toast-error{background:rgba(232,86,0,.95);border-color:#e85600}.toast a{color:#fff;text-decoration:underline}.toast a.active,.toast a:active,.toast a:focus,.toast a:hover{opacity:.75}.toast .btn-clear{margin:.1rem}.toast p:last-child{margin-bottom:0}.tooltip{position:relative}.tooltip::after{background:rgba(48,55,66,.95);border-radius:.1rem;bottom:100%;color:#fff;content:attr(data-tooltip);display:block;font-size:.7rem;left:50%;max-width:320px;opacity:0;overflow:hidden;padding:.2rem .4rem;pointer-events:none;position:absolute;text-overflow:ellipsis;transform:translate(-50%,.4rem);transition:opacity .2s,transform .2s;white-space:pre;z-index:300}.tooltip:focus::after,.tooltip:hover::after{opacity:1;transform:translate(-50%,-.2rem)}.tooltip.disabled,.tooltip[disabled]{pointer-events:auto}.tooltip.tooltip-right::after{bottom:50%;left:100%;transform:translate(-.2rem,50%)}.tooltip.tooltip-right:focus::after,.tooltip.tooltip-right:hover::after{transform:translate(.2rem,50%)}.tooltip.tooltip-bottom::after{bottom:auto;top:100%;transform:translate(-50%,-.4rem)}.tooltip.tooltip-bottom:focus::after,.tooltip.tooltip-bottom:hover::after{transform:translate(-50%,.2rem)}.tooltip.tooltip-left::after{bottom:50%;left:auto;right:100%;transform:translate(.4rem,50%)}.tooltip.tooltip-left:focus::after,.tooltip.tooltip-left:hover::after{transform:translate(-.2rem,50%)}@keyframes loading{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}@keyframes slide-down{0%{opacity:0;transform:translateY(-1.6rem)}100%{opacity:1;transform:translateY(0)}}.text-primary{color:#5755d9!important}a.text-primary:focus,a.text-primary:hover{color:#4240d4}a.text-primary:visited{color:#6c6ade}.text-secondary{color:#e5e5f9!important}a.text-secondary:focus,a.text-secondary:hover{color:#d1d0f4}a.text-secondary:visited{color:#fafafe}.text-gray{color:#bcc3ce!important}a.text-gray:focus,a.text-gray:hover{color:#adb6c4}a.text-gray:visited{color:#cbd0d9}.text-light{color:#fff!important}a.text-light:focus,a.text-light:hover{color:#f2f2f2}a.text-light:visited{color:#fff}.text-dark{color:#3b4351!important}a.text-dark:focus,a.text-dark:hover{color:#303742}a.text-dark:visited{color:#455060}.text-success{color:#32b643!important}a.text-success:focus,a.text-success:hover{color:#2da23c}a.text-success:visited{color:#39c94b}.text-warning{color:#ffb700!important}a.text-warning:focus,a.text-warning:hover{color:#e6a500}a.text-warning:visited{color:#ffbe1a}.text-error{color:#e85600!important}a.text-error:focus,a.text-error:hover{color:#cf4d00}a.text-error:visited{color:#ff6003}.bg-primary{background:#5755d9!important;color:#fff}.bg-secondary{background:#f1f1fc!important}.bg-dark{background:#303742!important;color:#fff}.bg-gray{background:#f7f8f9!important}.bg-success{background:#32b643!important;color:#fff}.bg-warning{background:#ffb700!important;color:#fff}.bg-error{background:#e85600!important;color:#fff}.c-hand{cursor:pointer}.c-move{cursor:move}.c-zoom-in{cursor:zoom-in}.c-zoom-out{cursor:zoom-out}.c-not-allowed{cursor:not-allowed}.c-auto{cursor:auto}.d-block{display:block}.d-inline{display:inline}.d-inline-block{display:inline-block}.d-flex{display:flex;display:-ms-flexbox}.d-inline-flex{display:inline-flex;display:-ms-inline-flexbox}.d-hide,.d-none{display:none!important}.d-visible{visibility:visible}.d-invisible{visibility:hidden}.text-hide{background:0 0;border:0;color:transparent;font-size:0;line-height:0;text-shadow:none}.text-assistive{border:0;clip:rect(0,0,0,0);height:1px;margin:-1px;overflow:hidden;padding:0;position:absolute;width:1px}.divider,.divider-vert{display:block;position:relative}.divider-vert[data-content]::after,.divider[data-content]::after{background:#fff;color:#bcc3ce;content:attr(data-content);display:inline-block;font-size:.7rem;padding:0 .4rem;transform:translateY(-.65rem)}.divider{border-top:.05rem solid #dadee4;height:.05rem;margin:.4rem 0}.divider[data-content]{margin:.8rem 0}.divider-vert{display:block;padding:.8rem}.divider-vert::before{border-left:.05rem solid #dadee4;bottom:.4rem;content:"";display:block;left:50%;position:absolute;top:.4rem;transform:translateX(-50%)}.divider-vert[data-content]::after{left:50%;padding:.2rem 0;position:absolute;top:50%;transform:translate(-50%,-50%)}.loading{color:transparent!important;min-height:.8rem;pointer-events:none;position:relative}.loading::after{animation:loading .5s infinite linear;border:.1rem solid #5755d9;border-radius:50%;border-right-color:transparent;border-top-color:transparent;content:"";display:block;height:.8rem;left:50%;margin-left:-.4rem;margin-top:-.4rem;position:absolute;top:50%;width:.8rem;z-index:1}.loading.loading-lg{min-height:2rem}.loading.loading-lg::after{height:1.6rem;margin-left:-.8rem;margin-top:-.8rem;width:1.6rem}.clearfix::after{clear:both;content:"";display:table}.float-left{float:left!important}.float-right{float:right!important}.p-relative{position:relative!important}.p-absolute{position:absolute!important}.p-fixed{position:fixed!important}.p-sticky{position:sticky!important;position:-webkit-sticky!important}.p-centered{display:block;float:none;margin-left:auto;margin-right:auto}.flex-centered{align-items:center;display:flex;display:-ms-flexbox;-ms-flex-align:center;-ms-flex-pack:center;justify-content:center}.m-0{margin:0!important}.mb-0{margin-bottom:0!important}.ml-0{margin-left:0!important}.mr-0{margin-right:0!important}.mt-0{margin-top:0!important}.mx-0{margin-left:0!important;margin-right:0!important}.my-0{margin-bottom:0!important;margin-top:0!important}.m-1{margin:.2rem!important}.mb-1{margin-bottom:.2rem!important}.ml-1{margin-left:.2rem!important}.mr-1{margin-right:.2rem!important}.mt-1{margin-top:.2rem!important}.mx-1{margin-left:.2rem!important;margin-right:.2rem!important}.my-1{margin-bottom:.2rem!important;margin-top:.2rem!important}.m-2{margin:.4rem!important}.mb-2{margin-bottom:.4rem!important}.ml-2{margin-left:.4rem!important}.mr-2{margin-right:.4rem!important}.mt-2{margin-top:.4rem!important}.mx-2{margin-left:.4rem!important;margin-right:.4rem!important}.my-2{margin-bottom:.4rem!important;margin-top:.4rem!important}.p-0{padding:0!important}.pb-0{padding-bottom:0!important}.pl-0{padding-left:0!important}.pr-0{padding-right:0!important}.pt-0{padding-top:0!important}.px-0{padding-left:0!important;padding-right:0!important}.py-0{padding-bottom:0!important;padding-top:0!important}.p-1{padding:.2rem!important}.pb-1{padding-bottom:.2rem!important}.pl-1{padding-left:.2rem!important}.pr-1{padding-right:.2rem!important}.pt-1{padding-top:.2rem!important}.px-1{padding-left:.2rem!important;padding-right:.2rem!important}.py-1{padding-bottom:.2rem!important;padding-top:.2rem!important}.p-2{padding:.4rem!important}.pb-2{padding-bottom:.4rem!important}.pl-2{padding-left:.4rem!important}.pr-2{padding-right:.4rem!important}.pt-2{padding-top:.4rem!important}.px-2{padding-left:.4rem!important;padding-right:.4rem!important}.py-2{padding-bottom:.4rem!important;padding-top:.4rem!important}.s-rounded{border-radius:.1rem}.s-circle{border-radius:50%}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-lowercase{text-transform:lowercase}.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-normal{font-weight:400}.text-bold{font-weight:700}.text-italic{font-style:italic}.text-large{font-size:1.2em}.text-ellipsis{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.text-clip{overflow:hidden;text-overflow:clip;white-space:nowrap}.text-break{-webkit-hyphens:auto;-ms-hyphens:auto;hyphens:auto;word-break:break-word;word-wrap:break-word} \ No newline at end of file From 03ca3f0783561fcd4a4f67068acefe2d7b5a99b9 Mon Sep 17 00:00:00 2001 From: Dmitry Date: Tue, 9 Apr 2019 14:31:13 +0300 Subject: [PATCH 64/65] Update README.md --- README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 9c9c563..1fd4488 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ ## Installation -Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases/download/0.24/KeyChain.Installer.zip). Windows and Linux installers are coming soon. +Download and install KeyChain for [macOS](https://github.com/arrayio/array-io-keychain/releases). Windows and Linux installers are coming soon. *Try out KeyChain on the [demo page](https://arrayio.github.io/array-io-keychain/demo/).* @@ -92,9 +92,9 @@ KeyChain and Swap.Online in action: The main purpose of this repository is to continue to evolve KeyChain core, making it faster and easier to use. Development of KeyChain happens in the open on GitHub, and we are grateful to the community for contributing bugfixes and improvements. -### [Code of Conduct](https://github.com/arrayio/array-io-keychain/blob/master/CODE_OF_CONDUCT.md) +### [Code of Conduct](CODE_OF_CONDUCT.md) -KeyChain has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](https://github.com/arrayio/array-io-keychain/blob/master/CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be accepted. +KeyChain has adopted a Code of Conduct that we expect project participants to adhere to. Please read [the full text](CODE_OF_CONDUCT.md) so that you can understand what actions will and will not be accepted. To contribute or report a bug, you can [contact us](#contact) or create an [issue](https://github.com/arrayio/array-io-keychain/issues/new) with a label "bug". From 1c281b76332af339f0456de51caf65cae9950c91 Mon Sep 17 00:00:00 2001 From: sinev-valentine Date: Thu, 11 Apr 2019 16:52:25 +0300 Subject: [PATCH 65/65] fix prefix oof public key in btc transaction --- keychain_lib/include/keychain_lib/keychain_commands.hpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/keychain_lib/include/keychain_lib/keychain_commands.hpp b/keychain_lib/include/keychain_lib/keychain_commands.hpp index ba38208..4ef0e0c 100644 --- a/keychain_lib/include/keychain_lib/keychain_commands.hpp +++ b/keychain_lib/include/keychain_lib/keychain_commands.hpp @@ -565,6 +565,12 @@ struct keychain_command : keychain_command_base s_length++; s.insert(0, "00"); } + auto pub_key = dev::toPublic(private_key); + std::string prefix; + if (pub_key[dev::Public::size-1]%2) + prefix = "03"; // y - odd + else + prefix = "02"; // y - even // script_len + signature DER-encoded + pub_key ss << std::setw(2) << ((int) script_len) << std::setw(2) << ((int) pushdata_sig) @@ -578,7 +584,7 @@ struct keychain_command : keychain_command_base << s << std::setw(2) << ((int) sig_hash_code) << std::setw(2) << ((int) pushdata_pubkey) - << "03"+ dev::toPublic(private_key).hex().substr(0,64); + << prefix+ pub_key.hex().substr(0,64); trx += ss.str(); trx += a.end_of_vin; }

» Download for macOS