diff --git a/.codespellrc b/.codespellrc new file mode 100644 index 000000000..96f480b57 --- /dev/null +++ b/.codespellrc @@ -0,0 +1,4 @@ +[codespell] +count = True +ignore-words-list = ans,deriver,inout,packag +skip = *.js,*WordLists.swift,.git,Carthage,.build,build diff --git a/.github/workflows/macOS-tests.yml b/.github/workflows/macOS-tests.yml index 9c842cd4f..3e3bafb6f 100644 --- a/.github/workflows/macOS-tests.yml +++ b/.github/workflows/macOS-tests.yml @@ -29,7 +29,7 @@ jobs: spm: name: Swift Package Manager 5.7 runs-on: macOS-12 - concurrency: + concurrency: group: spm-${{ github.run_id }} cancel-in-progress: false steps: @@ -38,7 +38,13 @@ jobs: run: | pip3 install --upgrade pip pip3 install codespell - codespell --count --ignore-words-list=ans,deriver,inout,packag --skip="*.js,*WordLists.swift" + codespell # See .codespellrc for args + - name: SwiftLint + run: | + # 1. Make all automated fixes that are possible + # 2. git diff to see what (if any) automated fixes were made + # 3. See https://github.com/realm/SwiftLint#xcode explains why the double run + swiftlint --fix --quiet && git diff && swiftlint --quiet - name: Resolve dependencies run: swift package resolve - name: Build diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml new file mode 100644 index 000000000..19c7b391b --- /dev/null +++ b/.github/workflows/pre-commit.yml @@ -0,0 +1,22 @@ +# https://pre-commit.com +# This GitHub Action assumes that the repo contains a valid .pre-commit-config.yaml file. +# Using pre-commit.ci is even better than using GitHub Actions for pre-commit. +name: pre-commit +on: + pull_request: + branches: [develop] + push: + branches: [develop] + workflow_dispatch: +jobs: + pre-commit: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: 3.x + - run: pip install pre-commit + - run: pre-commit --version + - run: pre-commit install + - run: pre-commit run --all-files diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 000000000..0b19196c4 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,22 @@ +repos: +- repo: https://github.com/pre-commit/pre-commit-hooks + rev: v3.2.0 + hooks: + - id: trailing-whitespace + - id: end-of-file-fixer + - id: check-yaml + - id: check-added-large-files + - id: check-case-conflict + - id: check-json + - id: mixed-line-ending + - id: no-commit-to-branch + args: [--branch, staging, --branch, main, --branch, master, --branch, develop-4.0, --branch, develop-upstream] +- repo: https://github.com/codespell-project/codespell + rev: v2.2.2 + hooks: + - id: codespell # See .codespellrc for args +# - repo: https://github.com/realm/SwiftLint # Too slow in pre-commit +# rev: 0.50.3 +# hooks: +# - id: swiftlint +# args: [--fix, Sources, Tests] diff --git a/.swiftlint.yml b/.swiftlint.yml index a0d7900d6..f7519e42f 100644 --- a/.swiftlint.yml +++ b/.swiftlint.yml @@ -1,45 +1,73 @@ excluded: - - Carthage - - Pods - .build - Build + - Carthage - DerivedData + - Pods + +analyzer_rules: + - unused_import disabled_rules: - - type_name + - block_based_kvo + - closure_body_length + - computed_accessors_order + - cyclomatic_complexity + - duplicate_imports + - empty_enum_arguments + - empty_string + - file_length + - for_where + - force_cast + - force_try + - force_unwrapping + - function_body_length + - function_parameter_count - identifier_name + - implicit_getter + - implicitly_unwrapped_optional + - indentation_width + - large_tuple + - legacy_objc_type - line_length - multiple_closures_with_trailing_closure + - nesting + - orphaned_doc_comment + - operator_whitespace + - return_arrow_whitespace + - shorthand_operator - todo + - trailing_closure + - type_body_length + - type_name + - unneeded_break_in_switch + - unused_optional_binding + - vertical_parameter_alignment + - xctfail_message opt_in_rules: - - weak_delegate - - unused_import - - unneeded_parentheses_in_closure_argument - - trailing_closure - - static_operator - - redundant_nil_coalescing - - override_in_extension - - legacy_objc_type - - implicitly_unwrapped_optional - - force_unwrapping - - empty_string - - closure_body_length - - fallthrough - - indentation_width - -# force warnings -force_cast: error -force_try: error + - closure_body_length + - empty_string + - fallthrough + - force_unwrapping + - implicitly_unwrapped_optional + - indentation_width + - legacy_objc_type + - override_in_extension + - redundant_nil_coalescing + - static_operator + - trailing_closure + - unneeded_parentheses_in_closure_argument + - weak_delegate custom_rules: - commented_out_code: - included: ".*\\.swift" # regex that defines paths to include during linting. optional. - excluded: ".*Test(s)?\\.swift" # regex that defines paths to exclude during linting. optional - name: "Commented out code" # rule name. optional. - regex: "^\\/\\/\\s*(@|\\.?([a-z]|(\\})))" # matching pattern + commented_out_code: + included: .*\.swift # regex that defines paths to include during linting. optional. + excluded: .*Test(s)?\.swift # regex that defines paths to exclude during linting. optional + name: Commented out code # rule name. optional. + regex: ^\s*(\/\/(?!\s*swiftlint:).*|\/\*[\s\S]*?\*\/) # matching pattern capture_group: 0 # number of regex capture group to highlight the rule violation at. optional. match_kinds: # SyntaxKinds to match. optional. - comment - message: "No commented code in devel branch allowed." # violation message. optional. + message: No commented code in devel branch allowed. # violation message. optional. severity: warning # violation severity. optional. diff --git a/CONTRIBUTION.md b/CONTRIBUTION.md index 5edbe93d5..be8daa9de 100644 --- a/CONTRIBUTION.md +++ b/CONTRIBUTION.md @@ -17,7 +17,7 @@ Please take it from the [roadmap](https://hackmd.io/G5znP3xAQY-BVc1X8Y1jSg) or f ## Codestyle guideline - `swiftlint` check should goes with no warnings. -- Here’s some more detailed and human readable code style [guidelines](https://hackmd.io/8bACoAnTSsKc55Os596yCg "") (you can add there some suggestion if you’d like to). +- Here’s some more detailed and human readable code style [guidelines](https://hackmd.io/8bACoAnTSsKc55Os596yCg "") (you can add there some suggestion if you’d like to). - We use [swift](https://www.swift.org/documentation/api-design-guidelines/ "") name convention. ## Tests guideline 1. Cover each new public method with tests. @@ -67,4 +67,4 @@ on: - [ ] All public method have `///` styled comments. - [ ] All magic or nonintuitive internal code parts are clearly explained in inline comments. - [ ] `swiftlint` ran have no warnings. -- [ ] No commented out code lefts in PR. \ No newline at end of file +- [ ] No commented out code lefts in PR. diff --git a/Example/myWeb3Wallet/Podfile b/Example/myWeb3Wallet/Podfile deleted file mode 100644 index 9dea1b01f..000000000 --- a/Example/myWeb3Wallet/Podfile +++ /dev/null @@ -1,30 +0,0 @@ -# Uncomment the next line to define a global platform for your project -platform :ios, '15.0' - -target 'myWeb3Wallet' do - # Comment the next line if you don't want to use dynamic frameworks - use_frameworks! - - # Pods for myWeb3Wallet -pod 'web3swift', :git => 'https://github.com/veerChauhan/web3swift.git', :branch => 'develop' - - - target 'myWeb3WalletTests' do - inherit! :search_paths - # Pods for testing - end - - target 'myWeb3WalletUITests' do - # Pods for testing - end - -end - -# set iOS deployment target for every pod to avoid warnings -post_install do |installer| - installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['IPHONEOS_DEPLOYMENT_TARGET'] = '15.0' - end - end -end diff --git a/Example/myWeb3Wallet/Podfile.lock b/Example/myWeb3Wallet/Podfile.lock deleted file mode 100644 index 5fd352276..000000000 --- a/Example/myWeb3Wallet/Podfile.lock +++ /dev/null @@ -1,53 +0,0 @@ -PODS: - - BigInt (5.2.0) - - CryptoSwift (1.4.2) - - PromiseKit (6.15.3): - - PromiseKit/CorePromise (= 6.15.3) - - PromiseKit/Foundation (= 6.15.3) - - PromiseKit/UIKit (= 6.15.3) - - PromiseKit/CorePromise (6.15.3) - - PromiseKit/Foundation (6.15.3): - - PromiseKit/CorePromise - - PromiseKit/UIKit (6.15.3): - - PromiseKit/CorePromise - - secp256k1.c (0.1.2) - - Starscream (4.0.4) - - web3swift (2.3.0): - - BigInt (~> 5.2) - - CryptoSwift (~> 1.4.0) - - PromiseKit (~> 6.15.3) - - secp256k1.c (~> 0.1) - - Starscream (~> 4.0.4) - -DEPENDENCIES: - - web3swift (from `https://github.com/veerChauhan/web3swift.git`, branch `develop`) - -SPEC REPOS: - trunk: - - BigInt - - CryptoSwift - - PromiseKit - - secp256k1.c - - Starscream - -EXTERNAL SOURCES: - web3swift: - :branch: develop - :git: https://github.com/veerChauhan/web3swift.git - -CHECKOUT OPTIONS: - web3swift: - :commit: d05a569a1dbb43b3770832cfa2be703ec26ca894 - :git: https://github.com/veerChauhan/web3swift.git - -SPEC CHECKSUMS: - BigInt: f668a80089607f521586bbe29513d708491ef2f7 - CryptoSwift: a532e74ed010f8c95f611d00b8bbae42e9fe7c17 - PromiseKit: 3b2b6995e51a954c46dbc550ce3da44fbfb563c5 - secp256k1.c: db47b726585d80f027423682eb369729e61b3b20 - Starscream: 5178aed56b316f13fa3bc55694e583d35dd414d9 - web3swift: dcc8da6f0944a062faa381869ce64114ddb5f8d3 - -PODFILE CHECKSUM: 53e3e6ef11ba247d3bee3e2fa1580cb90296aef2 - -COCOAPODS: 1.11.2 diff --git a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj index 2c39452c9..224ad4a5b 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj +++ b/Example/myWeb3Wallet/myWeb3Wallet.xcodeproj/project.pbxproj @@ -7,9 +7,7 @@ objects = { /* Begin PBXBuildFile section */ - 08D762AA7F8C96F1FEC2BDDA /* Pods_myWeb3Wallet.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D6EB035B54D0DDFE25556549 /* Pods_myWeb3Wallet.framework */; }; - 1A3D2B3177B96101E5BA3A86 /* Pods_myWeb3WalletTests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D4590F35DEE4A4CA41141602 /* Pods_myWeb3WalletTests.framework */; }; - ADDA7950DDF6B6F2FFB1F198 /* Pods_myWeb3Wallet_myWeb3WalletUITests.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2DEF494BADF9FD39D553B87D /* Pods_myWeb3Wallet_myWeb3WalletUITests.framework */; }; + D6DD90D22991966100EE140E /* web3swift in Frameworks */ = {isa = PBXBuildFile; productRef = D6DD90D12991966100EE140E /* web3swift */; }; FA5308212721D59B002C1F06 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308202721D59B002C1F06 /* AppDelegate.swift */; }; FA5308232721D59B002C1F06 /* SceneDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308222721D59B002C1F06 /* SceneDelegate.swift */; }; FA5308252721D59B002C1F06 /* ViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA5308242721D59B002C1F06 /* ViewController.swift */; }; @@ -47,14 +45,8 @@ /* Begin PBXFileReference section */ 2DEF494BADF9FD39D553B87D /* Pods_myWeb3Wallet_myWeb3WalletUITests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_myWeb3Wallet_myWeb3WalletUITests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - 5B0E97C0C8FE51D0241E7D19 /* Pods-myWeb3Wallet.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3Wallet.release.xcconfig"; path = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.release.xcconfig"; sourceTree = ""; }; - 600772647D45BC0D702D4137 /* Pods-myWeb3Wallet.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3Wallet.debug.xcconfig"; path = "Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet.debug.xcconfig"; sourceTree = ""; }; - 7574A738941D92CC94F93A9E /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig"; path = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig"; sourceTree = ""; }; - A87A2F63C4B3084139E790F5 /* Pods-myWeb3WalletTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3WalletTests.debug.xcconfig"; path = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.debug.xcconfig"; sourceTree = ""; }; D4590F35DEE4A4CA41141602 /* Pods_myWeb3WalletTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_myWeb3WalletTests.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - D6018FABA256C0117F85A829 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig"; path = "Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig"; sourceTree = ""; }; D6EB035B54D0DDFE25556549 /* Pods_myWeb3Wallet.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_myWeb3Wallet.framework; sourceTree = BUILT_PRODUCTS_DIR; }; - E41A5A8BF0A312348D3C52FD /* Pods-myWeb3WalletTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-myWeb3WalletTests.release.xcconfig"; path = "Target Support Files/Pods-myWeb3WalletTests/Pods-myWeb3WalletTests.release.xcconfig"; sourceTree = ""; }; FA53081D2721D59B002C1F06 /* myWeb3Wallet.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = myWeb3Wallet.app; sourceTree = BUILT_PRODUCTS_DIR; }; FA5308202721D59B002C1F06 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; FA5308222721D59B002C1F06 /* SceneDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SceneDelegate.swift; sourceTree = ""; }; @@ -82,7 +74,7 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 08D762AA7F8C96F1FEC2BDDA /* Pods_myWeb3Wallet.framework in Frameworks */, + D6DD90D22991966100EE140E /* web3swift in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -90,7 +82,6 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - 1A3D2B3177B96101E5BA3A86 /* Pods_myWeb3WalletTests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; @@ -98,26 +89,12 @@ isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( - ADDA7950DDF6B6F2FFB1F198 /* Pods_myWeb3Wallet_myWeb3WalletUITests.framework in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ /* Begin PBXGroup section */ - 40AC3854191B335F2FCA6C71 /* Pods */ = { - isa = PBXGroup; - children = ( - 600772647D45BC0D702D4137 /* Pods-myWeb3Wallet.debug.xcconfig */, - 5B0E97C0C8FE51D0241E7D19 /* Pods-myWeb3Wallet.release.xcconfig */, - D6018FABA256C0117F85A829 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */, - 7574A738941D92CC94F93A9E /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */, - A87A2F63C4B3084139E790F5 /* Pods-myWeb3WalletTests.debug.xcconfig */, - E41A5A8BF0A312348D3C52FD /* Pods-myWeb3WalletTests.release.xcconfig */, - ); - path = Pods; - sourceTree = ""; - }; B67819FA7D92C1562AFD65A8 /* Frameworks */ = { isa = PBXGroup; children = ( @@ -135,7 +112,6 @@ FA5308362721D59D002C1F06 /* myWeb3WalletTests */, FA5308402721D59D002C1F06 /* myWeb3WalletUITests */, FA53081E2721D59B002C1F06 /* Products */, - 40AC3854191B335F2FCA6C71 /* Pods */, B67819FA7D92C1562AFD65A8 /* Frameworks */, ); sourceTree = ""; @@ -227,17 +203,18 @@ isa = PBXNativeTarget; buildConfigurationList = FA5308472721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3Wallet" */; buildPhases = ( - 2C189F9EA9914E3A42777867 /* [CP] Check Pods Manifest.lock */, FA5308192721D59B002C1F06 /* Sources */, FA53081A2721D59B002C1F06 /* Frameworks */, FA53081B2721D59B002C1F06 /* Resources */, - 5E0CBD27780EAD115251C9AC /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); dependencies = ( ); name = myWeb3Wallet; + packageProductDependencies = ( + D6DD90D12991966100EE140E /* web3swift */, + ); productName = myWeb3Wallet; productReference = FA53081D2721D59B002C1F06 /* myWeb3Wallet.app */; productType = "com.apple.product-type.application"; @@ -246,7 +223,6 @@ isa = PBXNativeTarget; buildConfigurationList = FA53084A2721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3WalletTests" */; buildPhases = ( - 342829194E3F4C74B29C947B /* [CP] Check Pods Manifest.lock */, FA53082F2721D59D002C1F06 /* Sources */, FA5308302721D59D002C1F06 /* Frameworks */, FA5308312721D59D002C1F06 /* Resources */, @@ -265,11 +241,9 @@ isa = PBXNativeTarget; buildConfigurationList = FA53084D2721D59D002C1F06 /* Build configuration list for PBXNativeTarget "myWeb3WalletUITests" */; buildPhases = ( - 5F33F7D7F77389C37C4F1656 /* [CP] Check Pods Manifest.lock */, FA5308392721D59D002C1F06 /* Sources */, FA53083A2721D59D002C1F06 /* Frameworks */, FA53083B2721D59D002C1F06 /* Resources */, - AAF75ECFD98859A6D0818BB6 /* [CP] Embed Pods Frameworks */, ); buildRules = ( ); @@ -313,6 +287,9 @@ Base, ); mainGroup = FA5308142721D59B002C1F06; + packageReferences = ( + D6DD90D02991966100EE140E /* XCRemoteSwiftPackageReference "web3swift" */, + ); productRefGroup = FA53081E2721D59B002C1F06 /* Products */; projectDirPath = ""; projectRoot = ""; @@ -355,109 +332,6 @@ }; /* End PBXResourcesBuildPhase section */ -/* Begin PBXShellScriptBuildPhase section */ - 2C189F9EA9914E3A42777867 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-myWeb3Wallet-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; - }; - 342829194E3F4C74B29C947B /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-myWeb3WalletTests-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; - }; - 5E0CBD27780EAD115251C9AC /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet/Pods-myWeb3Wallet-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; - 5F33F7D7F77389C37C4F1656 /* [CP] Check Pods Manifest.lock */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - ); - inputPaths = ( - "${PODS_PODFILE_DIR_PATH}/Podfile.lock", - "${PODS_ROOT}/Manifest.lock", - ); - name = "[CP] Check Pods Manifest.lock"; - outputFileListPaths = ( - ); - outputPaths = ( - "$(DERIVED_FILE_DIR)/Pods-myWeb3Wallet-myWeb3WalletUITests-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; - }; - AAF75ECFD98859A6D0818BB6 /* [CP] Embed Pods Frameworks */ = { - isa = PBXShellScriptBuildPhase; - buildActionMask = 2147483647; - files = ( - ); - inputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-${CONFIGURATION}-input-files.xcfilelist", - ); - name = "[CP] Embed Pods Frameworks"; - outputFileListPaths = ( - "${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks-${CONFIGURATION}-output-files.xcfilelist", - ); - runOnlyForDeploymentPostprocessing = 0; - shellPath = /bin/sh; - shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-myWeb3Wallet-myWeb3WalletUITests/Pods-myWeb3Wallet-myWeb3WalletUITests-frameworks.sh\"\n"; - showEnvVarsInLog = 0; - }; -/* End PBXShellScriptBuildPhase section */ - /* Begin PBXSourcesBuildPhase section */ FA5308192721D59B002C1F06 /* Sources */ = { isa = PBXSourcesBuildPhase; @@ -642,7 +516,6 @@ }; FA5308482721D59D002C1F06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 600772647D45BC0D702D4137 /* Pods-myWeb3Wallet.debug.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -671,7 +544,6 @@ }; FA5308492721D59D002C1F06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 5B0E97C0C8FE51D0241E7D19 /* Pods-myWeb3Wallet.release.xcconfig */; buildSettings = { ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor; @@ -700,7 +572,6 @@ }; FA53084B2721D59D002C1F06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = A87A2F63C4B3084139E790F5 /* Pods-myWeb3WalletTests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -726,7 +597,6 @@ }; FA53084C2721D59D002C1F06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = E41A5A8BF0A312348D3C52FD /* Pods-myWeb3WalletTests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = YES; BUNDLE_LOADER = "$(TEST_HOST)"; @@ -752,7 +622,6 @@ }; FA53084E2721D59D002C1F06 /* Debug */ = { isa = XCBuildConfiguration; - baseConfigurationReference = D6018FABA256C0117F85A829 /* Pods-myWeb3Wallet-myWeb3WalletUITests.debug.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; CODE_SIGN_STYLE = Automatic; @@ -776,7 +645,6 @@ }; FA53084F2721D59D002C1F06 /* Release */ = { isa = XCBuildConfiguration; - baseConfigurationReference = 7574A738941D92CC94F93A9E /* Pods-myWeb3Wallet-myWeb3WalletUITests.release.xcconfig */; buildSettings = { ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES = "$(inherited)"; CODE_SIGN_STYLE = Automatic; @@ -838,6 +706,25 @@ defaultConfigurationName = Release; }; /* End XCConfigurationList section */ + +/* Begin XCRemoteSwiftPackageReference section */ + D6DD90D02991966100EE140E /* XCRemoteSwiftPackageReference "web3swift" */ = { + isa = XCRemoteSwiftPackageReference; + repositoryURL = "https://github.com/web3swift-team/web3swift"; + requirement = { + kind = upToNextMajorVersion; + minimumVersion = 3.0.0; + }; + }; +/* End XCRemoteSwiftPackageReference section */ + +/* Begin XCSwiftPackageProductDependency section */ + D6DD90D12991966100EE140E /* web3swift */ = { + isa = XCSwiftPackageProductDependency; + package = D6DD90D02991966100EE140E /* XCRemoteSwiftPackageReference "web3swift" */; + productName = web3swift; + }; +/* End XCSwiftPackageProductDependency section */ }; rootObject = FA5308152721D59B002C1F06 /* Project object */; } diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift index d4f88c2b0..855876d1c 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/AppDelegate.swift @@ -10,8 +10,6 @@ import UIKit @main class AppDelegate: UIResponder, UIApplicationDelegate { - - func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. return true @@ -31,6 +29,4 @@ class AppDelegate: UIResponder, UIApplicationDelegate { // Use this method to release any resources that were specific to the discarded scenes, as they will not return. } - } - diff --git a/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift index 3182cf687..4134b433b 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/Appdelegate/SceneDelegate.swift @@ -11,7 +11,6 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { var window: UIWindow? - func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`. // If using a storyboard, the `window` property will automatically be initialized and attached to the scene. @@ -47,6 +46,4 @@ class SceneDelegate: UIResponder, UIWindowSceneDelegate { // to restore the scene back to its current state. } - } - diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift index de12eaa06..cdaa670f8 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewController.swift @@ -14,6 +14,4 @@ class ViewController: UIViewController { // Do any additional setup after loading the view. } - } - diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift index fc4a8b585..cb99dd8e8 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/DashboardViewController.swift @@ -19,7 +19,6 @@ class DashboardViewController: UIViewController { } } - /* // MARK: - Navigation diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift index 6c8eef804..593b1281e 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/SplashViewController.swift @@ -10,7 +10,7 @@ import UIKit class SplashViewController: UIViewController { @IBOutlet weak var logoView: UIImageView! - + override func viewDidLoad() { super.viewDidLoad() UIView.animate(withDuration: 0.9) { @@ -18,12 +18,11 @@ class SplashViewController: UIViewController { Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.moveToWalletView), userInfo: nil, repeats: false) } - // Do any additional setup after loading the view. } - @objc func moveToWalletView(){ - + @objc func moveToWalletView() { + guard let walletScreen = self.storyboard?.instantiateViewController(withIdentifier: "WalletViewController") as? WalletViewController else { #if DEBUG printContent("Unable to get Wallet controller") diff --git a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift index c766c5758..922cd5757 100644 --- a/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift +++ b/Example/myWeb3Wallet/myWeb3Wallet/ViewControllers/WalletController/WalletViewController.swift @@ -7,14 +7,16 @@ import UIKit import web3swift +import Web3Core + class WalletViewController: UIViewController { - + @IBOutlet weak var continueButton: UIButton! @IBOutlet weak var walletAddressLabel: UILabel! @IBOutlet weak var importWalletButton: UIButton! @IBOutlet weak var createWalletButton: UIButton! var _walletAddress: String { - set{ + set { self.continueButton.isHidden = false self.walletAddressLabel.text = newValue } @@ -27,34 +29,33 @@ class WalletViewController: UIViewController { super.viewDidLoad() self.createWalletButton.layer.cornerRadius = 5.0 self.importWalletButton.layer.cornerRadius = 5.0 - + // Do any additional setup after loading the view. } - - + @IBAction func onClickCreateWallet(_ sender: UIButton) { #if DEBUG print("Clicked on Create Wallet Option") #endif self.createMnemonics() - + } @IBAction func onClickImportWalletButton(_ sender: UIButton) { print("Clicked on import Wallet Option") self.showImportALert() } - + @IBAction func onClickContinueButton(_ sender: UIButton) { print("Clicked on COntinue button") guard let dashboardScreen = self.storyboard?.instantiateViewController(withIdentifier: "DashboardViewController") as? DashboardViewController else { - #if DEBUG +#if DEBUG printContent("Unable to get Wallet controller") - #endif +#endif return } self.navigationController?.pushViewController(dashboardScreen, animated: true) } - fileprivate func showImportALert(){ + fileprivate func showImportALert() { let alert = UIAlertController(title: "MyWeb3Wallet", message: "", preferredStyle: .alert) alert.addTextField { textfied in textfied.placeholder = "Enter mnemonics/private Key" @@ -69,7 +70,7 @@ class WalletViewController: UIViewController { guard let privateKey = alert.textFields?[0].text else { return } print(privateKey) self.importWalletWith(privateKey: privateKey) - + } let cancelAction = UIAlertAction(title: "Cancel", style: .cancel) alert.addAction(mnemonicsAction) @@ -77,14 +78,14 @@ class WalletViewController: UIViewController { alert.addAction(cancelAction) self.present(alert, animated: true, completion: nil) } - func importWalletWith(privateKey: String){ + func importWalletWith(privateKey: String) { let formattedKey = privateKey.trimmingCharacters(in: .whitespacesAndNewlines) guard let dataKey = Data.fromHex(formattedKey) else { self.showAlertMessage(title: "Error", message: "Please enter a valid Private key ", actionName: "Ok") return } do { - let keystore = try EthereumKeystoreV3(privateKey: dataKey) + let keystore = try EthereumKeystoreV3(privateKey: dataKey, password: "") if let myWeb3KeyStore = keystore { let manager = KeystoreManager([myWeb3KeyStore]) let address = keystore?.addresses?.first @@ -94,7 +95,7 @@ class WalletViewController: UIViewController { #endif let walletAddress = manager.addresses?.first?.address self.walletAddressLabel.text = walletAddress ?? "0x" - + print(walletAddress) } else { print("error") @@ -109,26 +110,22 @@ class WalletViewController: UIViewController { alert.addAction(okAction) self.present(alert, animated: true) } - - - + } + func importWalletWith(mnemonics: String) { - let walletAddress = try? BIP32Keystore(mnemonics: mnemonics , prefixPath: "m/44'/77777'/0'/0") - print(walletAddress?.addresses) + let walletAddress = try? BIP32Keystore(mnemonics: mnemonics, password: "", prefixPath: "m/44'/77777'/0'/0") self.walletAddressLabel.text = "\(walletAddress?.addresses?.first?.address ?? "0x")" - } - - } + extension WalletViewController { - - fileprivate func createMnemonics(){ + + fileprivate func createMnemonics() { let userDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] let web3KeystoreManager = KeystoreManager.managerForPath(userDir + "/keystore") do { - if (web3KeystoreManager?.addresses?.count ?? 0 >= 0) { + if web3KeystoreManager?.addresses?.count ?? 0 >= 0 { let tempMnemonics = try? BIP39.generateMnemonics(bitsOfEntropy: 256, language: .english) guard let tMnemonics = tempMnemonics else { self.showAlertMessage(title: "", message: "We are unable to create wallet", actionName: "Ok") @@ -136,10 +133,10 @@ extension WalletViewController { } self._mnemonics = tMnemonics print(_mnemonics) - let tempWalletAddress = try? BIP32Keystore(mnemonics: self._mnemonics , prefixPath: "m/44'/77777'/0'/0") - print(tempWalletAddress?.addresses?.first?.address) + + let tempWalletAddress = try? BIP32Keystore(mnemonics: self._mnemonics, password: "", prefixPath: "m/44'/77777'/0'/0") guard let walletAddress = tempWalletAddress?.addresses?.first else { - self.showAlertMessage(title: "", message: "We are unable to create wallet", actionName: "Ok") + self.showAlertMessage(title: "", message: "Unable to create wallet", actionName: "Ok") return } self._walletAddress = walletAddress.address @@ -148,12 +145,12 @@ extension WalletViewController { print(privateKey, "Is the private key") #endif let keyData = try? JSONEncoder().encode(tempWalletAddress?.keystoreParams) - FileManager.default.createFile(atPath: userDir + "/keystore"+"/key.json", contents: keyData, attributes: nil) + FileManager.default.createFile(atPath: userDir + "/keystore" + "/key.json", contents: keyData, attributes: nil) } } catch { - + } - + } } extension UIViewController { @@ -163,5 +160,5 @@ extension UIViewController { alertController.addAction(action) self.present(alertController, animated: true) } - + } diff --git a/README.md b/README.md index f7f7187be..e7bb7523d 100755 --- a/README.md +++ b/README.md @@ -44,13 +44,13 @@ ## Core features -- [x] :zap: Swift implementation of [web3.js](https://github.com/ethereum/web3.js/) functionality -- [x] :thought_balloon: Interaction with remote node via **JSON RPC** +- [x] :zap: Swift implementation of [web3.js](https://github.com/ethereum/web3.js/) functionality +- [x] :thought_balloon: Interaction with remote node via **JSON RPC** - [x] 🔐 Local **keystore management** (`geth` compatible) -- [x] 🤖 Smart-contract **ABI parsing** +- [x] 🤖 Smart-contract **ABI parsing** - [x] 🔓**ABI decoding** (V2 is supported with return of structures from public functions. Part of 0.4.22 Solidity compiler) - [x] 🕸Ethereum Name Service **(ENS) support** - a secure & decentralised way to address resources both on and off the blockchain using simple, human-readable names -- [x] :arrows_counterclockwise: **Smart contracts interactions** (read/write) +- [x] :arrows_counterclockwise: **Smart contracts interactions** (read/write) - [x] ⛩ **Infura support** - [x] ⚒ **Parsing TxPool** content into native values (ethereum addresses and transactions) - easy to get pending transactions - [x] 🖇 **Event loops** functionality @@ -193,6 +193,10 @@ $ ganache This will create a local blockchain and also some test accounts that are used throughout our tests. Make sure that `ganache` is running on its default port `8546`. To change the port in test cases locate `LocalTestCase.swift` and modify the static `url` variable. +### Before you commit + +We are using [pre-commit](https://pre-commit.com) to run validations locally before a commit is created. Please, install pre-commit and run `pre-commit install` from project's root directory. After that before every commit git hook will run and execute `codespell`, `swiftlint` and other checks. + ## Contribute Want to improve? It's awesome: Then good news for you: **We are ready to pay for your contribution via [@gitcoin bot](https://gitcoin.co/grants/358/web3swift)!** diff --git a/Sources/Web3Core/EthereumABI/ABIDecoding.swift b/Sources/Web3Core/EthereumABI/ABIDecoding.swift index d03a0adb4..cb220fec6 100755 --- a/Sources/Web3Core/EthereumABI/ABIDecoding.swift +++ b/Sources/Web3Core/EthereumABI/ABIDecoding.swift @@ -21,11 +21,11 @@ extension ABIDecoder { var consumed: UInt64 = 0 for i in 0 ..< types.count { let (v, c) = decodeSingleType(type: types[i], data: data, pointer: consumed) - guard let valueUnwrapped = v, let consumedUnwrapped = c else {return nil} + guard let valueUnwrapped = v, let consumedUnwrapped = c else { return nil } toReturn.append(valueUnwrapped) consumed = consumed + consumedUnwrapped } - guard toReturn.count == types.count else {return nil} + guard toReturn.count == types.count else { return nil } return toReturn } @@ -235,23 +235,23 @@ extension ABIDecoder { let nonIndexedTypes = nonIndexedInputs.compactMap { inp -> ABI.Element.ParameterType in return inp.type } - guard logs.count == indexedInputs.count + 1 else {return nil} + guard logs.count == indexedInputs.count + 1 else { return nil } var indexedValues = [Any]() for i in 0 ..< indexedInputs.count { let data = logs[i+1] let input = indexedInputs[i] if !input.type.isStatic || input.type.isArray || input.type.memoryUsage != 32 { let (v, _) = ABIDecoder.decodeSingleType(type: .bytes(length: 32), data: data) - guard let valueUnwrapped = v else {return nil} + guard let valueUnwrapped = v else { return nil } indexedValues.append(valueUnwrapped) } else { let (v, _) = ABIDecoder.decodeSingleType(type: input.type, data: data) - guard let valueUnwrapped = v else {return nil} + guard let valueUnwrapped = v else { return nil } indexedValues.append(valueUnwrapped) } } let v = ABIDecoder.decode(types: nonIndexedTypes, data: dataForProcessing) - guard let nonIndexedValues = v else {return nil} + guard let nonIndexedValues = v else { return nil } var indexedInputCounter = 0 var nonIndexedInputCounter = 0 for i in 0 ..< event.inputs.count { diff --git a/Sources/Web3Core/EthereumABI/ABIElements.swift b/Sources/Web3Core/EthereumABI/ABIElements.swift index e2ca9202b..cdf38ba38 100755 --- a/Sources/Web3Core/EthereumABI/ABIElements.swift +++ b/Sources/Web3Core/EthereumABI/ABIElements.swift @@ -215,7 +215,7 @@ extension ABI.Element.Function { extension ABI.Element.Event { public func decodeReturnedLogs(eventLogTopics: [Data], eventLogData: Data) -> [String: Any]? { - guard let eventContent = ABIDecoder.decodeLog(event: self, eventLogTopics: eventLogTopics, eventLogData: eventLogData) else {return nil} + guard let eventContent = ABIDecoder.decodeLog(event: self, eventLogTopics: eventLogTopics, eventLogData: eventLogData) else { return nil } return eventContent } } @@ -274,35 +274,35 @@ extension ABI.Element.Function { /// /// Return cases: /// - when no `outputs` declared and `data` is not an error response: - ///```swift - ///["_success": true] - ///``` + /// ```swift + /// ["_success": true] + /// ``` /// - when `outputs` declared and decoding completed successfully: - ///```swift - ///["_success": true, "0": value_1, "1": value_2, ...] - ///``` - ///Additionally this dictionary will have mappings to output names if these names are specified in the ABI; + /// ```swift + /// ["_success": true, "0": value_1, "1": value_2, ...] + /// ``` + /// Additionally this dictionary will have mappings to output names if these names are specified in the ABI; /// - function call was aborted using `revert(message)` or `require(expression, message)`: - ///```swift - ///["_success": false, "_abortedByRevertOrRequire": true, "_errorMessage": message]` - ///``` + /// ```swift + /// ["_success": false, "_abortedByRevertOrRequire": true, "_errorMessage": message]` + /// ``` /// - function call was aborted using `revert CustomMessage()` and `errors` argument contains the ABI of that custom error type: - ///```swift - ///["_success": false, - ///"_abortedByRevertOrRequire": true, - ///"_error": error_name_and_types, // e.g. `MyCustomError(uint256, address senderAddress)` - ///"0": error_arg1, - ///"1": error_arg2, - ///..., - ///"error_arg1_name": error_arg1, // Only named arguments will be mapped to their names, e.g. `"senderAddress": EthereumAddress` - ///"error_arg2_name": error_arg2, // Otherwise, you can query them by position index. - ///...] - ///``` - ///- in case of any error: - ///```swift - ///["_success": false, "_failureReason": String] - ///``` - ///Error reasons include: + /// ```swift + /// ["_success": false, + /// "_abortedByRevertOrRequire": true, + /// "_error": error_name_and_types, // e.g. `MyCustomError(uint256, address senderAddress)` + /// "0": error_arg1, + /// "1": error_arg2, + /// ..., + /// "error_arg1_name": error_arg1, // Only named arguments will be mapped to their names, e.g. `"senderAddress": EthereumAddress` + /// "error_arg2_name": error_arg2, // Otherwise, you can query them by position index. + /// ...] + /// ``` + /// - in case of any error: + /// ```swift + /// ["_success": false, "_failureReason": String] + /// ``` + /// Error reasons include: /// - `outputs` declared but at least one value failed to be decoded; /// - `data.count` is less than `outputs.count * 32`; /// - `outputs` defined and `data` is empty; @@ -467,7 +467,6 @@ extension ABIDecoder { } var returnArray = [String: Any]() - if data.count == 0 && inputs.count == 1 { let name = "0" let value = inputs[0].type.emptyValue @@ -479,7 +478,7 @@ extension ABIDecoder { guard inputs.count * 32 <= data.count else { return nil } var i = 0 - guard let values = ABIDecoder.decode(types: inputs, data: data) else {return nil} + guard let values = ABIDecoder.decode(types: inputs, data: data) else { return nil } for input in inputs { let name = "\(i)" returnArray[name] = values[i] @@ -491,4 +490,4 @@ extension ABIDecoder { } return returnArray } -} \ No newline at end of file +} diff --git a/Sources/Web3Core/EthereumABI/ABIEncoding.swift b/Sources/Web3Core/EthereumABI/ABIEncoding.swift index 3b61da8c5..5ce2183d3 100755 --- a/Sources/Web3Core/EthereumABI/ABIEncoding.swift +++ b/Sources/Web3Core/EthereumABI/ABIEncoding.swift @@ -119,7 +119,7 @@ public struct ABIEncoder { case let d as [IntegerLiteralType]: var bytesArray = [UInt8]() for el in d { - guard el >= 0, el <= 255 else {return nil} + guard el >= 0, el <= 255 else { return nil } bytesArray.append(UInt8(el)) } return Data(bytesArray) @@ -140,7 +140,7 @@ public struct ABIEncoder { /// - `types.count != values.count`; /// - encoding of at least one value has failed (e.g. type mismatch). public static func encode(types: [ABI.Element.InOut], values: [Any]) -> Data? { - guard types.count == values.count else {return nil} + guard types.count == values.count else { return nil } let params = types.compactMap { el -> ABI.Element.ParameterType in return el.type } @@ -156,12 +156,12 @@ public struct ABIEncoder { /// - `types.count != values.count`; /// - encoding of at least one value has failed (e.g. type mismatch). public static func encode(types: [ABI.Element.ParameterType], values: [Any]) -> Data? { - guard types.count == values.count else {return nil} + guard types.count == values.count else { return nil } var tails = [Data]() var heads = [Data]() for i in 0 ..< types.count { let enc = encodeSingleType(type: types[i], value: values[i]) - guard let encoding = enc else {return nil} + guard let encoding = enc else { return nil } if types[i].isStatic { heads.append(encoding) tails.append(Data()) @@ -181,7 +181,7 @@ public struct ABIEncoder { let head = heads[i] let tail = tails[i] if !types[i].isStatic { - guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + guard let newHead = tailsPointer.abiEncode(bits: 256) else { return nil } headsConcatenated.append(newHead) tailsConcatenated.append(tail) tailsPointer = tailsPointer + BigUInt(tail.count) @@ -227,7 +227,7 @@ public struct ABIEncoder { return bigint == nil ? nil : bigint!.abiEncode(bits: 256) case .address: if let string = value as? String { - guard let address = EthereumAddress(string) else {return nil} + guard let address = EthereumAddress(string) else { return nil } let data = address.addressData return data.setLengthLeft(32) } else if let address = value as? EthereumAddress { @@ -295,7 +295,7 @@ public struct ABIEncoder { var heads = [Data]() for i in 0 ..< val.count { let enc = encodeSingleType(type: subType, value: val[i]) - guard let encoding = enc else {return nil} + guard let encoding = enc else { return nil } heads.append(Data(repeating: 0x0, count: 32)) tails.append(encoding) } @@ -310,7 +310,7 @@ public struct ABIEncoder { let head = heads[i] let tail = tails[i] if tail != Data() { - guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + guard let newHead = tailsPointer.abiEncode(bits: 256) else { return nil } headsConcatenated.append(newHead) tailsConcatenated.append(tail) tailsPointer = tailsPointer + BigUInt(tail.count) @@ -342,7 +342,7 @@ public struct ABIEncoder { var heads = [Data]() for i in 0 ..< val.count { let enc = encodeSingleType(type: subType, value: val[i]) - guard let encoding = enc else {return nil} + guard let encoding = enc else { return nil } heads.append(Data(repeating: 0x0, count: 32)) tails.append(encoding) } @@ -355,7 +355,7 @@ public struct ABIEncoder { var tailsConcatenated = Data() for i in 0 ..< val.count { let tail = tails[i] - guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + guard let newHead = tailsPointer.abiEncode(bits: 256) else { return nil } headsConcatenated.append(newHead) tailsConcatenated.append(tail) tailsPointer = tailsPointer + BigUInt(tail.count) @@ -372,7 +372,7 @@ public struct ABIEncoder { guard let val = value as? [Any] else {break} for i in 0 ..< subTypes.count { let enc = encodeSingleType(type: subTypes[i], value: val[i]) - guard let encoding = enc else {return nil} + guard let encoding = enc else { return nil } if subTypes[i].isStatic { heads.append(encoding) tails.append(Data()) @@ -392,7 +392,7 @@ public struct ABIEncoder { let head = heads[i] let tail = tails[i] if !subTypes[i].isStatic { - guard let newHead = tailsPointer.abiEncode(bits: 256) else {return nil} + guard let newHead = tailsPointer.abiEncode(bits: 256) else { return nil } headsConcatenated.append(newHead) tailsConcatenated.append(tail) tailsPointer = tailsPointer + BigUInt(tail.count) diff --git a/Sources/Web3Core/EthereumAddress/EthereumAddress.swift b/Sources/Web3Core/EthereumAddress/EthereumAddress.swift index 2e8d0ef45..ddc54b963 100755 --- a/Sources/Web3Core/EthereumAddress/EthereumAddress.swift +++ b/Sources/Web3Core/EthereumAddress/EthereumAddress.swift @@ -63,7 +63,7 @@ public struct EthereumAddress: Equatable { /// represented as `ASCII` data. Otherwise, checksummed address is returned with `0x` prefix. public static func toChecksumAddress(_ addr: String) -> String? { let address = addr.lowercased().stripHexPrefix() - guard let hash = address.data(using: .ascii)?.sha3(.keccak256).toHexString().stripHexPrefix() else {return nil} + guard let hash = address.data(using: .ascii)?.sha3(.keccak256).toHexString().stripHexPrefix() else { return nil } var ret = "0x" for (i, char) in address.enumerated() { @@ -71,7 +71,7 @@ public struct EthereumAddress: Equatable { let endIdx = hash.index(hash.startIndex, offsetBy: i+1) let hashChar = String(hash[startIdx..= 8 { ret += c.uppercased() } else { @@ -96,8 +96,8 @@ extension EthereumAddress { public init?(_ addressString: String, type: AddressType = .normal, ignoreChecksum: Bool = false) { switch type { case .normal: - guard let data = Data.fromHex(addressString) else {return nil} - guard data.count == 20 else {return nil} + guard let data = Data.fromHex(addressString) else { return nil } + guard data.count == 20 else { return nil } if !addressString.hasHexPrefix() { return nil } @@ -113,7 +113,7 @@ extension EthereumAddress { return } else { let checksummedAddress = EthereumAddress.toChecksumAddress(data.toHexString().addHexPrefix()) - guard checksummedAddress == addressString else {return nil} + guard checksummedAddress == addressString else { return nil } self._address = data.toHexString().addHexPrefix() self.type = .normal return @@ -131,7 +131,7 @@ extension EthereumAddress { } public init?(_ addressData: Data, type: AddressType = .normal) { - guard addressData.count == 20 else {return nil} + guard addressData.count == 20 else { return nil } self._address = addressData.toHexString().addHexPrefix() self.type = type } @@ -155,3 +155,16 @@ extension EthereumAddress: Codable { extension EthereumAddress: Hashable { } extension EthereumAddress: APIResultType { } + +// MARK: - CustomStringConvertible + +extension EthereumAddress: CustomStringConvertible { + /// Used when converting an instance to a string + public var description: String { + var toReturn = "" + toReturn += "EthereumAddress" + "\n" + toReturn += "type: " + String(describing: type) + "\n" + toReturn += "address: " + String(describing: address) + "\n" + return toReturn + } +} diff --git a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+ComputedProperties.swift b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+ComputedProperties.swift index 1b53a2b8e..cfa7f5190 100644 --- a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+ComputedProperties.swift +++ b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+ComputedProperties.swift @@ -1,6 +1,6 @@ // // APIRequest+ComputedProperties.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // diff --git a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+Methods.swift b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+Methods.swift index 463cd60d5..58e13aa0f 100644 --- a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+Methods.swift +++ b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+Methods.swift @@ -1,6 +1,6 @@ // // APIRequest+Methods.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // diff --git a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+UtilityTypes.swift b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+UtilityTypes.swift index 6c54fb887..ca55d622f 100644 --- a/Sources/Web3Core/EthereumNetwork/Request/APIRequest+UtilityTypes.swift +++ b/Sources/Web3Core/EthereumNetwork/Request/APIRequest+UtilityTypes.swift @@ -1,6 +1,6 @@ // // APIRequest+UtilityTypes.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // diff --git a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+Encodable.swift b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+Encodable.swift index a683d5fdc..835048fbf 100644 --- a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+Encodable.swift +++ b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+Encodable.swift @@ -8,23 +8,23 @@ import Foundation extension RequestParameter: Encodable { - /** - This encoder encodes `RequestParameter` associated value ignoring self value - - This is required to encode mixed types array, like - - ```swift - let someArray: [RequestParameter] = [ - .init(rawValue: 12)!, - .init(rawValue: "this")!, - .init(rawValue: 12.2)!, - .init(rawValue: [12.2, 12.4])! - ] - let encoded = try JSONEncoder().encode(someArray) - print(String(data: encoded, encoding: .utf8)!) - //> [12,\"this\",12.2,[12.2,12.4]]` - ``` - */ + + /// This encoder encodes `RequestParameter` associated value ignoring self value + /// + /// This is required to encode mixed types array, like + /// + /// ```swift + /// let someArray: [RequestParameter] = [ + /// .init(rawValue: 12)!, + /// .init(rawValue: "this")!, + /// .init(rawValue: 12.2)!, + /// .init(rawValue: [12.2, 12.4])! + /// ] + /// let encoded = try JSONEncoder().encode(someArray) + /// print(String(data: encoded, encoding: .utf8)!) + /// //> [12,\"this\",12.2,[12.2,12.4]]` + /// ``` + /// - Parameter encoder: The encoder to write data to. func encode(to encoder: Encoder) throws { var enumContainer = encoder.singleValueContainer() /// force casting in this switch is safe because diff --git a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+RawRepresentable.swift b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+RawRepresentable.swift index 5cdad289f..ef04032ba 100644 --- a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+RawRepresentable.swift +++ b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter+RawRepresentable.swift @@ -8,14 +8,15 @@ import Foundation extension RequestParameter: RawRepresentable { - /** - This init is required by ``RawRepresentable`` protocol, which is required to encode mixed type values array in JSON. - This protocol is used to implement custom `encode` method for that enum, - which encodes an array of self-assosiated values. - - You're totally free to use explicit and more convenience member init as `RequestParameter.int(12)` in your code. - */ + /// This init is required by ``RawRepresentable`` protocol, which is required + /// to encode mixed type values array in JSON. + /// + /// This protocol is used to implement custom `encode` method for that enum, + /// which encodes an array of self-assosiated values. + /// + /// You're totally free to use explicit and more convenience member init as `RequestParameter.int(12)` in your code. + /// - Parameter rawValue: one of the supported types like `Int`, `UInt` etc. init?(rawValue: APIRequestParameterType) { /// force casting in this switch is safe because /// each `rawValue` forced to casts only in exact case which is runs based on `rawValues` type diff --git a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter.swift b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter.swift index 65c3059fa..ff0d526a6 100644 --- a/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter.swift +++ b/Sources/Web3Core/EthereumNetwork/RequestParameter/RequestParameter.swift @@ -1,39 +1,41 @@ // // RequestParameter.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // import Foundation -/** - Enum to compose request to the node params. - - In most cases request params are passed to Ethereum JSON RPC request as array of mixed type values, such as `[12,"this",true]`. - - Meanwhile swift don't provide strict way to compose such array it gives some hacks to solve this task - and one of them is using `RawRepresentable` protocol. - - This protocol allows the designated type to represent itself in `String` representation. - - So in our case we're using it to implement custom `encode` method for all possible types used as request params. - - This `encode` method is required to encode array of `RequestParameter` to not to `[RequestParameter.int(1)]`, but to `[1]`. - - Here's an example of using this enum in field. - ```swift - let jsonRPCParams: [APIRequestParameterType] = [ - .init(rawValue: 12)!, - .init(rawValue: "this")!, - .init(rawValue: 12.2)!, - .init(rawValue: [12.2, 12.4])! - ] - let encoded = try JSONEncoder().encode(jsonRPCParams) - print(String(data: encoded, encoding: .utf8)!) - //> [12,\"this\",12.2,[12.2,12.4]]` - ``` - */ +/// Enum to compose request to the node params. +/// +/// In most cases request params are passed to Ethereum JSON RPC request as array of +/// mixed type values, such as `[12,"this",true]`. +/// +/// Meanwhile swift don't provide strict way to compose such array it gives +/// some hacks to solve this task +/// and one of them is using `RawRepresentable` protocol. +/// +/// This protocol allows the designated type to represent itself in `String` representation. +/// +/// So in our case we're using it to implement custom `encode` method for all possible +/// types used as request params. +/// +/// This `encode` method is required to encode array of `RequestParameter` +/// to not to `[RequestParameter.int(1)]`, but to `[1]`. +/// +/// Here's an example of using this enum in field. +/// ```swift +/// let jsonRPCParams: [APIRequestParameterType] = [ +/// .init(rawValue: 12)!, +/// .init(rawValue: "this")!, +/// .init(rawValue: 12.2)!, +/// .init(rawValue: [12.2, 12.4])! +/// ] +/// let encoded = try JSONEncoder().encode(jsonRPCParams) +/// print(String(data: encoded, encoding: .utf8)!) +/// //> [12,\"this\",12.2,[12.2,12.4]]` +/// ``` enum RequestParameter { case int(Int) case intArray([Int]) diff --git a/Sources/Web3Core/EthereumNetwork/Utility/Async+BackwardCapability.swift b/Sources/Web3Core/EthereumNetwork/Utility/Async+BackwardCapability.swift index 46658db72..e6b67ae83 100644 --- a/Sources/Web3Core/EthereumNetwork/Utility/Async+BackwardCapability.swift +++ b/Sources/Web3Core/EthereumNetwork/Utility/Async+BackwardCapability.swift @@ -1,6 +1,6 @@ // // Async+BackwardCapability.swift -// +// // // Created by Yaroslav Yashin on 05.06.2022. // diff --git a/Sources/Web3Core/EthereumNetwork/Utility/HexDecodable+Extensions.swift b/Sources/Web3Core/EthereumNetwork/Utility/HexDecodable+Extensions.swift index 27db82dee..d64bb9a09 100644 --- a/Sources/Web3Core/EthereumNetwork/Utility/HexDecodable+Extensions.swift +++ b/Sources/Web3Core/EthereumNetwork/Utility/HexDecodable+Extensions.swift @@ -1,6 +1,6 @@ // // HexDecodable+Extensions.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // diff --git a/Sources/Web3Core/EthereumNetwork/Utility/IntegerInitableWithRadix.swift b/Sources/Web3Core/EthereumNetwork/Utility/IntegerInitableWithRadix.swift index c02e14650..299cdc276 100644 --- a/Sources/Web3Core/EthereumNetwork/Utility/IntegerInitableWithRadix.swift +++ b/Sources/Web3Core/EthereumNetwork/Utility/IntegerInitableWithRadix.swift @@ -1,6 +1,6 @@ // // IntegerInitableWithRadix.swift -// +// // // Created by Yaroslav Yashin on 12.07.2022. // diff --git a/Sources/Web3Core/KeystoreManager/BIP32HDNode.swift b/Sources/Web3Core/KeystoreManager/BIP32HDNode.swift old mode 100755 new mode 100644 index fd86f1a54..6a57a8e43 --- a/Sources/Web3Core/KeystoreManager/BIP32HDNode.swift +++ b/Sources/Web3Core/KeystoreManager/BIP32HDNode.swift @@ -9,8 +9,7 @@ import CryptoSwift extension UInt32 { public func serialize32() -> Data { - let uint32 = UInt32(self) - var bigEndian = uint32.bigEndian + var bigEndian = self.bigEndian let count = MemoryLayout.size let bytePtr = withUnsafePointer(to: &bigEndian) { $0.withMemoryRebound(to: UInt8.self, capacity: count) { @@ -24,11 +23,11 @@ extension UInt32 { public class HDNode { public struct HDversion { + // swiftlint:disable force_unwrapping public var privatePrefix: Data = Data.fromHex("0x0488ADE4")! public var publicPrefix: Data = Data.fromHex("0x0488B21E")! - public init() { - - } + // swiftlint:enable force_unwrapping + public init() {} } public var path: String? = "m" public var privateKey: Data? @@ -38,23 +37,17 @@ public class HDNode { public var parentFingerprint: Data = Data(repeating: 0, count: 4) public var childNumber: UInt32 = UInt32(0) public var isHardened: Bool { - get { - return self.childNumber >= (UInt32(1) << 31) - } + childNumber >= (UInt32(1) << 31) } public var index: UInt32 { - get { if self.isHardened { - return self.childNumber - (UInt32(1) << 31) + return childNumber - (UInt32(1) << 31) } else { - return self.childNumber + return childNumber } - } } public var hasPrivate: Bool { - get { - return privateKey != nil - } + privateKey != nil } init() { @@ -69,7 +62,7 @@ public class HDNode { } public init?(_ data: Data) { - guard data.count == 82 else {return nil} + guard data.count == 82 else { return nil } let header = data[0..<4] var serializePrivate = false if header == HDNode.HDversion().privatePrefix { @@ -81,30 +74,33 @@ public class HDNode { chaincode = data[13..<45] if serializePrivate { privateKey = data[46..<78] - guard let pubKey = Utilities.privateToPublic(privateKey!, compressed: true) else {return nil} - if pubKey[0] != 0x02 && pubKey[0] != 0x03 {return nil} + guard + let privateKey = privateKey, + let pubKey = Utilities.privateToPublic(privateKey, compressed: true), + (pubKey[0] == 0x02 || pubKey[0] == 0x03) + else { return nil } publicKey = pubKey } else { publicKey = data[45..<78] } let hashedData = data[0..<78].sha256().sha256() let checksum = hashedData[0..<4] - if checksum != data[78..<82] {return nil} + if checksum != data[78..<82] { return nil } } public init?(seed: Data) { - guard seed.count >= 16 else {return nil} + guard seed.count >= 16 else { return nil } + // swiftlint:disable force_unwrapping let hmacKey = "Bitcoin seed".data(using: .ascii)! - let hmac: Authenticator = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha2(.sha512)) - guard let entropy = try? hmac.authenticate(seed.bytes) else {return nil} - guard entropy.count == 64 else { return nil} + let hmac = HMAC(key: hmacKey.bytes, variant: HMAC.Variant.sha2(.sha512)) + guard let entropy = try? hmac.authenticate(seed.bytes), entropy.count == 64 else { return nil } let I_L = entropy[0..<32] let I_R = entropy[32..<64] chaincode = Data(I_R) let privKeyCandidate = Data(I_L) - guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else {return nil} - guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else {return nil} - guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} + guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else { return nil } + guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else { return nil } + guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else { return nil } publicKey = pubKeyCandidate privateKey = privKeyCandidate depth = 0x00 @@ -112,6 +108,7 @@ public class HDNode { } private static var curveOrder = BigUInt("FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", radix: 16)! + // swiftlint:enable force_unwrapping public static var defaultPath: String = "m/44'/60'/0'/0" public static var defaultPathPrefix: String = "m/44'/60'/0'" public static var defaultPathMetamask: String = "m/44'/60'/0'/0/0" @@ -120,130 +117,15 @@ public class HDNode { } extension HDNode { - public func derive (index: UInt32, derivePrivateKey: Bool, hardened: Bool = false) -> HDNode? { + public func derive(index: UInt32, derivePrivateKey: Bool, hardened: Bool = false) -> HDNode? { if derivePrivateKey { - if self.hasPrivate { // derive private key when is itself extended private key - var entropy: [UInt8] - var trueIndex: UInt32 - if index >= (UInt32(1) << 31) || hardened { - trueIndex = index - if trueIndex < (UInt32(1) << 31) { - trueIndex = trueIndex + (UInt32(1) << 31) - } - let hmac: Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512)) - var inputForHMAC = Data() - inputForHMAC.append(Data([UInt8(0x00)])) - inputForHMAC.append(self.privateKey!) - inputForHMAC.append(trueIndex.serialize32()) - guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } - guard ent.count == 64 else { return nil } - entropy = ent - } else { - trueIndex = index - let hmac: Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512)) - var inputForHMAC = Data() - inputForHMAC.append(self.publicKey) - inputForHMAC.append(trueIndex.serialize32()) - guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } - guard ent.count == 64 else { return nil } - entropy = ent - } - let I_L = entropy[0..<32] - let I_R = entropy[32..<64] - let cc = Data(I_R) - let bn = BigUInt(Data(I_L)) - if bn > HDNode.curveOrder { - if trueIndex < UInt32.max { - return self.derive(index: index+1, derivePrivateKey: derivePrivateKey, hardened: hardened) - } - return nil - } - let newPK = (bn + BigUInt(self.privateKey!)) % HDNode.curveOrder - if newPK == BigUInt(0) { - if trueIndex < UInt32.max { - return self.derive(index: index+1, derivePrivateKey: derivePrivateKey, hardened: hardened) - } - return nil - } - guard let privKeyCandidate = newPK.serialize().setLengthLeft(32) else {return nil} - guard SECP256K1.verifyPrivateKey(privateKey: privKeyCandidate) else {return nil } - guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: privKeyCandidate, compressed: true) else {return nil} - guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} - guard self.depth < UInt8.max else {return nil} - let newNode = HDNode() - newNode.chaincode = cc - newNode.depth = self.depth + 1 - newNode.publicKey = pubKeyCandidate - newNode.privateKey = privKeyCandidate - newNode.childNumber = trueIndex - guard let fprint = try? RIPEMD160.hash(message: self.publicKey.sha256())[0..<4] else { - return nil - } - newNode.parentFingerprint = fprint - var newPath = String() - if newNode.isHardened { - newPath = self.path! + "/" - newPath += String(newNode.index % HDNode.hardenedIndexPrefix) + "'" - } else { - newPath = self.path! + "/" + String(newNode.index) - } - newNode.path = newPath - return newNode - } else { - return nil // derive private key when is itself extended public key (impossible) - } - } else { // deriving only the public key - var entropy: [UInt8] // derive public key when is itself public key - if index >= (UInt32(1) << 31) || hardened { - return nil // no derivation of hardened public key from extended public key - } else { - let hmac: Authenticator = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512)) - var inputForHMAC = Data() - inputForHMAC.append(self.publicKey) - inputForHMAC.append(index.serialize32()) - guard let ent = try? hmac.authenticate(inputForHMAC.bytes) else {return nil } - guard ent.count == 64 else { return nil } - entropy = ent - } - let I_L = entropy[0..<32] - let I_R = entropy[32..<64] - let cc = Data(I_R) - let bn = BigUInt(Data(I_L)) - if bn > HDNode.curveOrder { - if index < UInt32.max { - return self.derive(index: index+1, derivePrivateKey: derivePrivateKey, hardened: hardened) - } - return nil - } - guard let tempKey = bn.serialize().setLengthLeft(32) else {return nil} - guard SECP256K1.verifyPrivateKey(privateKey: tempKey) else {return nil } - guard let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: tempKey, compressed: true) else {return nil} - guard pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03 else {return nil} - guard let newPublicKey = SECP256K1.combineSerializedPublicKeys(keys: [self.publicKey, pubKeyCandidate], outputCompressed: true) else {return nil} - guard newPublicKey.bytes[0] == 0x02 || newPublicKey.bytes[0] == 0x03 else {return nil} - guard self.depth < UInt8.max else {return nil} - let newNode = HDNode() - newNode.chaincode = cc - newNode.depth = self.depth + 1 - newNode.publicKey = newPublicKey - newNode.childNumber = index - guard let fprint = try? RIPEMD160.hash(message: self.publicKey.sha256())[0..<4] else { - return nil - } - newNode.parentFingerprint = fprint - var newPath = String() - if newNode.isHardened { - newPath = self.path! + "/" - newPath += String(newNode.index % HDNode.hardenedIndexPrefix) + "'" - } else { - newPath = self.path! + "/" + String(newNode.index) - } - newNode.path = newPath - return newNode + return self.derivePrivateKey(index: index, hardened: hardened) + } else { + return derivePublicKey(index: index, hardened: hardened) } } - public func derive (path: String, derivePrivateKey: Bool = true) -> HDNode? { + public func derive(path: String, derivePrivateKey: Bool = true) -> HDNode? { let components = path.components(separatedBy: "/") var currentNode: HDNode = self var firstComponent = 0 @@ -255,37 +137,165 @@ extension HDNode { if component.hasSuffix("'") { hardened = true } - guard let index = UInt32(component.trimmingCharacters(in: CharacterSet(charactersIn: "'"))) else {return nil} - guard let newNode = currentNode.derive(index: index, derivePrivateKey: derivePrivateKey, hardened: hardened) else {return nil} + guard let index = UInt32(component.trimmingCharacters(in: CharacterSet(charactersIn: "'"))) else { return nil } + guard let newNode = currentNode.derive(index: index, derivePrivateKey: derivePrivateKey, hardened: hardened) else { return nil } currentNode = newNode } return currentNode } + /// Derive public key when is itself private key. + /// Derivation of private key when is itself extended public key is impossible and will return `nil`. + private func derivePrivateKey(index: UInt32, hardened: Bool) -> HDNode? { + guard let privateKey = privateKey else { + // derive private key when is itself extended public key (impossible) + return nil + } + + var trueIndex = index + if trueIndex < (UInt32(1) << 31) && hardened { + trueIndex += (UInt32(1) << 31) + } + + guard let entropy = calculateEntropy(index: trueIndex, privateKey: privateKey, hardened: hardened) else { return nil } + + let I_L = entropy[0..<32] + let I_R = entropy[32..<64] + let chainCode = Data(I_R) + let bn = BigUInt(Data(I_L)) + if bn > HDNode.curveOrder { + if trueIndex < UInt32.max { + return self.derive(index: index + 1, derivePrivateKey: true, hardened: hardened) + } + return nil + } + let newPK = (bn + BigUInt(privateKey)) % HDNode.curveOrder + if newPK == BigUInt(0) { + if trueIndex < UInt32.max { + return self.derive(index: index + 1, derivePrivateKey: true, hardened: hardened) + } + return nil + } + + guard + let newPrivateKey = newPK.serialize().setLengthLeft(32), + SECP256K1.verifyPrivateKey(privateKey: newPrivateKey), + let newPublicKey = SECP256K1.privateToPublic(privateKey: newPrivateKey, compressed: true), + (newPublicKey.bytes[0] == 0x02 || newPublicKey.bytes[0] == 0x03), + self.depth < UInt8.max + else { return nil } + return createNode(chainCode: chainCode, depth: depth + 1, publicKey: newPublicKey, privateKey: newPrivateKey, childNumber: trueIndex) + } + + /// Derive public key when is itself public key. + /// No derivation of hardened public key from extended public key is allowed. + private func derivePublicKey(index: UInt32, hardened: Bool) -> HDNode? { + if index >= (UInt32(1) << 31) || hardened { + // no derivation of hardened public key from extended public key + return nil + } + + guard let entropy = calculateEntropy(index: index, hardened: hardened) else { return nil } + + let I_L = entropy[0..<32] + let I_R = entropy[32..<64] + let chainCode = Data(I_R) + let bn = BigUInt(Data(I_L)) + if bn > HDNode.curveOrder { + if index < UInt32.max { + return self.derive(index: index+1, derivePrivateKey: false, hardened: hardened) + } + return nil + } + + guard + let tempKey = bn.serialize().setLengthLeft(32), + SECP256K1.verifyPrivateKey(privateKey: tempKey), + let pubKeyCandidate = SECP256K1.privateToPublic(privateKey: tempKey, compressed: true), + (pubKeyCandidate.bytes[0] == 0x02 || pubKeyCandidate.bytes[0] == 0x03), + let newPublicKey = SECP256K1.combineSerializedPublicKeys(keys: [self.publicKey, pubKeyCandidate], outputCompressed: true), + (newPublicKey.bytes[0] == 0x02 || newPublicKey.bytes[0] == 0x03), + self.depth < UInt8.max + else { return nil } + + return createNode(chainCode: chainCode, depth: depth + 1, publicKey: newPublicKey, childNumber: index) + } + + private func createNode(chainCode: Data, depth: UInt8, publicKey: Data, privateKey: Data? = nil, childNumber: UInt32) -> HDNode? { + let newNode = HDNode() + newNode.chaincode = chainCode + newNode.depth = depth + newNode.publicKey = publicKey + newNode.privateKey = privateKey + newNode.childNumber = childNumber + guard + let fprint = try? RIPEMD160.hash(message: self.publicKey.sha256())[0..<4], + let path = path + else { return nil } + newNode.parentFingerprint = fprint + var newPath = String() + if newNode.isHardened { + newPath = path + "/" + newPath += String(newNode.index % HDNode.hardenedIndexPrefix) + "'" + } else { + newPath = path + "/" + String(newNode.index) + } + newNode.path = newPath + return newNode + } + + private func calculateHMACInput(_ index: UInt32, privateKey: Data? = nil, hardened: Bool) -> Data { + var inputForHMAC = Data() + + if let privateKey = privateKey, (index >= (UInt32(1) << 31) || hardened) { + inputForHMAC.append(Data([UInt8(0x00)])) + inputForHMAC.append(privateKey) + } else { + inputForHMAC.append(self.publicKey) + } + + inputForHMAC.append(index.serialize32()) + return inputForHMAC + } + + /// Calculates entropy used for private or public key derivation. + /// - Parameters: + /// - index: index + /// - privateKey: private key data or `nil` if entropy is calculated for a public key; + /// - hardened: is hardened key + /// - Returns: 64 bytes entropy or `nil`. + private func calculateEntropy(index: UInt32, privateKey: Data? = nil, hardened: Bool) -> [UInt8]? { + let inputForHMAC = calculateHMACInput(index, privateKey: privateKey, hardened: hardened) + let hmac = HMAC(key: self.chaincode.bytes, variant: .sha2(.sha512)) + guard let entropy = try? hmac.authenticate(inputForHMAC.bytes), entropy.count == 64 else { return nil } + return entropy + } + public func serializeToString(serializePublic: Bool = true, version: HDversion = HDversion()) -> String? { - guard let data = self.serialize(serializePublic: serializePublic, version: version) else {return nil} - let encoded = Base58.base58FromBytes(data.bytes) - return encoded + guard let data = self.serialize(serializePublic: serializePublic, version: version) else { return nil } + return Base58.base58FromBytes(data.bytes) } public func serialize(serializePublic: Bool = true, version: HDversion = HDversion()) -> Data? { var data = Data() - if !serializePublic && !self.hasPrivate {return nil} + /// Public or private key + let keyData: Data if serializePublic { + keyData = publicKey data.append(version.publicPrefix) } else { + guard let privateKey = privateKey else { return nil } + keyData = privateKey data.append(version.privatePrefix) } - data.append(contentsOf: [self.depth]) - data.append(self.parentFingerprint) - data.append(self.childNumber.serialize32()) - data.append(self.chaincode) - if serializePublic { - data.append(self.publicKey) - } else { + data.append(contentsOf: [depth]) + data.append(parentFingerprint) + data.append(childNumber.serialize32()) + data.append(chaincode) + if !serializePublic { data.append(contentsOf: [0x00]) - data.append(self.privateKey!) } + data.append(keyData) let hashedData = data.sha256().sha256() let checksum = hashedData[0..<4] data.append(checksum) diff --git a/Sources/Web3Core/KeystoreManager/BIP32Keystore.swift b/Sources/Web3Core/KeystoreManager/BIP32Keystore.swift index 67a95e3ef..89205dde0 100755 --- a/Sources/Web3Core/KeystoreManager/BIP32Keystore.swift +++ b/Sources/Web3Core/KeystoreManager/BIP32Keystore.swift @@ -74,10 +74,10 @@ public class BIP32Keystore: AbstractKeystore { } public init?(_ jsonData: Data) { - guard var keystorePars = try? JSONDecoder().decode(KeystoreParamsBIP32.self, from: jsonData) else {return nil} - if keystorePars.version != Self.KeystoreParamsBIP32Version {return nil} - if keystorePars.crypto.version != nil && keystorePars.crypto.version != "1" {return nil} - if !keystorePars.isHDWallet {return nil} + guard var keystorePars = try? JSONDecoder().decode(KeystoreParamsBIP32.self, from: jsonData) else { return nil } + if keystorePars.version != Self.KeystoreParamsBIP32Version { return nil } + if keystorePars.crypto.version != nil && keystorePars.crypto.version != "1" { return nil } + if !keystorePars.isHDWallet { return nil } addressStorage = PathAddressStorage(pathAddressPairs: keystorePars.pathAddressPairs) @@ -100,7 +100,7 @@ public class BIP32Keystore: AbstractKeystore { public init? (seed: Data, password: String, prefixPath: String = HDNode.defaultPathMetamaskPrefix, aesMode: String = "aes-128-cbc") throws { addressStorage = PathAddressStorage() - guard let rootNode = HDNode(seed: seed)?.derive(path: prefixPath, derivePrivateKey: true) else {return nil} + guard let rootNode = HDNode(seed: seed)?.derive(path: prefixPath, derivePrivateKey: true) else { return nil } self.rootPrefix = prefixPath try createNewAccount(parentNode: rootNode, password: password) guard let serializedRootNode = rootNode.serialize(serializePublic: false) else { diff --git a/Sources/Web3Core/KeystoreManager/BIP39.swift b/Sources/Web3Core/KeystoreManager/BIP39.swift index a7966cdd3..32ba25294 100755 --- a/Sources/Web3Core/KeystoreManager/BIP39.swift +++ b/Sources/Web3Core/KeystoreManager/BIP39.swift @@ -71,7 +71,7 @@ public enum BIP39Language { public class BIP39 { static public func generateMnemonicsFromEntropy(entropy: Data, language: BIP39Language = BIP39Language.english) -> String? { - guard entropy.count >= 16, entropy.count & 4 == 0 else {return nil} + guard entropy.count >= 16, entropy.count & 4 == 0 else { return nil } let checksum = entropy.sha256() let checksumBits = entropy.count*8/32 var fullEntropy = Data() @@ -79,9 +79,9 @@ public class BIP39 { fullEntropy.append(checksum[0 ..< (checksumBits+7)/8 ]) var wordList = [String]() for i in 0 ..< fullEntropy.count*8/11 { - guard let bits = fullEntropy.bitsInRange(i*11, 11) else {return nil} + guard let bits = fullEntropy.bitsInRange(i*11, 11) else { return nil } let index = Int(bits) - guard language.words.count > index else {return nil} + guard language.words.count > index else { return nil } let word = language.words[index] wordList.append(word) } @@ -95,7 +95,7 @@ public class BIP39 { /// - language: words language, default english /// - Returns: random 12-24 words, that represent new Mnemonic phrase. static public func generateMnemonics(bitsOfEntropy: Int, language: BIP39Language = BIP39Language.english) throws -> String? { - guard bitsOfEntropy >= 128 && bitsOfEntropy <= 256 && bitsOfEntropy.isMultiple(of: 32) else {return nil} + guard bitsOfEntropy >= 128 && bitsOfEntropy <= 256 && bitsOfEntropy.isMultiple(of: 32) else { return nil } guard let entropy = Data.randomBytes(length: bitsOfEntropy/8) else {throw AbstractKeystoreError.noEntropyError} return BIP39.generateMnemonicsFromEntropy(entropy: entropy, language: language) @@ -104,7 +104,7 @@ public class BIP39 { static public func mnemonicsToEntropy(_ mnemonics: String, language: BIP39Language = BIP39Language.english) -> Data? { let wordList = mnemonics.components(separatedBy: " ") - guard wordList.count >= 12 && wordList.count.isMultiple(of: 3) && wordList.count <= 24 else {return nil} + guard wordList.count >= 12 && wordList.count.isMultiple(of: 3) && wordList.count <= 24 else { return nil } var bitString = "" for word in wordList { let idx = language.words.firstIndex(of: word) @@ -136,10 +136,10 @@ public class BIP39 { if !valid { return nil } - guard let mnemData = mnemonics.decomposedStringWithCompatibilityMapping.data(using: .utf8) else {return nil} + guard let mnemData = mnemonics.decomposedStringWithCompatibilityMapping.data(using: .utf8) else { return nil } let salt = "mnemonic" + password - guard let saltData = salt.decomposedStringWithCompatibilityMapping.data(using: .utf8) else {return nil} - guard let seedArray = try? PKCS5.PBKDF2(password: mnemData.bytes, salt: saltData.bytes, iterations: 2048, keyLength: 64, variant: HMAC.Variant.sha2(.sha512)).calculate() else {return nil} + guard let saltData = salt.decomposedStringWithCompatibilityMapping.data(using: .utf8) else { return nil } + guard let seedArray = try? PKCS5.PBKDF2(password: mnemData.bytes, salt: saltData.bytes, iterations: 2048, keyLength: 64, variant: HMAC.Variant.sha2(.sha512)).calculate() else { return nil } let seed = Data(seedArray) return seed } diff --git a/Sources/Web3Core/KeystoreManager/BIP44.swift b/Sources/Web3Core/KeystoreManager/BIP44.swift index 9a80a396c..d093115fc 100644 --- a/Sources/Web3Core/KeystoreManager/BIP44.swift +++ b/Sources/Web3Core/KeystoreManager/BIP44.swift @@ -6,19 +6,18 @@ import Foundation public protocol BIP44 { - /** - Derive an ``HDNode`` based on the provided path. The function will throw ``BIP44Error.warning`` if it was invoked with `throwOnWarning` equal to - `true` and the root key doesn't have a previous child with at least one transaction. If it is invoked with `throwOnWarning` equal to `false` the child node will be - derived directly using the derive function of ``HDNode``. This function needs to query the blockchain history when `throwOnWarning` is `true`, so it can throw - network errors. - - Parameter path: valid BIP44 path. - - Parameter throwOnWarning: `true` to use - [Account Discovery](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery) standard, - otherwise it will dervive the key using the derive function of ``HDNode``. - - Throws: ``BIP44Error.warning`` if the child key shouldn't be used according to - [Account Discovery](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery) standard. - - Returns: an ``HDNode`` child key for the provided `path` if it can be created, otherwise `nil` - */ + /// Derive an ``HDNode`` based on the provided path. The function will throw ``BIP44Error.warning`` + /// if it was invoked with `throwOnWarning` equal to `true` and the root key doesn't have a previous child + /// with at least one transaction. If it is invoked with `throwOnWarning` equal to `false` the child node will + /// be derived directly using the derive function of ``HDNode``. This function needs to query the blockchain + /// history when `throwOnWarning` is `true`, so it can throw network errors. + /// - Parameter path: valid BIP44 path. + /// - Parameter throwOnWarning: `true` to use + /// [Account Discovery](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery) standard, + /// otherwise it will dervive the key using the derive function of ``HDNode``. + /// - Throws: ``BIP44Error.warning`` if the child key shouldn't be used according to + /// [Account Discovery](https://github.com/bitcoin/bips/blob/master/bip-0044.mediawiki#account-discovery) standard. + /// - Returns: an ``HDNode`` child key for the provided `path` if it can be created, otherwise `nil` func derive(path: String, throwOnWarning: Bool, transactionChecker: TransactionChecker) async throws -> HDNode? } @@ -35,12 +34,10 @@ public enum BIP44Error: LocalizedError, Equatable { } public protocol TransactionChecker { - /** - It verifies if the provided address has at least one transaction - - Parameter address: to be queried - - Throws: any error related to query the blockchain provider - - Returns: `true` if the address has at least one transaction, `false` otherwise - */ + /// It verifies if the provided address has at least one transaction + /// - Parameter ethereumAddress: to be queried + /// - Throws: any error related to query the blockchain provider + /// - Returns: `true` if the address has at least one transaction, `false` otherwise func hasTransactions(ethereumAddress: EthereumAddress) async throws -> Bool } @@ -104,12 +101,11 @@ extension String { return account } - /** - Transforms a bip44 path into a new one changing account & index. The resulting one will have the change value equal to `0` to represent the external chain. The format will be `m/44'/coin_type'/account'/change/address_index` - - Parameter account: the new account to use - - Parameter addressIndex: the new addressIndex to use - - Returns: a valid bip44 path with the provided account, addressIndex and external change or `nil` otherwise - */ + /// Transforms a bip44 path into a new one changing account & index. The resulting one will have the change value equal to `0` to + /// represent the external chain. The format will be `m/44'/coin_type'/account'/change/address_index` + /// - Parameter account: the new account to use + /// - Parameter addressIndex: the new addressIndex to use + /// - Returns: a valid bip44 path with the provided account, addressIndex and external change or `nil` otherwise func newPath(account: Int, addressIndex: Int) -> String? { guard isBip44Path else { return nil diff --git a/Sources/Web3Core/KeystoreManager/EthereumKeystoreV3.swift b/Sources/Web3Core/KeystoreManager/EthereumKeystoreV3.swift index 9f68dc2c8..d2602637c 100755 --- a/Sources/Web3Core/KeystoreManager/EthereumKeystoreV3.swift +++ b/Sources/Web3Core/KeystoreManager/EthereumKeystoreV3.swift @@ -6,6 +6,7 @@ import Foundation import CryptoSwift +// swiftlint:disable cyclomatic_complexity public class EthereumKeystoreV3: AbstractKeystore { // Protocol public var isHDKeystore: Bool = false diff --git a/Sources/Web3Core/KeystoreManager/IBAN.swift b/Sources/Web3Core/KeystoreManager/IBAN.swift index 164ff319f..84a46b1c2 100755 --- a/Sources/Web3Core/KeystoreManager/IBAN.swift +++ b/Sources/Web3Core/KeystoreManager/IBAN.swift @@ -111,15 +111,15 @@ public struct IBAN { public init?(_ ibanString: String) { let matched = ibanString.replacingOccurrences(of: " ", with: "").uppercased() - guard IBAN.isValidIBANaddress(matched) else {return nil} + guard IBAN.isValidIBANaddress(matched) else { return nil } self.iban = matched } public init?(_ address: EthereumAddress) { let addressString = address.address.lowercased().stripHexPrefix() - guard let bigNumber = BigUInt(addressString, radix: 16) else {return nil} + guard let bigNumber = BigUInt(addressString, radix: 16) else { return nil } let base36EncodedString = String(bigNumber, radix: 36) - guard base36EncodedString.count <= 30 else {return nil} + guard base36EncodedString.count <= 30 else { return nil } let padded = base36EncodedString.leftPadding(toLength: 30, withPad: "0") let prefix = "XE" let remainder = IBAN.calculateChecksumMod97(IBAN.decodeToInts(prefix + "00" + padded)) diff --git a/Sources/Web3Core/KeystoreManager/PlainKeystore.swift b/Sources/Web3Core/KeystoreManager/PlainKeystore.swift index 5150149a2..1e43ff3af 100755 --- a/Sources/Web3Core/KeystoreManager/PlainKeystore.swift +++ b/Sources/Web3Core/KeystoreManager/PlainKeystore.swift @@ -19,14 +19,14 @@ public class PlainKeystore: AbstractKeystore { } public convenience init?(privateKey: String) { - guard let privateKeyData = Data.fromHex(privateKey) else {return nil} + guard let privateKeyData = Data.fromHex(privateKey) else { return nil } self.init(privateKey: privateKeyData) } public init?(privateKey: Data) { - guard SECP256K1.verifyPrivateKey(privateKey: privateKey) else {return nil} - guard let publicKey = Utilities.privateToPublic(privateKey, compressed: false) else {return nil} - guard let address = Utilities.publicToAddress(publicKey) else {return nil} + guard SECP256K1.verifyPrivateKey(privateKey: privateKey) else { return nil } + guard let publicKey = Utilities.privateToPublic(privateKey, compressed: false) else { return nil } + guard let address = Utilities.publicToAddress(publicKey) else { return nil } self.addresses = [address] self.privateKey = privateKey } diff --git a/Sources/Web3Core/RLP/RLP.swift b/Sources/Web3Core/RLP/RLP.swift index af5d8b29e..b565bb3fa 100755 --- a/Sources/Web3Core/RLP/RLP.swift +++ b/Sources/Web3Core/RLP/RLP.swift @@ -33,12 +33,12 @@ public struct RLP { if let hexData = Data.fromHex(string) { return encode(hexData) } - guard let data = string.data(using: .utf8) else {return nil} + guard let data = string.data(using: .utf8) else { return nil } return encode(data) } internal static func encode(_ number: Int) -> Data? { - guard number >= 0 else {return nil} + guard number >= 0 else { return nil } let uint = UInt(number) return encode(uint) } @@ -57,7 +57,7 @@ public struct RLP { if data.count == 1 && data.bytes[0] < UInt8(0x80) { return data } else { - guard let length = encodeLength(data.count, offset: UInt8(0x80)) else {return nil} + guard let length = encodeLength(data.count, offset: UInt8(0x80)) else { return nil } var encoded = Data() encoded.append(length) encoded.append(data) @@ -76,12 +76,12 @@ public struct RLP { internal static func encodeLength(_ length: BigUInt, offset: UInt8) -> Data? { if length < length56 { let encodedLength = length + BigUInt(UInt(offset)) - guard encodedLength.bitWidth <= 8 else {return nil} + guard encodedLength.bitWidth <= 8 else { return nil } return encodedLength.serialize() } else if length < lengthMax { let encodedLength = length.serialize() let len = BigUInt(UInt(encodedLength.count)) - guard let prefix = lengthToBinary(len) else {return nil} + guard let prefix = lengthToBinary(len) else { return nil } let lengthPrefix = prefix + offset + UInt8(55) var encoded = Data([lengthPrefix]) encoded.append(encodedLength) @@ -96,7 +96,7 @@ public struct RLP { } let divisor = BigUInt(256) var encoded = Data() - guard let prefix = lengthToBinary(length/divisor) else {return nil} + guard let prefix = lengthToBinary(length/divisor) else { return nil } let suffix = length % divisor var prefixData = Data([prefix]) @@ -107,7 +107,7 @@ public struct RLP { encoded.append(prefixData) encoded.append(suffixData) - guard encoded.count == 1 else {return nil} + guard encoded.count == 1 else { return nil } return encoded.bytes[0] } @@ -117,12 +117,12 @@ public struct RLP { if let encoded = encode(element: e) { encodedData.append(encoded) } else { - guard let asArray = e as? [Any] else {return nil} - guard let encoded = encode(asArray) else {return nil} + guard let asArray = e as? [Any] else { return nil } + guard let encoded = encode(asArray) else { return nil } encodedData.append(encoded) } } - guard var encodedLength = encodeLength(encodedData.count, offset: UInt8(0xc0)) else {return nil} + guard var encodedLength = encodeLength(encodedData.count, offset: UInt8(0xc0)) else { return nil } if encodedLength != Data() { encodedLength.append(encodedData) } @@ -130,7 +130,7 @@ public struct RLP { } internal static func decode(_ raw: String) -> RLPItem? { - guard let rawData = Data.fromHex(raw) else {return nil} + guard let rawData = Data.fromHex(raw) else { return nil } return decode(rawData) } @@ -142,18 +142,18 @@ public struct RLP { var bytesToParse = Data(raw) while bytesToParse.count != 0 { let (of, dl, t) = decodeLength(bytesToParse) - guard let offset = of, let dataLength = dl, let type = t else {return nil} + guard let offset = of, let dataLength = dl, let type = t else { return nil } switch type { case .empty: break case .data: - guard let slice = try? slice(data: bytesToParse, offset: offset, length: dataLength) else {return nil} + guard let slice = try? slice(data: bytesToParse, offset: offset, length: dataLength) else { return nil } let data = Data(slice) let rlpItem = RLPItem.init(content: .data(data)) outputArray.append(rlpItem) case .list: - guard let slice = try? slice(data: bytesToParse, offset: offset, length: dataLength) else {return nil} - guard let inside = decode(Data(slice)) else {return nil} + guard let slice = try? slice(data: bytesToParse, offset: offset, length: dataLength) else { return nil } + guard let inside = decode(Data(slice)) else { return nil } switch inside.content { case .data: return nil @@ -161,7 +161,7 @@ public struct RLP { outputArray.append(inside) } } - guard let tail = try? slice(data: bytesToParse, start: offset + dataLength) else {return nil} + guard let tail = try? slice(data: bytesToParse, start: offset + dataLength) else { return nil } bytesToParse = tail } return RLPItem.init(content: .list(outputArray, 0, Data(raw))) @@ -217,7 +217,7 @@ public struct RLP { public subscript(index: Int) -> RLPItem? { get { - guard case .list(let list, _, _) = self.content else {return nil} + guard case .list(let list, _, _) = self.content else { return nil } let item = list[index] return item } @@ -229,10 +229,10 @@ public struct RLP { public func getData() -> Data? { if self.isList { - guard case .list(_, _, let rawContent) = self.content else {return nil} + guard case .list(_, _, let rawContent) = self.content else { return nil } return rawContent } - guard case .data(let data) = self.content else {return nil} + guard case .data(let data) = self.content else { return nil } return data } diff --git a/Sources/Web3Core/Structure/Block/BlockNumber.swift b/Sources/Web3Core/Structure/Block/BlockNumber.swift index 983dd37bc..524f371e3 100644 --- a/Sources/Web3Core/Structure/Block/BlockNumber.swift +++ b/Sources/Web3Core/Structure/Block/BlockNumber.swift @@ -1,6 +1,6 @@ // // BlockNumber.swift -// +// // // Created by Yaroslav Yashin on 11.07.2022. // diff --git a/Sources/Web3Core/Structure/SECP256k1.swift b/Sources/Web3Core/Structure/SECP256k1.swift index eb4552616..f67e69d77 100755 --- a/Sources/Web3Core/Structure/SECP256k1.swift +++ b/Sources/Web3Core/Structure/SECP256k1.swift @@ -1,7 +1,4 @@ // -// secp256k1.swift -// secp256k1_swift -// // Created by Alexander Vlasov on 30.05.2018. // Copyright © 2018 Alexander Vlasov. All rights reserved. // @@ -27,7 +24,7 @@ extension SECP256K1 { static let context = secp256k1_context_create(UInt32(SECP256K1_CONTEXT_SIGN|SECP256K1_CONTEXT_VERIFY)) public static func signForRecovery(hash: Data, privateKey: Data, useExtraEntropy: Bool = false) -> (serializedSignature: Data?, rawSignature: Data?) { - if hash.count != 32 || privateKey.count != 32 {return (nil, nil)} + if hash.count != 32 || privateKey.count != 32 { return (nil, nil) } if !SECP256K1.verifyPrivateKey(privateKey: privateKey) { return (nil, nil) } @@ -48,15 +45,15 @@ extension SECP256K1 { } public static func privateToPublic(privateKey: Data, compressed: Bool = false) -> Data? { - if privateKey.count != 32 {return nil} - guard var publicKey = SECP256K1.privateKeyToPublicKey(privateKey: privateKey) else {return nil} - guard let serializedKey = serializePublicKey(publicKey: &publicKey, compressed: compressed) else {return nil} + if privateKey.count != 32 { return nil } + guard var publicKey = SECP256K1.privateKeyToPublicKey(privateKey: privateKey) else { return nil } + guard let serializedKey = serializePublicKey(publicKey: &publicKey, compressed: compressed) else { return nil } return serializedKey } public static func combineSerializedPublicKeys(keys: [Data], outputCompressed: Bool = false) -> Data? { let numToCombine = keys.count - guard numToCombine >= 1 else { return nil} + guard let context = context, numToCombine >= 1 else { return nil } var storage = ContiguousArray() let arrayOfPointers = UnsafeMutablePointer< UnsafePointer? >.allocate(capacity: numToCombine) defer { @@ -65,7 +62,7 @@ extension SECP256K1 { } for i in 0 ..< numToCombine { let key = keys[i] - guard let pubkey = SECP256K1.parsePublicKey(serializedKey: key) else {return nil} + guard let pubkey = SECP256K1.parsePublicKey(serializedKey: key) else { return nil } storage.append(pubkey) } for i in 0 ..< numToCombine { @@ -76,7 +73,7 @@ extension SECP256K1 { let immutablePointer = UnsafePointer(arrayOfPointers) var publicKey: secp256k1_pubkey = secp256k1_pubkey() let result = withUnsafeMutablePointer(to: &publicKey) { (pubKeyPtr: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ec_pubkey_combine(context!, pubKeyPtr, immutablePointer, numToCombine) + let res = secp256k1_ec_pubkey_combine(context, pubKeyPtr, immutablePointer, numToCombine) return res } if result == 0 { @@ -87,22 +84,21 @@ extension SECP256K1 { } internal static func recoverPublicKey(hash: Data, recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> secp256k1_pubkey? { - guard hash.count == 32 else {return nil} + guard let context = context, hash.count == 32 else { return nil } var publicKey: secp256k1_pubkey = secp256k1_pubkey() - let result = hash.withUnsafeBytes({ (hashRawBufferPointer: UnsafeRawBufferPointer) -> Int32? in + let result = hash.withUnsafeBytes { (hashRawBufferPointer: UnsafeRawBufferPointer) -> Int32? in if let hashRawPointer = hashRawBufferPointer.baseAddress, hashRawBufferPointer.count > 0 { let hashPointer = hashRawPointer.assumingMemoryBound(to: UInt8.self) - return withUnsafePointer(to: &recoverableSignature, { (signaturePointer: UnsafePointer) -> Int32 in - withUnsafeMutablePointer(to: &publicKey, { (pubKeyPtr: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ecdsa_recover(context!, pubKeyPtr, - signaturePointer, hashPointer) + return withUnsafePointer(to: &recoverableSignature) { (signaturePointer: UnsafePointer) -> Int32 in + withUnsafeMutablePointer(to: &publicKey) { (pubKeyPtr: UnsafeMutablePointer) -> Int32 in + let res = secp256k1_ecdsa_recover(context, pubKeyPtr, signaturePointer, hashPointer) return res - }) - }) + } + } } else { return nil } - }) + } guard let res = result, res != 0 else { return nil } @@ -110,12 +106,13 @@ extension SECP256K1 { } internal static func privateKeyToPublicKey(privateKey: Data) -> secp256k1_pubkey? { - if privateKey.count != 32 {return nil} + guard let context = context else { return nil } + if privateKey.count != 32 { return nil } var publicKey = secp256k1_pubkey() let result = privateKey.withUnsafeBytes { (pkRawBufferPointer: UnsafeRawBufferPointer) -> Int32? in if let pkRawPointer = pkRawBufferPointer.baseAddress, pkRawBufferPointer.count > 0 { let privateKeyPointer = pkRawPointer.assumingMemoryBound(to: UInt8.self) - let res = secp256k1_ec_pubkey_create(context!, &publicKey, privateKeyPointer) + let res = secp256k1_ec_pubkey_create(context, &publicKey, privateKeyPointer) return res } else { return nil @@ -128,21 +125,24 @@ extension SECP256K1 { } public static func serializePublicKey(publicKey: inout secp256k1_pubkey, compressed: Bool = false) -> Data? { + guard let context = context else { return nil } var keyLength = compressed ? 33 : 65 var serializedPubkey = Data(repeating: 0x00, count: keyLength) let result = serializedPubkey.withUnsafeMutableBytes { serializedPubkeyRawBuffPointer -> Int32? in if let serializedPkRawPointer = serializedPubkeyRawBuffPointer.baseAddress, serializedPubkeyRawBuffPointer.count > 0 { let serializedPubkeyPointer = serializedPkRawPointer.assumingMemoryBound(to: UInt8.self) - return withUnsafeMutablePointer(to: &keyLength, { (keyPtr: UnsafeMutablePointer) -> Int32 in - withUnsafeMutablePointer(to: &publicKey, { (pubKeyPtr: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ec_pubkey_serialize(context!, - serializedPubkeyPointer, - keyPtr, - pubKeyPtr, - UInt32(compressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED)) + return withUnsafeMutablePointer(to: &keyLength) { (keyPtr: UnsafeMutablePointer) -> Int32 in + withUnsafeMutablePointer(to: &publicKey) { (pubKeyPtr: UnsafeMutablePointer) -> Int32 in + let res = secp256k1_ec_pubkey_serialize( + context, + serializedPubkeyPointer, + keyPtr, + pubKeyPtr, + UInt32(compressed ? SECP256K1_EC_COMPRESSED : SECP256K1_EC_UNCOMPRESSED) + ) return res - }) - }) + } + } } else { return nil } @@ -154,7 +154,10 @@ extension SECP256K1 { } internal static func parsePublicKey(serializedKey: Data) -> secp256k1_pubkey? { - guard serializedKey.count == 33 || serializedKey.count == 65 else { + guard + let context = context, + (serializedKey.count == 33 || serializedKey.count == 65) + else { return nil } let keyLen: Int = Int(serializedKey.count) @@ -162,7 +165,7 @@ extension SECP256K1 { let result = serializedKey.withUnsafeBytes { (serializedKeyRawBufferPointer: UnsafeRawBufferPointer) -> Int32? in if let serializedKeyRawPointer = serializedKeyRawBufferPointer.baseAddress, serializedKeyRawBufferPointer.count > 0 { let serializedKeyPointer = serializedKeyRawPointer.assumingMemoryBound(to: UInt8.self) - let res = secp256k1_ec_pubkey_parse(context!, &publicKey, serializedKeyPointer, keyLen) + let res = secp256k1_ec_pubkey_parse(context, &publicKey, serializedKeyPointer, keyLen) return res } else { return nil @@ -175,7 +178,7 @@ extension SECP256K1 { } public static func parseSignature(signature: Data) -> secp256k1_ecdsa_recoverable_signature? { - guard signature.count == 65 else {return nil} + guard let context = context, signature.count == 65 else { return nil } var recoverableSignature: secp256k1_ecdsa_recoverable_signature = secp256k1_ecdsa_recoverable_signature() let serializedSignature = Data(signature[0..<64]) var v = Int32(signature[64]) @@ -189,10 +192,10 @@ extension SECP256K1 { let result = serializedSignature.withUnsafeBytes { (serRawBufferPtr: UnsafeRawBufferPointer) -> Int32? in if let serRawPtr = serRawBufferPtr.baseAddress, serRawBufferPtr.count > 0 { let serPtr = serRawPtr.assumingMemoryBound(to: UInt8.self) - return withUnsafeMutablePointer(to: &recoverableSignature, { (signaturePointer: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ecdsa_recoverable_signature_parse_compact(context!, signaturePointer, serPtr, v) + return withUnsafeMutablePointer(to: &recoverableSignature) { (signaturePointer: UnsafeMutablePointer) -> Int32 in + let res = secp256k1_ecdsa_recoverable_signature_parse_compact(context, signaturePointer, serPtr, v) return res - }) + } } else { return nil } @@ -204,16 +207,17 @@ extension SECP256K1 { } internal static func serializeSignature(recoverableSignature: inout secp256k1_ecdsa_recoverable_signature) -> Data? { + guard let context = context else { return nil } var serializedSignature = Data(repeating: 0x00, count: 64) var v: Int32 = 0 let result = serializedSignature.withUnsafeMutableBytes { (serSignatureRawBufferPointer: UnsafeMutableRawBufferPointer) -> Int32? in if let serSignatureRawPointer = serSignatureRawBufferPointer.baseAddress, serSignatureRawBufferPointer.count > 0 { let serSignaturePointer = serSignatureRawPointer.assumingMemoryBound(to: UInt8.self) return withUnsafePointer(to: &recoverableSignature) { (signaturePointer: UnsafePointer) -> Int32 in - withUnsafeMutablePointer(to: &v, { (vPtr: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ecdsa_recoverable_signature_serialize_compact(context!, serSignaturePointer, vPtr, signaturePointer) + withUnsafeMutablePointer(to: &v) { (vPtr: UnsafeMutablePointer) -> Int32 in + let res = secp256k1_ecdsa_recoverable_signature_serialize_compact(context, serSignaturePointer, vPtr, signaturePointer) return res - }) + } } } else { return nil @@ -236,32 +240,32 @@ extension SECP256K1 { if hash.count != 32 || privateKey.count != 32 { return nil } - if !SECP256K1.verifyPrivateKey(privateKey: privateKey) { + guard let context = context, SECP256K1.verifyPrivateKey(privateKey: privateKey) else { return nil } var recoverableSignature: secp256k1_ecdsa_recoverable_signature = secp256k1_ecdsa_recoverable_signature() - guard let extraEntropy = SECP256K1.randomBytes(length: 32) else {return nil} + guard let extraEntropy = SECP256K1.randomBytes(length: 32) else { return nil } let result = hash.withUnsafeBytes { hashRBPointer -> Int32? in if let hashRPointer = hashRBPointer.baseAddress, hashRBPointer.count > 0 { let hashPointer = hashRPointer.assumingMemoryBound(to: UInt8.self) - return privateKey.withUnsafeBytes({ privateKeyRBPointer -> Int32? in + return privateKey.withUnsafeBytes { privateKeyRBPointer -> Int32? in if let privateKeyRPointer = privateKeyRBPointer.baseAddress, privateKeyRBPointer.count > 0 { let privateKeyPointer = privateKeyRPointer.assumingMemoryBound(to: UInt8.self) - return extraEntropy.withUnsafeBytes({ extraEntropyRBPointer -> Int32? in + return extraEntropy.withUnsafeBytes { extraEntropyRBPointer -> Int32? in if let extraEntropyRPointer = extraEntropyRBPointer.baseAddress, extraEntropyRBPointer.count > 0 { let extraEntropyPointer = extraEntropyRPointer.assumingMemoryBound(to: UInt8.self) - return withUnsafeMutablePointer(to: &recoverableSignature, { (recSignaturePtr: UnsafeMutablePointer) -> Int32 in - let res = secp256k1_ecdsa_sign_recoverable(context!, recSignaturePtr, hashPointer, privateKeyPointer, nil, useExtraEntropy ? extraEntropyPointer : nil) + return withUnsafeMutablePointer(to: &recoverableSignature) { (recSignaturePtr: UnsafeMutablePointer) -> Int32 in + let res = secp256k1_ecdsa_sign_recoverable(context, recSignaturePtr, hashPointer, privateKeyPointer, nil, useExtraEntropy ? extraEntropyPointer : nil) return res - }) + } } else { return nil } - }) + } } else { return nil } - }) + } } else { return nil } @@ -273,19 +277,19 @@ extension SECP256K1 { } public static func recoverPublicKey(hash: Data, signature: Data, compressed: Bool = false) -> Data? { - guard hash.count == 32, signature.count == 65 else {return nil} - guard var recoverableSignature = parseSignature(signature: signature) else {return nil} - guard var publicKey = SECP256K1.recoverPublicKey(hash: hash, recoverableSignature: &recoverableSignature) else {return nil} - guard let serializedKey = SECP256K1.serializePublicKey(publicKey: &publicKey, compressed: compressed) else {return nil} + guard hash.count == 32, signature.count == 65 else { return nil } + guard var recoverableSignature = parseSignature(signature: signature) else { return nil } + guard var publicKey = SECP256K1.recoverPublicKey(hash: hash, recoverableSignature: &recoverableSignature) else { return nil } + guard let serializedKey = SECP256K1.serializePublicKey(publicKey: &publicKey, compressed: compressed) else { return nil } return serializedKey } public static func verifyPrivateKey(privateKey: Data) -> Bool { - if privateKey.count != 32 {return false} + guard let context = context, privateKey.count == 32 else { return false } let result = privateKey.withUnsafeBytes { privateKeyRBPointer -> Int32? in if let privateKeyRPointer = privateKeyRBPointer.baseAddress, privateKeyRBPointer.count > 0 { let privateKeyPointer = privateKeyRPointer.assumingMemoryBound(to: UInt8.self) - let res = secp256k1_ec_seckey_verify(context!, privateKeyPointer) + let res = secp256k1_ec_seckey_verify(context, privateKeyPointer) return res } else { return nil @@ -311,7 +315,7 @@ extension SECP256K1 { } public static func unmarshalSignature(signatureData: Data) -> UnmarshaledSignature? { - if signatureData.count != 65 {return nil} + if signatureData.count != 65 { return nil } let v = signatureData[64] let r = Data(signatureData[0..<32]) let s = Data(signatureData[32..<64]) @@ -319,7 +323,7 @@ extension SECP256K1 { } public static func marshalSignature(v: UInt8, r: [UInt8], s: [UInt8]) -> Data? { - guard r.count == 32, s.count == 32 else {return nil} + guard r.count == 32, s.count == 32 else { return nil } var completeSignature = Data(r) completeSignature.append(Data(s)) completeSignature.append(Data([v])) @@ -327,7 +331,7 @@ extension SECP256K1 { } public static func marshalSignature(v: Data, r: Data, s: Data) -> Data? { - guard r.count == 32, s.count == 32 else {return nil} + guard r.count == 32, s.count == 32 else { return nil } var completeSignature = Data(r) completeSignature.append(s) completeSignature.append(v) @@ -361,12 +365,13 @@ extension SECP256K1 { internal static func fromByteArray(_ value: [UInt8], _: T.Type) -> T { return value.withUnsafeBytes { - $0.baseAddress!.load(as: T.self) + guard let baseAddress = $0.baseAddress else { fatalError("baseAddress of \($0) byte is nil.") } + return baseAddress.load(as: T.self) } } internal static func constantTimeComparison(_ lhs: Data, _ rhs: Data) -> Bool { - guard lhs.count == rhs.count else {return false} + guard lhs.count == rhs.count else { return false } var difference = UInt8(0x00) for i in 0..(_ value: T) -> [UInt8] { } func scrypt (password: String, salt: Data, length: Int, N: Int, R: Int, P: Int) -> Data? { - guard let passwordData = password.data(using: .utf8) else {return nil} - guard let deriver = try? Scrypt(password: passwordData.bytes, salt: salt.bytes, dkLen: length, N: N, r: R, p: P) else {return nil} - guard let result = try? deriver.calculate() else {return nil} + guard let passwordData = password.data(using: .utf8) else { return nil } + guard let deriver = try? Scrypt(password: passwordData.bytes, salt: salt.bytes, dkLen: length, N: N, r: R, p: P) else { return nil } + guard let result = try? deriver.calculate() else { return nil } return Data(result) } diff --git a/Sources/Web3Core/Utility/Data+Extension.swift b/Sources/Web3Core/Utility/Data+Extension.swift index 6949f91be..448728f1a 100755 --- a/Sources/Web3Core/Utility/Data+Extension.swift +++ b/Sources/Web3Core/Utility/Data+Extension.swift @@ -59,15 +59,15 @@ extension Data { } public func bitsInRange(_ startingBit: Int, _ length: Int) -> UInt64? { // return max of 8 bytes for simplicity, non-public - if startingBit + length / 8 > self.count, length > 64, startingBit > 0, length >= 1 {return nil} + if startingBit + length / 8 > self.count, length > 64, startingBit > 0, length >= 1 { return nil } let bytes = self[(startingBit/8) ..< (startingBit+length+7)/8] let padding = Data(repeating: 0, count: 8 - bytes.count) let padded = bytes + padding - guard padded.count == 8 else {return nil} + guard padded.count == 8 else { return nil } let pointee = padded.withUnsafeBytes { (body: UnsafeRawBufferPointer) in body.baseAddress?.assumingMemoryBound(to: UInt64.self).pointee } - guard let ptee = pointee else {return nil} + guard let ptee = pointee else { return nil } var uintRepresentation = UInt64(bigEndian: ptee) uintRepresentation = uintRepresentation << (startingBit % 8) uintRepresentation = uintRepresentation >> UInt64(64 - length) diff --git a/Sources/Web3Core/Utility/Utilities.swift b/Sources/Web3Core/Utility/Utilities.swift index 3d347e79a..e2ba762be 100644 --- a/Sources/Web3Core/Utility/Utilities.swift +++ b/Sources/Web3Core/Utility/Utilities.swift @@ -18,8 +18,10 @@ public struct Utilities { static func publicToAddressData(_ publicKey: Data) -> Data? { var publicKey = publicKey if publicKey.count == 33 { - guard (publicKey[0] == 2 || publicKey[0] == 3), - let decompressedKey = SECP256K1.combineSerializedPublicKeys(keys: [publicKey], outputCompressed: false) else { + guard + (publicKey[0] == 2 || publicKey[0] == 3), + let decompressedKey = SECP256K1.combineSerializedPublicKeys(keys: [publicKey], outputCompressed: false) + else { return nil } publicKey = decompressedKey @@ -44,14 +46,14 @@ public struct Utilities { /// - Parameter publicKey: compressed 33, non-compressed (65 bytes) or non-compressed without prefix (64 bytes) /// - Returns: `EthereumAddress` object. public static func publicToAddress(_ publicKey: Data) -> EthereumAddress? { - guard let addressData = publicToAddressData(publicKey) else {return nil} + guard let addressData = publicToAddressData(publicKey) else { return nil } let address = addressData.toHexString().addHexPrefix().lowercased() return EthereumAddress(address) } /// Convert the private key (32 bytes of Data) to compressed (33 bytes) or non-compressed (65 bytes) public key. public static func privateToPublic(_ privateKey: Data, compressed: Bool = false) -> Data? { - guard let publicKey = SECP256K1.privateToPublic(privateKey: privateKey, compressed: compressed) else {return nil} + guard let publicKey = SECP256K1.privateToPublic(privateKey: privateKey, compressed: compressed) else { return nil } return publicKey } @@ -61,14 +63,14 @@ public struct Utilities { /// - Parameter publicKey: compressed 33, non-compressed (65 bytes) or non-compressed without prefix (64 bytes) /// - Returns: `0x` prefixed hex string. public static func publicToAddressString(_ publicKey: Data) -> String? { - guard let addressData = Utilities.publicToAddressData(publicKey) else {return nil} + guard let addressData = Utilities.publicToAddressData(publicKey) else { return nil } let address = addressData.toHexString().addHexPrefix().lowercased() return address } /// Converts address data (20 bytes) to the 0x prefixed hex string. Does not perform checksumming. static func addressDataToString(_ addressData: Data) -> String? { - guard addressData.count == 20 else {return nil} + guard addressData.count == 20 else { return nil } return addressData.toHexString().addHexPrefix().lowercased() } @@ -78,7 +80,7 @@ public struct Utilities { public static func hashPersonalMessage(_ personalMessage: Data) -> Data? { var prefix = "\u{19}Ethereum Signed Message:\n" prefix += String(personalMessage.count) - guard let prefixData = prefix.data(using: .ascii) else {return nil} + guard let prefixData = prefix.data(using: .ascii) else { return nil } var data = Data() if personalMessage.count >= prefixData.count && prefixData == personalMessage[0 ..< prefixData.count] { data.append(personalMessage) @@ -98,31 +100,37 @@ public struct Utilities { return parseToBigUInt(amount, decimals: unitDecimals) } - /// Parse a user-supplied string using the number of decimals. + /// Parse a string using the number of decimals. /// If input is non-numeric or precision is not sufficient - returns nil. /// Allowed decimal separators are ".", ",". public static func parseToBigUInt(_ amount: String, decimals: Int = 18) -> BigUInt? { let separators = CharacterSet(charactersIn: ".,") let components = amount.trimmingCharacters(in: .whitespacesAndNewlines).components(separatedBy: separators) - guard components.count == 1 || components.count == 2 else {return nil} + guard components.count == 1 || components.count == 2 else { return nil } let unitDecimals = decimals - guard let beforeDecPoint = BigUInt(components[0], radix: 10) else {return nil} - var mainPart = beforeDecPoint*BigUInt(10).power(unitDecimals) + guard let beforeDecPoint = BigUInt(components[0], radix: 10) else { return nil } + var mainPart = beforeDecPoint * BigUInt(10).power(unitDecimals) if components.count == 2 { let numDigits = components[1].count - guard numDigits <= unitDecimals else {return nil} - guard let afterDecPoint = BigUInt(components[1], radix: 10) else {return nil} - let extraPart = afterDecPoint*BigUInt(10).power(unitDecimals-numDigits) - mainPart = mainPart + extraPart + guard numDigits <= unitDecimals else { return nil } + guard let afterDecPoint = BigUInt(components[1], radix: 10) else { return nil } + let extraPart = afterDecPoint * BigUInt(10).power(unitDecimals-numDigits) + mainPart += extraPart } return mainPart } - /// Formats a BigInt object to String. The supplied number is first divided into integer and decimal part based on "units", - /// then limit the decimal part to "decimals" symbols and uses a "decimalSeparator" as a separator. + /// Formats a `BigInt` object to `String`. The supplied number is first divided into integer and decimal part based on `units` value, + /// then limits the decimal part to `formattingDecimals` symbols and uses a `decimalSeparator` as a separator. /// Fallbacks to scientific format if higher precision is required. /// - /// Returns nil of formatting is not possible to satisfy. + /// - Parameters: + /// - bigNumber: number to format; + /// - units: unit to format number to; + /// - formattingDecimals: the number of decimals that should be in the final formatted number; + /// - decimalSeparator: decimals separator; + /// - fallbackToScientific: if should fallback to scienctific representation like `1.23e-10`. + /// - Returns: formatted number or `nil` if formatting was not possible. public static func formatToPrecision(_ bigNumber: BigInt, units: Utilities.Units = .ether, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String { let magnitude = bigNumber.magnitude let formatted = formatToPrecision(magnitude, units: units, formattingDecimals: formattingDecimals, decimalSeparator: decimalSeparator, fallbackToScientific: fallbackToScientific) @@ -134,13 +142,19 @@ public struct Utilities { } } - /// Formats a BigUInt object to String. The supplied number is first divided into integer and decimal part based on "units", - /// then limits the decimal part to "formattingDecimals" symbols and uses a "decimalSeparator" as a separator. + /// Formats a `BigUInt` object to `String`. The supplied number is first divided into integer and decimal part based on `units` value, + /// then limits the decimal part to `formattingDecimals` symbols and uses a `decimalSeparator` as a separator. /// Fallbacks to scientific format if higher precision is required. /// - /// Returns nil of formatting is not possible to satisfy. + /// - Parameters: + /// - bigNumber: number to format; + /// - units: unit to format number to; + /// - formattingDecimals: the number of decimals that should be in the final formatted number; + /// - decimalSeparator: decimals separator; + /// - fallbackToScientific: if should fallback to scienctific representation like `1.23e-10`. + /// - Returns: formatted number or `nil` if formatting was not possible. public static func formatToPrecision(_ bigNumber: BigUInt, units: Utilities.Units = .ether, formattingDecimals: Int = 4, decimalSeparator: String = ".", fallbackToScientific: Bool = false) -> String { - if bigNumber == 0 { + guard bigNumber != 0 else { return "0" } let unitDecimals = units.decimals @@ -150,86 +164,81 @@ public struct Utilities { } let divisor = BigUInt(10).power(unitDecimals) let (quotient, remainder) = bigNumber.quotientAndRemainder(dividingBy: divisor) - var fullRemainder = "\(remainder)" - let fullPaddedRemainder = fullRemainder.leftPadding(toLength: unitDecimals, withPad: "0") + + guard toDecimals != 0 else { + return "\(quotient)" + } + + let remainderStr = "\(remainder)" + let fullPaddedRemainder = remainderStr.leftPadding(toLength: unitDecimals, withPad: "0") let remainderPadded = fullPaddedRemainder[0.. formattingDecimals { - let end = firstDigit+1+formattingDecimals > fullPaddedRemainder.count ? fullPaddedRemainder.count: firstDigit+1+formattingDecimals - remainingDigits = String(fullPaddedRemainder[firstDigit+1 ..< end]) - } else { - remainingDigits = String(fullPaddedRemainder[firstDigit+1 ..< fullPaddedRemainder.count]) - } - if remainingDigits != "" { - fullRemainder = firstDecimalUnit + decimalSeparator + remainingDigits - } else { - fullRemainder = firstDecimalUnit - } - firstDigit = firstDigit + 1 - break - } - } - return fullRemainder + "e-" + String(firstDigit) - } + + guard remainderPadded == String(repeating: "0", count: toDecimals) else { + return "\(quotient)" + decimalSeparator + remainderPadded + } + + if fallbackToScientific { + return formatToScientificRepresentation(remainderStr, remainder: fullPaddedRemainder, decimals: formattingDecimals, decimalSeparator: decimalSeparator) } - if toDecimals == 0 { + + guard quotient == 0 else { return "\(quotient)" } + return "\(quotient)" + decimalSeparator + remainderPadded } + private static func formatToScientificRepresentation(_ remainder: String, remainder fullPaddedRemainder: String, decimals: Int, decimalSeparator: String) -> String { + var remainder = remainder + var firstDigit = 0 + for char in fullPaddedRemainder { + if char == "0" { + firstDigit += 1 + } else { + let firstDecimalUnit = String(fullPaddedRemainder[firstDigit ..< firstDigit + 1]) + var remainingDigits = "" + let numOfRemainingDecimals = fullPaddedRemainder.count - firstDigit - 1 + if numOfRemainingDecimals <= 0 { + remainingDigits = "" + } else if numOfRemainingDecimals > decimals { + let end = firstDigit + 1 + decimals > fullPaddedRemainder.count ? fullPaddedRemainder.count : firstDigit + 1 + decimals + remainingDigits = String(fullPaddedRemainder[firstDigit + 1 ..< end]) + } else { + remainingDigits = String(fullPaddedRemainder[firstDigit + 1 ..< fullPaddedRemainder.count]) + } + if !remainingDigits.isEmpty { + remainder = firstDecimalUnit + decimalSeparator + remainingDigits + } else { + remainder = firstDecimalUnit + } + firstDigit += 1 + break + } + } + return remainder + "e-" + String(firstDigit) + } + /// Recover the Ethereum address from recoverable secp256k1 signature. Message is first hashed using the "personal hash" protocol. /// BE WARNED - changing a message will result in different Ethereum address, but not in error. /// /// Input parameters should be hex Strings. static func personalECRecover(_ personalMessage: String, signature: String) -> EthereumAddress? { - guard let data = Data.fromHex(personalMessage) else {return nil} - guard let sig = Data.fromHex(signature) else {return nil} + guard let data = Data.fromHex(personalMessage) else { return nil } + guard let sig = Data.fromHex(signature) else { return nil } return Utilities.personalECRecover(data, signature: sig) } /// Recover the Ethereum address from recoverable secp256k1 signature. Message is first hashed using the "personal hash" protocol. - /// BE WARNED - changing a message will result in different Ethereum address, but not in error. - /// - /// Input parameters should be Data objects. + /// BE WARNED - changing a message will result in different Ethereum address, but not in an error. public static func personalECRecover(_ personalMessage: Data, signature: Data) -> EthereumAddress? { - if signature.count != 65 { return nil} - let rData = signature[0..<32].bytes - let sData = signature[32..<64].bytes - var vData = signature[64] - if vData >= 27 && vData <= 30 { - vData -= 27 - } else if vData >= 31 && vData <= 34 { - vData -= 31 - } else if vData >= 35 && vData <= 38 { - vData -= 35 - } - - guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else {return nil} - guard let hash = Utilities.hashPersonalMessage(personalMessage) else {return nil} - guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} - return Utilities.publicToAddress(publicKey) + guard let hash = Utilities.hashPersonalMessage(personalMessage) else { return nil } + return hashECRecover(hash: hash, signature: signature) } /// Recover the Ethereum address from recoverable secp256k1 signature. /// Takes a hash of some message. What message is hashed should be checked by user separately. - /// - /// Input parameters should be Data objects. public static func hashECRecover(hash: Data, signature: Data) -> EthereumAddress? { - if signature.count != 65 { return nil} + if signature.count != 65 { return nil } let rData = signature[0..<32].bytes let sData = signature[32..<64].bytes var vData = signature[64] @@ -240,32 +249,32 @@ public struct Utilities { } else if vData >= 35 && vData <= 38 { vData -= 35 } - guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else {return nil} - guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else { return nil } + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else { return nil } return Utilities.publicToAddress(publicKey) } /// returns Ethereum variant of sha3 (keccak256) of data. Returns nil is data is empty static func keccak256(_ data: Data) -> Data? { - if data.count == 0 {return nil} + if data.count == 0 { return nil } return data.sha3(.keccak256) } /// returns Ethereum variant of sha3 (keccak256) of data. Returns nil is data is empty static func sha3(_ data: Data) -> Data? { - if data.count == 0 {return nil} + if data.count == 0 { return nil } return data.sha3(.keccak256) } /// returns sha256 of data. Returns nil is data is empty static func sha256(_ data: Data) -> Data? { - if data.count == 0 {return nil} + if data.count == 0 { return nil } return data.sha256() } /// Unmarshals a 65 byte recoverable EC signature into internal structure. static func unmarshalSignature(signatureData: Data) -> SECP256K1.UnmarshaledSignature? { - if signatureData.count != 65 {return nil} + if signatureData.count != 65 { return nil } let bytes = signatureData.bytes let r = Array(bytes[0..<32]) let s = Array(bytes[32..<64]) @@ -274,7 +283,7 @@ public struct Utilities { /// Marshals the V, R and S signature parameters into a 65 byte recoverable EC signature. static func marshalSignature(v: UInt8, r: [UInt8], s: [UInt8]) -> Data? { - guard r.count == 32, s.count == 32 else {return nil} + guard r.count == 32, s.count == 32 else { return nil } var completeSignature = Data(r) completeSignature.append(Data(s)) completeSignature.append(Data([v])) diff --git a/Sources/Web3Core/Web3Error/Web3Error.swift b/Sources/Web3Core/Web3Error/Web3Error.swift index 6a24b2456..a9e77a188 100644 --- a/Sources/Web3Core/Web3Error/Web3Error.swift +++ b/Sources/Web3Core/Web3Error/Web3Error.swift @@ -1,6 +1,6 @@ // // Web3Error.swift -// +// // // Created by Yaroslav Yashin on 11.07.2022. // diff --git a/Sources/secp256k1/ecmult_impl.h b/Sources/secp256k1/ecmult_impl.h index 61a5ffd23..fd847c8e6 100755 --- a/Sources/secp256k1/ecmult_impl.h +++ b/Sources/secp256k1/ecmult_impl.h @@ -306,7 +306,7 @@ static int secp256k1_ecmult_wnaf(int *wnaf, int len, const secp256k1_scalar *a, CHECK(carry == 0); while (bit < 256) { CHECK(secp256k1_scalar_get_bits(&s, bit++, 1) == 0); - } + } #endif return last_set_bit + 1; } diff --git a/Sources/secp256k1/include/secp256k1.h b/Sources/secp256k1/include/secp256k1.h index c1fc13fac..22a27e06f 100755 --- a/Sources/secp256k1/include/secp256k1.h +++ b/Sources/secp256k1/include/secp256k1.h @@ -646,7 +646,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( const secp256k1_pubkey * const * ins, size_t n ) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); - + /** Opaque data structured that holds a parsed ECDSA signature, * supporting pubkey recovery. * @@ -664,7 +664,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( typedef struct { unsigned char data[65]; } secp256k1_ecdsa_recoverable_signature; - + /** Parse a compact ECDSA signature (64 bytes + recovery id). * * Returns: 1 when the signature could be parsed, 0 otherwise @@ -679,7 +679,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( const unsigned char *input64, int recid ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); - + /** Convert a recoverable signature into a normal signature. * * Returns: 1 @@ -691,7 +691,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( secp256k1_ecdsa_signature* sig, const secp256k1_ecdsa_recoverable_signature* sigin ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3); - + /** Serialize an ECDSA signature in compact format (64 bytes + recovery id). * * Returns: 1 @@ -706,7 +706,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( int *recid, const secp256k1_ecdsa_recoverable_signature* sig ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); - + /** Create a recoverable ECDSA signature. * * Returns: 1: signature created @@ -726,7 +726,7 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( secp256k1_nonce_function noncefp, const void *ndata ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); - + /** Recover an ECDSA public key from a signature. * * Returns: 1: public key successfully recovered (which guarantees a correct signature). @@ -758,8 +758,8 @@ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine( const secp256k1_pubkey *pubkey, const unsigned char *privkey ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4); - - + + #ifdef __cplusplus } #endif diff --git a/Sources/web3swift/Browser/browser.js b/Sources/web3swift/Browser/browser.js index 8cffd18b1..d85214d3d 100644 --- a/Sources/web3swift/Browser/browser.js +++ b/Sources/web3swift/Browser/browser.js @@ -113,18 +113,18 @@ } }); }()); - + //# sourceURL=/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/index.js },{"./wk.bridge":424,"web3":407,"web3-provider-engine/zero.js":397}],2:[function(require,module,exports){ module.exports = require('./register')().Promise - + },{"./register":4}],3:[function(require,module,exports){ "use strict" // global key for user preferred registration var REGISTRATION_KEY = '@@any-promise/REGISTRATION', // Prior registration (preferred or detected) registered = null - + /** * Registers the given implementation. An implementation must * be registered prior to any call to `require("any-promise")`, @@ -161,12 +161,12 @@ opts = opts || {} // global registration unless explicitly {global: false} in options (default true) var registerGlobal = opts.global !== false; - + // load any previous global registration if(registered === null && registerGlobal){ registered = root[REGISTRATION_KEY] || null } - + if(registered !== null && implementation !== null && registered.implementation !== implementation){ @@ -175,7 +175,7 @@ '". You can only register an implementation before the first '+ ' call to require("any-promise") and an implementation cannot be changed') } - + if(registered === null){ // use provided implementation if(implementation !== null && typeof opts.Promise !== 'undefined'){ @@ -187,21 +187,21 @@ // require implementation if implementation is specified but not provided registered = loadImplementation(implementation) } - + if(registerGlobal){ // register preference globally in case multiple installations root[REGISTRATION_KEY] = registered } } - + return registered } } - + },{}],4:[function(require,module,exports){ "use strict"; module.exports = require('./loader')(window, loadImplementation) - + /** * Browser specific loadImplementation. Always uses `window.Promise` * @@ -217,36 +217,36 @@ implementation: 'window.Promise' } } - + },{"./loader":3}],5:[function(require,module,exports){ var asn1 = exports; - + asn1.bignum = require('bn.js'); - + asn1.define = require('./asn1/api').define; asn1.base = require('./asn1/base'); asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); - + },{"./asn1/api":6,"./asn1/base":8,"./asn1/constants":12,"./asn1/decoders":14,"./asn1/encoders":17,"bn.js":53}],6:[function(require,module,exports){ var asn1 = require('../asn1'); var inherits = require('inherits'); - + var api = exports; - + api.define = function define(name, body) { return new Entity(name, body); }; - + function Entity(name, body) { this.name = name; this.body = body; - + this.decoders = {}; this.encoders = {}; }; - + Entity.prototype._createNamed = function createNamed(base) { var named; try { @@ -264,10 +264,10 @@ named.prototype._initNamed = function initnamed(entity) { base.call(this, entity); }; - + return new named(this); }; - + Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder @@ -275,11 +275,11 @@ this.decoders[enc] = this._createNamed(asn1.decoders[enc]); return this.decoders[enc]; }; - + Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; - + Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder @@ -287,76 +287,76 @@ this.encoders[enc] = this._createNamed(asn1.encoders[enc]); return this.encoders[enc]; }; - + Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; - + },{"../asn1":5,"inherits":180,"vm":334}],7:[function(require,module,exports){ var inherits = require('inherits'); var Reporter = require('../base').Reporter; var Buffer = require('buffer').Buffer; - + function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } - + this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.DecoderBuffer = DecoderBuffer; - + DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; - + DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data var res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; - + this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); - + return res; }; - + DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; - + DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); } - + DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); - + var res = new DecoderBuffer(this.base); - + // Share reporter state res._reporterState = this._reporterState; - + res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; } - + DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); } - + function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; @@ -382,16 +382,16 @@ } } exports.EncoderBuffer = EncoderBuffer; - + EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = new Buffer(this.length); if (!offset) offset = 0; - + if (this.length === 0) return out; - + if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); @@ -406,24 +406,24 @@ this.value.copy(out, offset); offset += this.length; } - + return out; }; - + },{"../base":8,"buffer":84,"inherits":180}],8:[function(require,module,exports){ var base = exports; - + base.Reporter = require('./reporter').Reporter; base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); - + },{"./buffer":7,"./node":9,"./reporter":10}],9:[function(require,module,exports){ var Reporter = require('../base').Reporter; var EncoderBuffer = require('../base').EncoderBuffer; var DecoderBuffer = require('../base').DecoderBuffer; var assert = require('minimalistic-assert'); - + // Supported tags var tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', @@ -431,32 +431,32 @@ 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; - + // Public methods list var methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); - + // Overrided methods list var overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - + '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; - + function Node(enc, parent) { var state = {}; this._baseState = state; - + state.enc = enc; - + state.parent = parent || null; state.children = null; - + // State state.tag = null; state.args = null; @@ -472,7 +472,7 @@ state.explicit = null; state.implicit = null; state.contains = null; - + // Should create new instance on each method if (!state.parent) { state.children = []; @@ -480,13 +480,13 @@ } } module.exports = Node; - + var stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; - + Node.prototype.clone = function clone() { var state = this._baseState; var cstate = {}; @@ -497,7 +497,7 @@ res._baseState = cstate; return res; }; - + Node.prototype._wrap = function wrap() { var state = this._baseState; methods.forEach(function(method) { @@ -508,23 +508,23 @@ }; }, this); }; - + Node.prototype._init = function init(body) { var state = this._baseState; - + assert(state.parent === null); body.call(this); - + // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; - + Node.prototype._useArgs = function useArgs(args) { var state = this._baseState; - + // Filter children and args var children = args.filter(function(arg) { return arg instanceof this.constructor; @@ -532,11 +532,11 @@ args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); - + if (children.length !== 0) { assert(state.children === null); state.children = children; - + // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; @@ -548,7 +548,7 @@ state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; - + var res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) @@ -560,150 +560,150 @@ }); } }; - + // // Overrided methods // - + overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { var state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); - + // // Public methods // - + tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); - + assert(state.tag === null); state.tag = tag; - + this._useArgs(args); - + return this; }; }); - + Node.prototype.use = function use(item) { assert(item); var state = this._baseState; - + assert(state.use === null); state.use = item; - + return this; }; - + Node.prototype.optional = function optional() { var state = this._baseState; - + state.optional = true; - + return this; }; - + Node.prototype.def = function def(val) { var state = this._baseState; - + assert(state['default'] === null); state['default'] = val; state.optional = true; - + return this; }; - + Node.prototype.explicit = function explicit(num) { var state = this._baseState; - + assert(state.explicit === null && state.implicit === null); state.explicit = num; - + return this; }; - + Node.prototype.implicit = function implicit(num) { var state = this._baseState; - + assert(state.explicit === null && state.implicit === null); state.implicit = num; - + return this; }; - + Node.prototype.obj = function obj() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); - + state.obj = true; - + if (args.length !== 0) this._useArgs(args); - + return this; }; - + Node.prototype.key = function key(newKey) { var state = this._baseState; - + assert(state.key === null); state.key = newKey; - + return this; }; - + Node.prototype.any = function any() { var state = this._baseState; - + state.any = true; - + return this; }; - + Node.prototype.choice = function choice(obj) { var state = this._baseState; - + assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); - + return this; }; - + Node.prototype.contains = function contains(item) { var state = this._baseState; - + assert(state.use === null); state.contains = item; - + return this; }; - + // // Decoding // - + Node.prototype._decode = function decode(input, options) { var state = this._baseState; - + // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); - + var result = state['default']; var present = true; - + var prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); - + // Check if tag is there if (state.optional) { var tag = null; @@ -713,7 +713,7 @@ tag = state.implicit; else if (state.tag !== null) tag = state.tag; - + if (tag === null && !state.any) { // Trial and Error var save = input.save(); @@ -729,17 +729,17 @@ input.restore(save); } else { present = this._peekTag(input, tag, state.any); - + if (input.isError(present)) return present; } } - + // Push object on stack var prevObj; if (state.obj && present) prevObj = input.enterObject(); - + if (present) { // Unwrap explicit values if (state.explicit !== null) { @@ -748,9 +748,9 @@ return explicit; input = explicit; } - + var start = input.offset; - + // Unwrap implicit and normal values if (state.use === null && state.choice === null) { if (state.any) @@ -762,19 +762,19 @@ ); if (input.isError(body)) return body; - + if (state.any) result = input.raw(save); else input = body; } - + if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); - + if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); - + // Select proper method for tag if (state.any) result = result; @@ -782,10 +782,10 @@ result = this._decodeGeneric(state.tag, input, options); else result = this._decodeChoice(input, options); - + if (input.isError(result)) return result; - + // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { @@ -794,7 +794,7 @@ child._decode(input, options); }); } - + // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { var data = new DecoderBuffer(result); @@ -802,23 +802,23 @@ ._decode(data, options); } } - + // Pop object if (state.obj && present) result = input.leaveObject(prevObj); - + // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); - + return result; }; - + Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { var state = this._baseState; - + if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') @@ -839,7 +839,7 @@ return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); - + if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); @@ -847,9 +847,9 @@ return input.error('unknown tag: ' + tag); } }; - + Node.prototype._getUse = function _getUse(entity, obj) { - + var state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); @@ -861,12 +861,12 @@ } return state.useDecoder; }; - + Node.prototype._decodeChoice = function decodeChoice(input, options) { var state = this._baseState; var result = null; var match = false; - + Object.keys(state.choice).some(function(key) { var save = input.save(); var node = state.choice[key]; @@ -874,7 +874,7 @@ var value = node._decode(input, options); if (input.isError(value)) return false; - + result = { type: key, value: value }; match = true; } catch (e) { @@ -883,48 +883,48 @@ } return true; }, this); - + if (!match) return input.error('Choice not matched'); - + return result; }; - + // // Encoding // - + Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; - + Node.prototype._encode = function encode(data, reporter, parent) { var state = this._baseState; if (state['default'] !== null && state['default'] === data) return; - + var result = this._encodeValue(data, reporter, parent); if (result === undefined) return; - + if (this._skipDefault(result, reporter, parent)) return; - + return result; }; - + Node.prototype._encodeValue = function encode(data, reporter, parent) { var state = this._baseState; - + // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); - + var result = null; - + // Set reporter to share it with a child class this.reporter = reporter; - + // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) @@ -932,7 +932,7 @@ else return; } - + // Encode children first var content = null; var primitive = false; @@ -948,17 +948,17 @@ content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); - + if (child._baseState.key === null) return reporter.error('Child should have a key'); var prevKey = reporter.enterKey(child._baseState.key); - + if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); - + var res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); - + return res; }, this).filter(function(child) { return child; @@ -969,15 +969,15 @@ // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); - + if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); - + var child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { var state = this._baseState; - + return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { @@ -987,13 +987,13 @@ primitive = true; } } - + // Encode data itself var result; if (!state.any && state.choice === null) { var tag = state.implicit !== null ? state.implicit : state.tag; var cls = state.implicit === null ? 'universal' : 'context'; - + if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); @@ -1002,17 +1002,17 @@ result = this._encodeComposite(tag, primitive, cls, content); } } - + // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); - + return result; }; - + Node.prototype._encodeChoice = function encodeChoice(data, reporter) { var state = this._baseState; - + var node = state.choice[data.type]; if (!node) { assert( @@ -1022,10 +1022,10 @@ } return node._encode(data.value, reporter); }; - + Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { var state = this._baseState; - + if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) @@ -1045,18 +1045,18 @@ else throw new Error('Unsupported tag: ' + tag); }; - + Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; - + Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); }; - + },{"../base":8,"minimalistic-assert":234}],10:[function(require,module,exports){ var inherits = require('inherits'); - + function Reporter(options) { this._reporterState = { obj: null, @@ -1066,66 +1066,66 @@ }; } exports.Reporter = Reporter; - + Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; - + Reporter.prototype.save = function save() { var state = this._reporterState; - + return { obj: state.obj, pathLen: state.path.length }; }; - + Reporter.prototype.restore = function restore(data) { var state = this._reporterState; - + state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; - + Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; - + Reporter.prototype.exitKey = function exitKey(index) { var state = this._reporterState; - + state.path = state.path.slice(0, index - 1); }; - + Reporter.prototype.leaveKey = function leaveKey(index, key, value) { var state = this._reporterState; - + this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; - + Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; - + Reporter.prototype.enterObject = function enterObject() { var state = this._reporterState; - + var prev = state.obj; state.obj = {}; return prev; }; - + Reporter.prototype.leaveObject = function leaveObject(prev) { var state = this._reporterState; - + var now = state.obj; state.obj = prev; return now; }; - + Reporter.prototype.error = function error(msg) { var err; var state = this._reporterState; - + var inherited = msg instanceof ReporterError; if (inherited) { err = msg; @@ -1134,38 +1134,38 @@ return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } - + if (!state.options.partial) throw err; - + if (!inherited) state.errors.push(err); - + return err; }; - + Reporter.prototype.wrapResult = function wrapResult(result) { var state = this._reporterState; if (!state.options.partial) return result; - + return { result: this.isError(result) ? null : result, errors: state.errors }; }; - + function ReporterError(path, msg) { this.path = path; this.rethrow(msg); }; inherits(ReporterError, Error); - + ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); - + if (!this.stack) { try { // IE only adds stack when thrown @@ -1176,10 +1176,10 @@ } return this; }; - + },{"inherits":180}],11:[function(require,module,exports){ var constants = require('../constants'); - + exports.tagClass = { 0: 'universal', 1: 'application', @@ -1187,7 +1187,7 @@ 3: 'private' }; exports.tagClassByName = constants._reverse(exports.tagClass); - + exports.tag = { 0x00: 'end', 0x01: 'bool', @@ -1220,102 +1220,102 @@ 0x1e: 'bmpstr' }; exports.tagByName = constants._reverse(exports.tag); - + },{"../constants":12}],12:[function(require,module,exports){ var constants = exports; - + // Helper constants._reverse = function reverse(map) { var res = {}; - + Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; - + var value = map[key]; res[value] = key; }); - + return res; }; - + constants.der = require('./der'); - + },{"./der":11}],13:[function(require,module,exports){ var inherits = require('inherits'); - + var asn1 = require('../../asn1'); var base = asn1.base; var bignum = asn1.bignum; - + // Import DER constants var der = asn1.constants.der; - + function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; - + // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DERDecoder; - + DERDecoder.prototype.decode = function decode(data, options) { if (!(data instanceof base.DecoderBuffer)) data = new base.DecoderBuffer(data, options); - + return this.tree._decode(data, options); }; - + // Tree methods - + function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); - + DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; - + var state = buffer.save(); var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; - + buffer.restore(state); - + return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any; }; - + DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; - + var len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); - + // Failure if (buffer.isError(len)) return len; - + if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } - + if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - + // Indefinite length... find END tag var state = buffer.save(); var res = this._skipUntilEnd( @@ -1323,12 +1323,12 @@ 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; - + len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; - + DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { while (true) { var tag = derDecodeTag(buffer, fail); @@ -1337,22 +1337,22 @@ var len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; - + var res; if (tag.primitive || len !== null) res = buffer.skip(len) else res = this._skipUntilEnd(buffer, fail); - + // Failure if (buffer.isError(res)) return res; - + if (tag.tagStr === 'end') break; } }; - + DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { var result = []; @@ -1360,7 +1360,7 @@ var possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; - + var res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; @@ -1368,7 +1368,7 @@ } return result; }; - + DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { var unused = buffer.readUInt8(); @@ -1379,7 +1379,7 @@ var raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); - + var str = ''; for (var i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); @@ -1409,7 +1409,7 @@ return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; - + DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { var result; var identifiers = []; @@ -1425,15 +1425,15 @@ } if (subident & 0x80) identifiers.push(ident); - + var first = (identifiers[0] / 40) | 0; var second = identifiers[0] % 40; - + if (relative) result = identifiers; else result = [first, second].concat(identifiers.slice(1)); - + if (values) { var tmp = values[result.join(' ')]; if (tmp === undefined) @@ -1441,10 +1441,10 @@ if (tmp !== undefined) result = tmp; } - + return result; }; - + DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { var str = buffer.raw().toString(); if (tag === 'gentime') { @@ -1468,14 +1468,14 @@ } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } - + return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; - + DERNode.prototype._decodeNull = function decodeNull(buffer) { return null; }; - + DERNode.prototype._decodeBool = function decodeBool(buffer) { var res = buffer.readUInt8(); if (buffer.isError(res)) @@ -1483,34 +1483,34 @@ else return res !== 0; }; - + DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) var raw = buffer.raw(); var res = new bignum(raw); - + if (values) res = values[res.toString(10)] || res; - + return res; }; - + DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; - + // Utility methods - + function derDecodeTag(buf, fail) { var tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; - + var cls = der.tagClass[tag >> 6]; var primitive = (tag & 0x20) === 0; - + // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { var oct = tag; @@ -1519,7 +1519,7 @@ oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; - + tag <<= 7; tag |= oct & 0x7f; } @@ -1527,7 +1527,7 @@ tag &= 0x1f; } var tagStr = der.tag[tag]; - + return { cls: cls, primitive: primitive, @@ -1535,27 +1535,27 @@ tagStr: tagStr }; } - + function derDecodeLen(buf, primitive, fail) { var len = buf.readUInt8(fail); if (buf.isError(len)) return len; - + // Indefinite form if (!primitive && len === 0x80) return null; - + // Definite form if ((len & 0x80) === 0) { // Short form return len; } - + // Long form var num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); - + len = 0; for (var i = 0; i < num; i++) { len <<= 8; @@ -1564,34 +1564,34 @@ return j; len |= j; } - + return len; } - + },{"../../asn1":5,"inherits":180}],14:[function(require,module,exports){ var decoders = exports; - + decoders.der = require('./der'); decoders.pem = require('./pem'); - + },{"./der":13,"./pem":15}],15:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; - + var DERDecoder = require('./der'); - + function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; - + PEMDecoder.prototype.decode = function decode(data, options) { var lines = data.toString().split(/[\r\n]+/g); - + var label = options.label.toUpperCase(); - + var re = /^-----(BEGIN|END) ([^-]+)-----$/; var start = -1; var end = -1; @@ -1599,10 +1599,10 @@ var match = lines[i].match(re); if (match === null) continue; - + if (match[2] !== label) continue; - + if (start === -1) { if (match[1] !== 'BEGIN') break; @@ -1616,53 +1616,53 @@ } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); - + var base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9\+\/=]+/gi, ''); - + var input = new Buffer(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; - + },{"./der":13,"buffer":84,"inherits":180}],16:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; - + var asn1 = require('../../asn1'); var base = asn1.base; - + // Import DER constants var der = asn1.constants.der; - + function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; - + // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DEREncoder; - + DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; - + // Tree methods - + function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); - + DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { var encodedTag = encodeTag(tag, primitive, cls, this.reporter); - + // Short form if (content.length < 0x80) { var header = new Buffer(2); @@ -1670,23 +1670,23 @@ header[1] = content.length; return this._createEncoderBuffer([ header, content ]); } - + // Long form // Count octets required to store length var lenOctets = 1; for (var i = content.length; i >= 0x100; i >>= 8) lenOctets++; - + var header = new Buffer(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; - + for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff; - + return this._createEncoderBuffer([ header, content ]); }; - + DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([ str.unused | 0, str.data ]); @@ -1721,7 +1721,7 @@ ' unsupported'); } }; - + DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) @@ -1736,18 +1736,18 @@ for (var i = 0; i < id.length; i++) id[i] |= 0; } - + if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } - + if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } - + // Count number of octets var size = 0; for (var i = 0; i < id.length; i++) { @@ -1755,7 +1755,7 @@ for (size++; ident >= 0x80; ident >>= 7) size++; } - + var objid = new Buffer(size); var offset = objid.length - 1; for (var i = id.length - 1; i >= 0; i--) { @@ -1764,21 +1764,21 @@ while ((ident >>= 7) > 0) objid[offset--] = 0x80 | (ident & 0x7f); } - + return this._createEncoderBuffer(objid); }; - + function two(num) { if (num < 10) return '0' + num; else return num; } - + DERNode.prototype._encodeTime = function encodeTime(time, tag) { var str; var date = new Date(time); - + if (tag === 'gentime') { str = [ two(date.getFullYear()), @@ -1802,14 +1802,14 @@ } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } - + return this._encodeStr(str, 'octstr'); }; - + DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; - + DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) @@ -1820,7 +1820,7 @@ } num = values[num]; } - + // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { var numArray = num.toArray(); @@ -1829,29 +1829,29 @@ } num = new Buffer(numArray); } - + if (Buffer.isBuffer(num)) { var size = num.length; if (num.length === 0) size++; - + var out = new Buffer(size); num.copy(out); if (num.length === 0) out[0] = 0 return this._createEncoderBuffer(out); } - + if (num < 0x80) return this._createEncoderBuffer(num); - + if (num < 0x100) return this._createEncoderBuffer([0, num]); - + var size = 1; for (var i = num; i >= 0x100; i >>= 8) size++; - + var out = new Array(size); for (var i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff; @@ -1860,89 +1860,89 @@ if(out[0] & 0x80) { out.unshift(0); } - + return this._createEncoderBuffer(new Buffer(out)); }; - + DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; - + DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; - + DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { var state = this._baseState; var i; if (state['default'] === null) return false; - + var data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - + if (data.length !== state.defaultBuffer.length) return false; - + for (i=0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false; - + return true; }; - + // Utility methods - + function encodeTag(tag, primitive, cls, reporter) { var res; - + if (tag === 'seqof') tag = 'seq'; else if (tag === 'setof') tag = 'set'; - + if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag]; else if (typeof tag === 'number' && (tag | 0) === tag) res = tag; else return reporter.error('Unknown tag: ' + tag); - + if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); - + if (!primitive) res |= 0x20; - + res |= (der.tagClassByName[cls || 'universal'] << 6); - + return res; } - + },{"../../asn1":5,"buffer":84,"inherits":180}],17:[function(require,module,exports){ var encoders = exports; - + encoders.der = require('./der'); encoders.pem = require('./pem'); - + },{"./der":16,"./pem":18}],18:[function(require,module,exports){ var inherits = require('inherits'); - + var DEREncoder = require('./der'); - + function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; - + PEMEncoder.prototype.encode = function encode(data, options) { var buf = DEREncoder.prototype.encode.call(this, data); - + var p = buf.toString('base64'); var out = [ '-----BEGIN ' + options.label + '-----' ]; for (var i = 0; i < p.length; i += 64) @@ -1950,14 +1950,14 @@ out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; - + },{"./der":16,"inherits":180}],19:[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. * @@ -1968,10 +1968,10 @@ 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]; @@ -1979,7 +1979,7 @@ break; } } - + if (x < y) { return -1; } @@ -1994,9 +1994,9 @@ } 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! @@ -2020,7 +2020,7 @@ // 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; @@ -2054,14 +2054,14 @@ // 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) { @@ -2095,7 +2095,7 @@ 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); @@ -2105,15 +2105,15 @@ 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); @@ -2134,18 +2134,18 @@ 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, @@ -2155,66 +2155,66 @@ 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`). @@ -2224,13 +2224,13 @@ 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 @@ -2243,7 +2243,7 @@ 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 @@ -2254,25 +2254,25 @@ 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; @@ -2314,51 +2314,51 @@ } 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; @@ -2366,14 +2366,14 @@ } 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 { @@ -2383,59 +2383,59 @@ } 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) { @@ -2443,30 +2443,30 @@ } return keys; }; - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"util/":333}],20:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = asyncify; - + var _isObject = require('lodash/isObject'); - + var _isObject2 = _interopRequireDefault(_isObject); - + var _initialParams = require('./internal/initialParams'); - + var _initialParams2 = _interopRequireDefault(_initialParams); - + var _setImmediate = require('./internal/setImmediate'); - + var _setImmediate2 = _interopRequireDefault(_setImmediate); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * Take a sync function and make it async, passing its return value to a * callback. This is useful for plugging sync functions into a waterfall, @@ -2543,7 +2543,7 @@ } }); } - + function invokeCallback(callback, error, value) { try { callback(error, value); @@ -2551,7 +2551,7 @@ (0, _setImmediate2.default)(rethrow, e); } } - + function rethrow(error) { throw error; } @@ -2563,7 +2563,7 @@ typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.async = global.async || {}))); }(this, (function (exports) { 'use strict'; - + function slice(arrayLike, start) { start = start|0; var newLen = Math.max(arrayLike.length - start, 0); @@ -2573,7 +2573,7 @@ } return newArr; } - + /** * Creates a continuation function with some arguments already applied. * @@ -2626,7 +2626,7 @@ return fn.apply(null, args.concat(callArgs)); }; }; - + var initialParams = function (fn) { return function (/*...args, callback*/) { var args = slice(arguments); @@ -2634,7 +2634,7 @@ fn.call(this, args, callback); }; }; - + /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) @@ -2664,14 +2664,14 @@ var type = typeof value; return value != null && (type == 'object' || type == 'function'); } - + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - + function fallback(fn) { setTimeout(fn, 0); } - + function wrap(defer) { return function (fn/*, ...args*/) { var args = slice(arguments, 1); @@ -2680,9 +2680,9 @@ }); }; } - + var _defer; - + if (hasSetImmediate) { _defer = setImmediate; } else if (hasNextTick) { @@ -2690,9 +2690,9 @@ } else { _defer = fallback; } - + var setImmediate$1 = wrap(_defer); - + /** * Take a sync function and make it async, passing its return value to a * callback. This is useful for plugging sync functions into a waterfall, @@ -2769,7 +2769,7 @@ } }); } - + function invokeCallback(callback, error, value) { try { callback(error, value); @@ -2777,21 +2777,21 @@ setImmediate$1(rethrow, e); } } - + function rethrow(error) { throw error; } - + var supportsSymbol = typeof Symbol === 'function'; - + function isAsync(fn) { return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; } - + function wrapAsync(asyncFn) { return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; } - + function applyEach$1(eachfn) { return function(fns/*, ...args*/) { var args = slice(arguments, 1); @@ -2809,35 +2809,35 @@ } }; } - + /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - + /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - + /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); - + /** Built-in value references. */ var Symbol$1 = root.Symbol; - + /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - + /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; - + /** Built-in value references. */ var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - + /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * @@ -2848,12 +2848,12 @@ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag$1), tag = value[symToStringTag$1]; - + try { value[symToStringTag$1] = undefined; var unmasked = true; } catch (e) {} - + var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { @@ -2864,17 +2864,17 @@ } return result; } - + /** Used for built-in method references. */ var objectProto$1 = Object.prototype; - + /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString$1 = objectProto$1.toString; - + /** * Converts `value` to a string using `Object.prototype.toString`. * @@ -2885,14 +2885,14 @@ function objectToString(value) { return nativeObjectToString$1.call(value); } - + /** `Object#toString` result references. */ var nullTag = '[object Null]'; var undefinedTag = '[object Undefined]'; - + /** Built-in value references. */ var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - + /** * The base implementation of `getTag` without fallbacks for buggy environments. * @@ -2908,13 +2908,13 @@ ? getRawTag(value) : objectToString(value); } - + /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]'; var funcTag = '[object Function]'; var genTag = '[object GeneratorFunction]'; var proxyTag = '[object Proxy]'; - + /** * Checks if `value` is classified as a `Function` object. * @@ -2941,10 +2941,10 @@ var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } - + /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; - + /** * Checks if `value` is a valid array-like length. * @@ -2975,7 +2975,7 @@ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } - + /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or @@ -3004,11 +3004,11 @@ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } - + // A temporary value used to identify if the loop should be broken. // See #1064, #1293 var breakLoop = {}; - + /** * This method returns `undefined`. * @@ -3024,7 +3024,7 @@ function noop() { // No operation performed. } - + function once(fn) { return function () { if (fn === null) return; @@ -3033,13 +3033,13 @@ callFn.apply(this, arguments); }; } - + var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - + var getIterator = function (coll) { return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); }; - + /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. @@ -3052,13 +3052,13 @@ function baseTimes(n, iteratee) { var index = -1, result = Array(n); - + while (++index < n) { result[index] = iteratee(index); } return result; } - + /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". @@ -3086,10 +3086,10 @@ function isObjectLike(value) { return value != null && typeof value == 'object'; } - + /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; - + /** * The base implementation of `_.isArguments`. * @@ -3100,16 +3100,16 @@ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } - + /** Used for built-in method references. */ var objectProto$3 = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - + /** Built-in value references. */ var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - + /** * Checks if `value` is likely an `arguments` object. * @@ -3132,7 +3132,7 @@ return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; - + /** * Checks if `value` is classified as an `Array` object. * @@ -3157,7 +3157,7 @@ * // => false */ var isArray = Array.isArray; - + /** * This method returns `false`. * @@ -3174,22 +3174,22 @@ function stubFalse() { return false; } - + /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - + /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - + /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; - + /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; - + /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - + /** * Checks if `value` is a buffer. * @@ -3208,13 +3208,13 @@ * // => false */ var isBuffer = nativeIsBuffer || stubFalse; - + /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER$1 = 9007199254740991; - + /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; - + /** * Checks if `value` is a valid array-like index. * @@ -3229,7 +3229,7 @@ (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } - + /** `Object#toString` result references. */ var argsTag$1 = '[object Arguments]'; var arrayTag = '[object Array]'; @@ -3244,7 +3244,7 @@ var setTag = '[object Set]'; var stringTag = '[object String]'; var weakMapTag = '[object WeakMap]'; - + var arrayBufferTag = '[object ArrayBuffer]'; var dataViewTag = '[object DataView]'; var float32Tag = '[object Float32Array]'; @@ -3256,7 +3256,7 @@ var uint8ClampedTag = '[object Uint8ClampedArray]'; var uint16Tag = '[object Uint16Array]'; var uint32Tag = '[object Uint32Array]'; - + /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = @@ -3272,7 +3272,7 @@ typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - + /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * @@ -3284,7 +3284,7 @@ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } - + /** * The base implementation of `_.unary` without support for storing metadata. * @@ -3297,29 +3297,29 @@ return func(value); }; } - + /** Detect free variable `exports`. */ var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - + /** Detect free variable `module`. */ var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - + /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - + /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports$1 && freeGlobal.process; - + /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); - + /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - + /** * Checks if `value` is classified as a typed array. * @@ -3338,13 +3338,13 @@ * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - + /** Used for built-in method references. */ var objectProto$2 = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - + /** * Creates an array of the enumerable property names of the array-like `value`. * @@ -3361,7 +3361,7 @@ skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; - + for (var key in value) { if ((inherited || hasOwnProperty$1.call(value, key)) && !(skipIndexes && ( @@ -3379,10 +3379,10 @@ } return result; } - + /** Used for built-in method references. */ var objectProto$5 = Object.prototype; - + /** * Checks if `value` is likely a prototype object. * @@ -3393,10 +3393,10 @@ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - + return value === proto; } - + /** * Creates a unary function that invokes `func` with its argument transformed. * @@ -3410,16 +3410,16 @@ return func(transform(arg)); }; } - + /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); - + /** Used for built-in method references. */ var objectProto$4 = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - + /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * @@ -3439,7 +3439,7 @@ } return result; } - + /** * Creates an array of the own enumerable property names of `object`. * @@ -3471,7 +3471,7 @@ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } - + function createArrayIterator(coll) { var i = -1; var len = coll.length; @@ -3479,7 +3479,7 @@ return ++i < len ? {value: coll[i], key: i} : null; } } - + function createES2015Iterator(iterator) { var i = -1; return function next() { @@ -3490,7 +3490,7 @@ return {value: item.value, key: i}; } } - + function createObjectIterator(obj) { var okeys = keys(obj); var i = -1; @@ -3500,16 +3500,16 @@ return i < len ? {value: obj[key], key: key} : null; }; } - + function iterator(coll) { if (isArrayLike(coll)) { return createArrayIterator(coll); } - + var iterator = getIterator(coll); return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); } - + function onlyOnce(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); @@ -3518,7 +3518,7 @@ callFn.apply(this, arguments); }; } - + function _eachOfLimit(limit) { return function (obj, iteratee, callback) { callback = once(callback || noop); @@ -3528,7 +3528,7 @@ var nextElem = iterator(obj); var done = false; var running = 0; - + function iterateeCallback(err, value) { running -= 1; if (err) { @@ -3543,7 +3543,7 @@ replenish(); } } - + function replenish () { while (running < limit && !done) { var elem = nextElem(); @@ -3558,11 +3558,11 @@ iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); } } - + replenish(); }; } - + /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a * time. @@ -3586,13 +3586,13 @@ function eachOfLimit(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); } - + function doLimit(fn, limit) { return function (iterable, iteratee, callback) { return fn(iterable, limit, iteratee, callback); }; } - + // eachOf implementation optimized for array-likes function eachOfArrayLike(coll, iteratee, callback) { callback = once(callback || noop); @@ -3602,7 +3602,7 @@ if (length === 0) { callback(null); } - + function iteratorCallback(err, value) { if (err) { callback(err); @@ -3610,15 +3610,15 @@ callback(null); } } - + for (; index < length; index++) { iteratee(coll[index], index, onlyOnce(iteratorCallback)); } } - + // a generic version of eachOf which can handle array, object, and iterator cases. var eachOfGeneric = doLimit(eachOfLimit, Infinity); - + /** * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument * to the iteratee. @@ -3662,20 +3662,20 @@ var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; eachOfImplementation(coll, wrapAsync(iteratee), callback); }; - + function doParallel(fn) { return function (obj, iteratee, callback) { return fn(eachOf, obj, wrapAsync(iteratee), callback); }; } - + function _asyncMap(eachfn, arr, iteratee, callback) { callback = callback || noop; arr = arr || []; var results = []; var counter = 0; var _iteratee = wrapAsync(iteratee); - + eachfn(arr, function (value, _, callback) { var index = counter++; _iteratee(value, function (err, v) { @@ -3686,7 +3686,7 @@ callback(err, results); }); } - + /** * Produces a new collection of values by mapping each value in `coll` through * the `iteratee` function. The `iteratee` is called with an item from `coll` @@ -3724,7 +3724,7 @@ * }); */ var map = doParallel(_asyncMap); - + /** * Applies the provided arguments to each function in the array, calling * `callback` after all functions have completed. If you only provide the first @@ -3759,13 +3759,13 @@ * ); */ var applyEach = applyEach$1(map); - + function doParallelLimit(fn) { return function (obj, limit, iteratee, callback) { return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); }; } - + /** * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. * @@ -3786,7 +3786,7 @@ * transformed items from the `coll`. Invoked with (err, results). */ var mapLimit = doParallelLimit(_asyncMap); - + /** * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. * @@ -3806,7 +3806,7 @@ * transformed items from the `coll`. Invoked with (err, results). */ var mapSeries = doLimit(mapLimit, 1); - + /** * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. * @@ -3827,7 +3827,7 @@ * function call. */ var applyEachSeries = applyEach$1(mapSeries); - + /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. @@ -3840,7 +3840,7 @@ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; - + while (++index < length) { if (iteratee(array[index], index, array) === false) { break; @@ -3848,7 +3848,7 @@ } return array; } - + /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * @@ -3862,7 +3862,7 @@ iterable = Object(object), props = keysFunc(object), length = props.length; - + while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { @@ -3872,7 +3872,7 @@ return object; }; } - + /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. @@ -3885,7 +3885,7 @@ * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); - + /** * The base implementation of `_.forOwn` without support for iteratee shorthands. * @@ -3897,7 +3897,7 @@ function baseForOwn(object, iteratee) { return object && baseFor(object, iteratee, keys); } - + /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. @@ -3912,7 +3912,7 @@ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); - + while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; @@ -3920,7 +3920,7 @@ } return -1; } - + /** * The base implementation of `_.isNaN` without support for number objects. * @@ -3931,7 +3931,7 @@ function baseIsNaN(value) { return value !== value; } - + /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. @@ -3945,7 +3945,7 @@ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; - + while (++index < length) { if (array[index] === value) { return index; @@ -3953,7 +3953,7 @@ } return -1; } - + /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * @@ -3968,7 +3968,7 @@ ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } - + /** * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on * their requirements. Each function can optionally depend on other functions @@ -4063,20 +4063,20 @@ if (!concurrency) { concurrency = numTasks; } - + var results = {}; var runningTasks = 0; var hasError = false; - + var listeners = Object.create(null); - + var readyTasks = []; - + // for cycle detection: var readyToCheck = []; // tasks that have been identified as reachable // without the possibility of returning to an ancestor task var uncheckedDependencies = {}; - + baseForOwn(tasks, function (task, key) { if (!isArray(task)) { // no dependencies @@ -4084,7 +4084,7 @@ readyToCheck.push(key); return; } - + var dependencies = task.slice(0, task.length - 1); var remainingDependencies = dependencies.length; if (remainingDependencies === 0) { @@ -4093,7 +4093,7 @@ return; } uncheckedDependencies[key] = remainingDependencies; - + arrayEach(dependencies, function (dependencyName) { if (!tasks[dependencyName]) { throw new Error('async.auto task `' + key + @@ -4109,16 +4109,16 @@ }); }); }); - + checkForDeadlocks(); processQueue(); - + function enqueueTask(key, task) { readyTasks.push(function () { runTask(key, task); }); } - + function processQueue() { if (readyTasks.length === 0 && runningTasks === 0) { return callback(null, results); @@ -4127,18 +4127,18 @@ var run = readyTasks.shift(); run(); } - + } - + function addListener(taskName, fn) { var taskListeners = listeners[taskName]; if (!taskListeners) { taskListeners = listeners[taskName] = []; } - + taskListeners.push(fn); } - + function taskComplete(taskName) { var taskListeners = listeners[taskName] || []; arrayEach(taskListeners, function (fn) { @@ -4146,11 +4146,11 @@ }); processQueue(); } - - + + function runTask(key, task) { if (hasError) return; - + var taskCallback = onlyOnce(function(err, result) { runningTasks--; if (arguments.length > 2) { @@ -4164,14 +4164,14 @@ safeResults[key] = result; hasError = true; listeners = Object.create(null); - + callback(err, safeResults); } else { results[key] = result; taskComplete(key); } }); - + runningTasks++; var taskFn = wrapAsync(task[task.length - 1]); if (task.length > 1) { @@ -4180,7 +4180,7 @@ taskFn(taskCallback); } } - + function checkForDeadlocks() { // Kahn's algorithm // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm @@ -4196,14 +4196,14 @@ } }); } - + if (counter !== numTasks) { throw new Error( 'async.auto cannot execute tasks due to a recursive dependency' ); } } - + function getDependents(taskName) { var result = []; baseForOwn(tasks, function (task, key) { @@ -4214,7 +4214,7 @@ return result; } }; - + /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. @@ -4228,16 +4228,16 @@ var index = -1, length = array == null ? 0 : array.length, result = Array(length); - + while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } - + /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; - + /** * Checks if `value` is classified as a `Symbol` primitive or object. * @@ -4259,14 +4259,14 @@ return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } - + /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; - + /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; var symbolToString = symbolProto ? symbolProto.toString : undefined; - + /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. @@ -4290,7 +4290,7 @@ var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } - + /** * The base implementation of `_.slice` without an iteratee call guard. * @@ -4303,7 +4303,7 @@ function baseSlice(array, start, end) { var index = -1, length = array.length; - + if (start < 0) { start = -start > length ? 0 : (length + start); } @@ -4313,14 +4313,14 @@ } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; - + var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } - + /** * Casts `array` to a slice if it's needed. * @@ -4335,7 +4335,7 @@ end = end === undefined ? length : end; return (!start && end >= length) ? array : baseSlice(array, start, end); } - + /** * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol * that is not found in the character symbols. @@ -4347,11 +4347,11 @@ */ function charsEndIndex(strSymbols, chrSymbols) { var index = strSymbols.length; - + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } - + /** * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol * that is not found in the character symbols. @@ -4364,11 +4364,11 @@ function charsStartIndex(strSymbols, chrSymbols) { var index = -1, length = strSymbols.length; - + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} return index; } - + /** * Converts an ASCII `string` to an array. * @@ -4379,7 +4379,7 @@ function asciiToArray(string) { return string.split(''); } - + /** Used to compose unicode character classes. */ var rsAstralRange = '\\ud800-\\udfff'; var rsComboMarksRange = '\\u0300-\\u036f'; @@ -4387,13 +4387,13 @@ var rsComboSymbolsRange = '\\u20d0-\\u20ff'; var rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange; var rsVarRange = '\\ufe0e\\ufe0f'; - + /** Used to compose unicode capture groups. */ var rsZWJ = '\\u200d'; - + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - + /** * Checks if `string` contains Unicode symbols. * @@ -4404,7 +4404,7 @@ function hasUnicode(string) { return reHasUnicode.test(string); } - + /** Used to compose unicode character classes. */ var rsAstralRange$1 = '\\ud800-\\udfff'; var rsComboMarksRange$1 = '\\u0300-\\u036f'; @@ -4412,7 +4412,7 @@ var rsComboSymbolsRange$1 = '\\u20d0-\\u20ff'; var rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1; var rsVarRange$1 = '\\ufe0e\\ufe0f'; - + /** Used to compose unicode capture groups. */ var rsAstral = '[' + rsAstralRange$1 + ']'; var rsCombo = '[' + rsComboRange$1 + ']'; @@ -4422,17 +4422,17 @@ var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; var rsZWJ$1 = '\\u200d'; - + /** Used to compose unicode regexes. */ var reOptMod = rsModifier + '?'; var rsOptVar = '[' + rsVarRange$1 + ']?'; var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; var rsSeq = rsOptVar + reOptMod + rsOptJoin; var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - + /** * Converts a Unicode `string` to an array. * @@ -4443,7 +4443,7 @@ function unicodeToArray(string) { return string.match(reUnicode) || []; } - + /** * Converts `string` to an array. * @@ -4456,7 +4456,7 @@ ? unicodeToArray(string) : asciiToArray(string); } - + /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. @@ -4481,10 +4481,10 @@ function toString(value) { return value == null ? '' : baseToString(value); } - + /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; - + /** * Removes leading and trailing whitespace or specified characters from `string`. * @@ -4519,15 +4519,15 @@ chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; - + return castSlice(strSymbols, start, end).join(''); } - + var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; var FN_ARG_SPLIT = /,/; var FN_ARG = /(=.+)?(\s*)$/; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - + function parseParams(func) { func = func.toString().replace(STRIP_COMMENTS, ''); func = func.match(FN_ARGS)[2].replace(' ', ''); @@ -4537,7 +4537,7 @@ }); return func; } - + /** * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent * tasks are specified as parameters to the function, after the usual callback @@ -4622,18 +4622,18 @@ */ function autoInject(tasks, callback) { var newTasks = {}; - + baseForOwn(tasks, function (taskFn, key) { var params; var fnIsAsync = isAsync(taskFn); var hasNoDeps = (!fnIsAsync && taskFn.length === 1) || (fnIsAsync && taskFn.length === 0); - + if (isArray(taskFn)) { params = taskFn.slice(0, -1); taskFn = taskFn[taskFn.length - 1]; - + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); } else if (hasNoDeps) { // no dependencies, use the function as-is @@ -4643,13 +4643,13 @@ if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { throw new Error("autoInject task functions require explicit parameters."); } - + // remove callback param if (!fnIsAsync) params.pop(); - + newTasks[key] = params.concat(newTask); } - + function newTask(results, taskCb) { var newArgs = arrayMap(params, function (name) { return results[name]; @@ -4658,10 +4658,10 @@ wrapAsync(taskFn).apply(null, newArgs); } }); - + auto(newTasks, callback); } - + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation // used for queues. This implementation assumes that the node provided by the user can be modified // to adjust the next and last properties. We implement only the minimal functionality @@ -4670,28 +4670,28 @@ this.head = this.tail = null; this.length = 0; } - + function setInitial(dll, node) { dll.length = 1; dll.head = dll.tail = node; } - + DLL.prototype.removeLink = function(node) { if (node.prev) node.prev.next = node.next; else this.head = node.next; if (node.next) node.next.prev = node.prev; else this.tail = node.prev; - + node.prev = node.next = null; this.length -= 1; return node; }; - + DLL.prototype.empty = function () { while(this.head) this.shift(); return this; }; - + DLL.prototype.insertAfter = function(node, newNode) { newNode.prev = node; newNode.next = node.next; @@ -4700,7 +4700,7 @@ node.next = newNode; this.length += 1; }; - + DLL.prototype.insertBefore = function(node, newNode) { newNode.prev = node.prev; newNode.next = node; @@ -4709,25 +4709,25 @@ node.prev = newNode; this.length += 1; }; - + DLL.prototype.unshift = function(node) { if (this.head) this.insertBefore(this.head, node); else setInitial(this, node); }; - + DLL.prototype.push = function(node) { if (this.tail) this.insertAfter(this.tail, node); else setInitial(this, node); }; - + DLL.prototype.shift = function() { return this.head && this.removeLink(this.head); }; - + DLL.prototype.pop = function() { return this.tail && this.removeLink(this.tail); }; - + DLL.prototype.toArray = function () { var arr = Array(this.length); var curr = this.head; @@ -4737,7 +4737,7 @@ } return arr; }; - + DLL.prototype.remove = function (testFn) { var curr = this.head; while(!!curr) { @@ -4749,7 +4749,7 @@ } return this; }; - + function queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; @@ -4757,11 +4757,11 @@ else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } - + var _worker = wrapAsync(worker); var numRunning = 0; var workersList = []; - + var processingScheduled = false; function _insert(data, insertAtFront, callback) { if (callback != null && typeof callback !== 'function') { @@ -4777,20 +4777,20 @@ q.drain(); }); } - + for (var i = 0, l = data.length; i < l; i++) { var item = { data: data[i], callback: callback || noop }; - + if (insertAtFront) { q._tasks.unshift(item); } else { q._tasks.push(item); } } - + if (!processingScheduled) { processingScheduled = true; setImmediate$1(function() { @@ -4799,39 +4799,39 @@ }); } } - + function _next(tasks) { return function(err){ numRunning -= 1; - + for (var i = 0, l = tasks.length; i < l; i++) { var task = tasks[i]; - + var index = baseIndexOf(workersList, task, 0); if (index === 0) { workersList.shift(); } else if (index > 0) { workersList.splice(index, 1); } - + task.callback.apply(task, arguments); - + if (err != null) { q.error(err, task.data); } } - + if (numRunning <= (q.concurrency - q.buffer) ) { q.unsaturated(); } - + if (q.idle()) { q.drain(); } q.process(); }; } - + var isProcessing = false; var q = { _tasks: new DLL(), @@ -4875,17 +4875,17 @@ workersList.push(node); data.push(node.data); } - + numRunning += 1; - + if (q._tasks.length === 0) { q.empty(); } - + if (numRunning === q.concurrency) { q.saturated(); } - + var cb = onlyOnce(_next(tasks)); _worker(data, cb); } @@ -4914,7 +4914,7 @@ }; return q; } - + /** * A cargo of tasks for the worker function to complete. Cargo inherits all of * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. @@ -4944,7 +4944,7 @@ * @property {Function} kill - a function that removes the `drain` callback and * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. */ - + /** * Creates a `cargo` object with the specified payload. Tasks added to the * cargo will be processed altogether (up to the `payload` limit). If the @@ -4995,7 +4995,7 @@ function cargo(worker, payload) { return queue(worker, 1, payload); } - + /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. * @@ -5014,7 +5014,7 @@ * functions have finished, or an error occurs. Invoked with (err). */ var eachOfSeries = doLimit(eachOfLimit, 1); - + /** * Reduces `coll` into a single value using an async `iteratee` to return each * successive step. `memo` is the initial state of the reduction. This function @@ -5067,7 +5067,7 @@ callback(err, memo); }); } - + /** * Version of the compose function that is more natural to read. Each function * consumes the return value of the previous function. It is the equivalent of @@ -5111,14 +5111,14 @@ return function(/*...args*/) { var args = slice(arguments); var that = this; - + var cb = args[args.length - 1]; if (typeof cb == 'function') { args.pop(); } else { cb = noop; } - + reduce(_functions, args, function(newargs, fn, cb) { fn.apply(that, newargs.concat(function(err/*, ...nextargs*/) { var nextargs = slice(arguments, 1); @@ -5130,7 +5130,7 @@ }); }; } - + /** * Creates a function which is a composition of the passed asynchronous * functions. Each function consumes the return value of the function that @@ -5169,9 +5169,9 @@ var compose = function(/*...args*/) { return seq.apply(null, slice(arguments).reverse()); }; - + var _concat = Array.prototype.concat; - + /** * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. * @@ -5205,11 +5205,11 @@ result = _concat.apply(result, mapResults[i]); } } - + return callback(err, result); }); }; - + /** * Applies `iteratee` to each item in `coll`, concatenating the results. Returns * the concatenated list. The `iteratee`s are called in parallel, and the @@ -5236,7 +5236,7 @@ * }); */ var concat = doLimit(concatLimit, Infinity); - + /** * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. * @@ -5256,7 +5256,7 @@ * (err, results). */ var concatSeries = doLimit(concatLimit, 1); - + /** * Returns a function that when called, calls-back with the values provided. * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to @@ -5307,7 +5307,7 @@ return callback.apply(this, args); }; }; - + /** * This method returns the first argument it receives. * @@ -5327,7 +5327,7 @@ function identity(value) { return value; } - + function _createTester(check, getResult) { return function(eachfn, arr, iteratee, cb) { cb = cb || noop; @@ -5354,18 +5354,18 @@ }); }; } - + function _findGetResult(v, x) { return x; } - + /** * Returns the first value in `coll` that passes an async truth test. The * `iteratee` is applied in parallel, meaning the first iteratee to return * `true` will fire the detect `callback` with that result. That means the * result might not be the first item in the original `coll` (in terms of order) * that passes the test. - + * If order within the original `coll` is important, then look at * [`detectSeries`]{@link module:Collections.detectSeries}. * @@ -5395,7 +5395,7 @@ * }); */ var detect = doParallel(_createTester(identity, _findGetResult)); - + /** * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a * time. @@ -5419,7 +5419,7 @@ * (err, result). */ var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - + /** * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. * @@ -5441,7 +5441,7 @@ * (err, result). */ var detectSeries = doLimit(detectLimit, 1); - + function consoleFunc(name) { return function (fn/*, ...args*/) { var args = slice(arguments, 1); @@ -5462,7 +5462,7 @@ wrapAsync(fn).apply(null, args); }; } - + /** * Logs the result of an [`async` function]{@link AsyncFunction} to the * `console` using `console.dir` to display the properties of the resulting object. @@ -5493,7 +5493,7 @@ * {hello: 'world'} */ var dir = consoleFunc('dir'); - + /** * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in * the order of operations, the arguments `test` and `fn` are switched. @@ -5518,24 +5518,24 @@ callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); - + function next(err/*, ...args*/) { if (err) return callback(err); var args = slice(arguments, 1); args.push(check); _test.apply(this, args); } - + function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } - + check(null, true); - + } - + /** * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in * the order of operations, the arguments `test` and `iteratee` are switched. @@ -5569,7 +5569,7 @@ }; _iteratee(next); } - + /** * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the * argument ordering differs from `until`. @@ -5595,7 +5595,7 @@ return !test.apply(this, arguments); }, callback); } - + /** * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that * is passed a callback in the form of `function (err, truth)`. If error is @@ -5636,27 +5636,27 @@ callback = onlyOnce(callback || noop); var _fn = wrapAsync(fn); var _test = wrapAsync(test); - + function next(err) { if (err) return callback(err); _test(check); } - + function check(err, truth) { if (err) return callback(err); if (!truth) return callback(null); _fn(next); } - + _test(check); } - + function _withoutIndex(iteratee) { return function (value, index, callback) { return iteratee(value, callback); }; } - + /** * Applies the function `iteratee` to each item in `coll`, in parallel. * The `iteratee` is called with an item from the list, and a callback for when @@ -5717,7 +5717,7 @@ function eachLimit(coll, iteratee, callback) { eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - + /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. * @@ -5741,7 +5741,7 @@ function eachLimit$1(coll, limit, iteratee, callback) { _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); } - + /** * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. * @@ -5762,7 +5762,7 @@ * `iteratee` functions have finished, or an error occurs. Invoked with (err). */ var eachSeries = doLimit(eachLimit$1, 1); - + /** * Wrap an async function and ensure it calls its callback on a later tick of * the event loop. If the function already calls its callback on a next tick, @@ -5816,11 +5816,11 @@ sync = false; }); } - + function notId(v) { return !v; } - + /** * Returns `true` if every element in `coll` satisfies an async test. If any * iteratee call returns `false`, the main `callback` is immediately called. @@ -5850,7 +5850,7 @@ * }); */ var every = doParallel(_createTester(notId, notId)); - + /** * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. * @@ -5872,7 +5872,7 @@ * depending on the values of the async tests. Invoked with (err, result). */ var everyLimit = doParallelLimit(_createTester(notId, notId)); - + /** * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. * @@ -5893,7 +5893,7 @@ * depending on the values of the async tests. Invoked with (err, result). */ var everySeries = doLimit(everyLimit, 1); - + /** * The base implementation of `_.property` without support for deep paths. * @@ -5906,7 +5906,7 @@ return object == null ? undefined : object[key]; }; } - + function filterArray(eachfn, arr, iteratee, callback) { var truthValues = new Array(arr.length); eachfn(arr, function (x, index, callback) { @@ -5923,7 +5923,7 @@ callback(null, results); }); } - + function filterGeneric(eachfn, coll, iteratee, callback) { var results = []; eachfn(coll, function (x, index, callback) { @@ -5947,12 +5947,12 @@ } }); } - + function _filter(eachfn, coll, iteratee, callback) { var filter = isArrayLike(coll) ? filterArray : filterGeneric; filter(eachfn, coll, wrapAsync(iteratee), callback || noop); } - + /** * Returns a new array of all the values in `coll` which pass an async truth * test. This operation is performed in parallel, but the results array will be @@ -5981,7 +5981,7 @@ * }); */ var filter = doParallel(_filter); - + /** * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a * time. @@ -6002,7 +6002,7 @@ * `iteratee` functions have finished. Invoked with (err, results). */ var filterLimit = doParallelLimit(_filter); - + /** * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. * @@ -6021,11 +6021,11 @@ * `iteratee` functions have finished. Invoked with (err, results) */ var filterSeries = doLimit(filterLimit, 1); - + /** * Calls the asynchronous function `fn` with a callback parameter that allows it * to call itself again, in series, indefinitely. - + * If an error is passed to the callback then `errback` is called with the * error, and execution stops, otherwise it will never be called. * @@ -6054,14 +6054,14 @@ function forever(fn, errback) { var done = onlyOnce(errback || noop); var task = wrapAsync(ensureAsync(fn)); - + function next(err) { if (err) return done(err); task(next); } next(); } - + /** * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. * @@ -6093,12 +6093,12 @@ var result = {}; // from MDN, handle object having an `hasOwnProperty` prop var hasOwnProperty = Object.prototype.hasOwnProperty; - + for (var i = 0; i < mapResults.length; i++) { if (mapResults[i]) { var key = mapResults[i].key; var val = mapResults[i].val; - + if (hasOwnProperty.call(result, key)) { result[key].push(val); } else { @@ -6106,11 +6106,11 @@ } } } - + return callback(err, result); }); }; - + /** * Returns a new object, where each value corresponds to an array of items, from * `coll`, that returned the corresponding key. That is, the keys of the object @@ -6148,7 +6148,7 @@ * }); */ var groupBy = doLimit(groupByLimit, Infinity); - + /** * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. * @@ -6169,7 +6169,7 @@ * properties are arrays of values which returned the corresponding key. */ var groupBySeries = doLimit(groupByLimit, 1); - + /** * Logs the result of an `async` function to the `console`. Only works in * Node.js or in browsers that support `console.log` and `console.error` (such @@ -6198,7 +6198,7 @@ * 'hello world' */ var log = consoleFunc('log'); - + /** * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a * time. @@ -6234,7 +6234,7 @@ callback(err, newObj); }); } - + /** * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. * @@ -6279,9 +6279,9 @@ * // } * }); */ - + var mapValues = doLimit(mapValuesLimit, Infinity); - + /** * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. * @@ -6302,11 +6302,11 @@ * Invoked with (err, result). */ var mapValuesSeries = doLimit(mapValuesLimit, 1); - + function has(obj, key) { return key in obj; } - + /** * Caches the results of an async function. When creating a hash to store * function results against, the callback is omitted from the hash and an @@ -6374,7 +6374,7 @@ memoized.unmemoized = fn; return memoized; } - + /** * Calls `callback` on a later loop around the event loop. In Node.js this just * calls `process.nextTicl`. In the browser it will use `setImmediate` if @@ -6407,7 +6407,7 @@ * }, 1, 2, 3); */ var _defer$1; - + if (hasNextTick) { _defer$1 = process.nextTick; } else if (hasSetImmediate) { @@ -6415,13 +6415,13 @@ } else { _defer$1 = fallback; } - + var nextTick = wrap(_defer$1); - + function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = isArrayLike(tasks) ? [] : {}; - + eachfn(tasks, function (task, key, callback) { wrapAsync(task)(function (err, result) { if (arguments.length > 2) { @@ -6434,7 +6434,7 @@ callback(err, results); }); } - + /** * Run the `tasks` collection of functions in parallel, without waiting until * the previous function has completed. If any of the functions pass an error to @@ -6507,7 +6507,7 @@ function parallelLimit(tasks, callback) { _parallel(eachOf, tasks, callback); } - + /** * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a * time. @@ -6530,7 +6530,7 @@ function parallelLimit$1(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); } - + /** * A queue of tasks for the worker function to complete. * @typedef {Object} QueueObject @@ -6584,7 +6584,7 @@ * empties remaining tasks from the queue forcing it to go idle. No more tasks * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. */ - + /** * Creates a `queue` object with the specified `concurrency`. Tasks added to the * `queue` are processed in parallel (up to the `concurrency` limit). If all @@ -6642,7 +6642,7 @@ _worker(items[0], cb); }, concurrency, 1); }; - + /** * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and * completed in ascending priority order. @@ -6669,7 +6669,7 @@ var priorityQueue = function(worker, concurrency) { // Start with a normal queue var q = queue$1(worker, concurrency); - + // Override push to accept second parameter representing priority q.push = function(data, priority, callback) { if (callback == null) callback = noop; @@ -6686,20 +6686,20 @@ q.drain(); }); } - + priority = priority || 0; var nextNode = q._tasks.head; while (nextNode && priority >= nextNode.priority) { nextNode = nextNode.next; } - + for (var i = 0, l = data.length; i < l; i++) { var item = { data: data[i], priority: priority, callback: callback }; - + if (nextNode) { q._tasks.insertBefore(nextNode, item); } else { @@ -6708,13 +6708,13 @@ } setImmediate$1(q.process); }; - + // Remove unshift function delete q.unshift; - + return q; }; - + /** * Runs the `tasks` array of functions in parallel, without waiting until the * previous function has completed. Once any of the `tasks` complete or pass an @@ -6759,7 +6759,7 @@ wrapAsync(tasks[i])(callback); } } - + /** * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. * @@ -6786,7 +6786,7 @@ var reversed = slice(array).reverse(); reduce(reversed, memo, iteratee, callback); } - + /** * Wraps the async function in another function that always completes with a * result object, even when it errors. @@ -6842,11 +6842,11 @@ reflectCallback(null, { value: value }); } }); - + return _fn.apply(this, args); }); } - + /** * A helper function that wraps an array or an object of functions with `reflect`. * @@ -6926,7 +6926,7 @@ } return results; } - + function reject$1(eachfn, arr, iteratee, callback) { _filter(eachfn, arr, function(value, cb) { iteratee(value, function(err, v) { @@ -6934,7 +6934,7 @@ }); }, callback); } - + /** * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. * @@ -6963,7 +6963,7 @@ * }); */ var reject = doParallel(reject$1); - + /** * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a * time. @@ -6984,7 +6984,7 @@ * `iteratee` functions have finished. Invoked with (err, results). */ var rejectLimit = doParallelLimit(reject$1); - + /** * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. * @@ -7003,7 +7003,7 @@ * `iteratee` functions have finished. Invoked with (err, results). */ var rejectSeries = doLimit(rejectLimit, 1); - + /** * Creates a function that returns `value`. * @@ -7028,7 +7028,7 @@ return value; }; } - + /** * Attempts to get a successful response from `task` no more than `times` times * before returning an error. If the task is successful, the `callback` will be @@ -7116,20 +7116,20 @@ function retry(opts, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; - + var options = { times: DEFAULT_TIMES, intervalFunc: constant$1(DEFAULT_INTERVAL) }; - + function parseTimes(acc, t) { if (typeof t === 'object') { acc.times = +t.times || DEFAULT_TIMES; - + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : constant$1(+t.interval || DEFAULT_INTERVAL); - + acc.errorFilter = t.errorFilter; } else if (typeof t === 'number' || typeof t === 'string') { acc.times = +t || DEFAULT_TIMES; @@ -7137,7 +7137,7 @@ throw new Error("Invalid arguments for async.retry"); } } - + if (arguments.length < 3 && typeof opts === 'function') { callback = task || noop; task = opts; @@ -7145,13 +7145,13 @@ parseTimes(options, opts); callback = callback || noop; } - + if (typeof task !== 'function') { throw new Error("Invalid arguments for async.retry"); } - + var _task = wrapAsync(task); - + var attempt = 1; function retryAttempt() { _task(function(err) { @@ -7164,10 +7164,10 @@ } }); } - + retryAttempt(); } - + /** * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method * wraps a task and makes it retryable, rather than immediately calling it @@ -7206,13 +7206,13 @@ function taskFn(cb) { _task.apply(null, args.concat(cb)); } - + if (opts) retry(opts, taskFn, callback); else retry(taskFn, callback); - + }); }; - + /** * Run the functions in the `tasks` collection in series, each one running once * the previous function has completed. If any functions in the series pass an @@ -7280,7 +7280,7 @@ function series(tasks, callback) { _parallel(eachOfSeries, tasks, callback); } - + /** * Returns `true` if at least one element in the `coll` satisfies an async test. * If any iteratee call returns `true`, the main `callback` is immediately @@ -7312,7 +7312,7 @@ * }); */ var some = doParallel(_createTester(Boolean, identity)); - + /** * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. * @@ -7335,7 +7335,7 @@ * tests. Invoked with (err, result). */ var someLimit = doParallelLimit(_createTester(Boolean, identity)); - + /** * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. * @@ -7357,7 +7357,7 @@ * tests. Invoked with (err, result). */ var someSeries = doLimit(someLimit, 1); - + /** * Sorts a list by the results of running each `coll` value through an async * `iteratee`. @@ -7416,13 +7416,13 @@ if (err) return callback(err); callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); }); - + function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } } - + /** * Sets a time limit on an asynchronous function. If the function does not call * its callback within the specified milliseconds, it will be called with a @@ -7466,11 +7466,11 @@ */ function timeout(asyncFn, milliseconds, info) { var fn = wrapAsync(asyncFn); - + return initialParams(function (args, callback) { var timedOut = false; var timer; - + function timeoutCallback() { var name = asyncFn.name || 'anonymous'; var error = new Error('Callback function "' + name + '" timed out.'); @@ -7481,24 +7481,24 @@ timedOut = true; callback(error); } - + args.push(function () { if (!timedOut) { callback.apply(null, arguments); clearTimeout(timer); } }); - + // setup timer and call original function timer = setTimeout(timeoutCallback, milliseconds); fn.apply(null, args); }); } - + /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeCeil = Math.ceil; var nativeMax = Math.max; - + /** * The base implementation of `_.range` and `_.rangeRight` which doesn't * coerce arguments. @@ -7514,14 +7514,14 @@ var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result = Array(length); - + while (length--) { result[fromRight ? length : ++index] = start; start += step; } return result; } - + /** * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a * time. @@ -7542,7 +7542,7 @@ var _iteratee = wrapAsync(iteratee); mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); } - + /** * Calls the `iteratee` function `n` times, and accumulates results in the same * manner you would use with [map]{@link module:Collections.map}. @@ -7576,7 +7576,7 @@ * }); */ var times = doLimit(timeLimit, Infinity); - + /** * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. * @@ -7592,7 +7592,7 @@ * @param {Function} callback - see {@link module:Collections.map}. */ var timesSeries = doLimit(timeLimit, 1); - + /** * A relative of `reduce`. Takes an Object or Array, and iterates over each * element in series, each step potentially mutating an `accumulator` value. @@ -7643,14 +7643,14 @@ } callback = once(callback || noop); var _iteratee = wrapAsync(iteratee); - + eachOf(coll, function(v, k, cb) { _iteratee(accumulator, v, k, cb); }, function(err) { callback(err, accumulator); }); } - + /** * It runs each task in series but stops whenever any of the functions were * successful. If one of the tasks were successful, the `callback` will be @@ -7706,7 +7706,7 @@ callback(error, result); }); } - + /** * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, * unmemoized form. Handy for testing. @@ -7725,7 +7725,7 @@ return (fn.unmemoized || fn).apply(null, arguments); }; } - + /** * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when * stopped, or an error occurs. @@ -7772,7 +7772,7 @@ }; _iteratee(next); } - + /** * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when * stopped, or an error occurs. `callback` will be passed an error and any @@ -7800,7 +7800,7 @@ return !test.apply(this, arguments); }, iteratee, callback); } - + /** * Runs the `tasks` array of functions in series, each passing their results to * the next in the array. However, if any of the `tasks` pass an error to their @@ -7863,23 +7863,23 @@ if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return callback(); var taskIndex = 0; - + function nextTask(args) { var task = wrapAsync(tasks[taskIndex++]); args.push(onlyOnce(next)); task.apply(null, args); } - + function next(err/*, ...args*/) { if (err || taskIndex === tasks.length) { return callback.apply(null, arguments); } nextTask(slice(arguments, 1)); } - + nextTask([]); }; - + /** * An "async function" in the context of Async is an asynchronous function with * a variable number of parameters, with the final parameter being a callback. @@ -7918,7 +7918,7 @@ * @typedef {Function} AsyncFunction * @static */ - + /** * Async is a utility module which provides straight-forward, powerful functions * for working with asynchronous JavaScript. Although originally designed for @@ -7927,24 +7927,24 @@ * @module async * @see AsyncFunction */ - - + + /** * A collection of `async` functions for manipulating collections, such as * arrays and objects. * @module Collections */ - + /** * A collection of `async` functions for controlling the flow through a script. * @module ControlFlow */ - + /** * A collection of `async` utility functions. * @module Utils */ - + var index = { apply: apply, applyEach: applyEach, @@ -8023,7 +8023,7 @@ until: until, waterfall: waterfall, whilst: whilst, - + // aliases all: every, allLimit: everyLimit, @@ -8048,7 +8048,7 @@ selectSeries: filterSeries, wrapSync: asyncify }; - + exports['default'] = index; exports.apply = apply; exports.applyEach = applyEach; @@ -8149,34 +8149,34 @@ exports.selectLimit = filterLimit; exports.selectSeries = filterSeries; exports.wrapSync = asyncify; - + Object.defineProperty(exports, '__esModule', { value: true }); - + }))); - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":257}],22:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = eachLimit; - + var _eachOfLimit = require('./internal/eachOfLimit'); - + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - + var _withoutIndex = require('./internal/withoutIndex'); - + var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - + var _wrapAsync = require('./internal/wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. * @@ -8203,50 +8203,50 @@ module.exports = exports['default']; },{"./internal/eachOfLimit":29,"./internal/withoutIndex":39,"./internal/wrapAsync":40}],23:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + exports.default = function (coll, iteratee, callback) { var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); }; - + var _isArrayLike = require('lodash/isArrayLike'); - + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - + var _breakLoop = require('./internal/breakLoop'); - + var _breakLoop2 = _interopRequireDefault(_breakLoop); - + var _eachOfLimit = require('./eachOfLimit'); - + var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - + var _doLimit = require('./internal/doLimit'); - + var _doLimit2 = _interopRequireDefault(_doLimit); - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _once = require('./internal/once'); - + var _once2 = _interopRequireDefault(_once); - + var _onlyOnce = require('./internal/onlyOnce'); - + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - + var _wrapAsync = require('./internal/wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + // eachOf implementation optimized for array-likes function eachOfArrayLike(coll, iteratee, callback) { callback = (0, _once2.default)(callback || _noop2.default); @@ -8256,7 +8256,7 @@ if (length === 0) { callback(null); } - + function iteratorCallback(err, value) { if (err) { callback(err); @@ -8264,15 +8264,15 @@ callback(null); } } - + for (; index < length; index++) { iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); } } - + // a generic version of eachOf which can handle array, object, and iterator cases. var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - + /** * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument * to the iteratee. @@ -8315,22 +8315,22 @@ module.exports = exports['default']; },{"./eachOfLimit":24,"./internal/breakLoop":26,"./internal/doLimit":27,"./internal/once":34,"./internal/onlyOnce":35,"./internal/wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],24:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = eachOfLimit; - + var _eachOfLimit2 = require('./internal/eachOfLimit'); - + var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - + var _wrapAsync = require('./internal/wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a * time. @@ -8357,21 +8357,21 @@ module.exports = exports['default']; },{"./internal/eachOfLimit":29,"./internal/wrapAsync":40}],25:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + var _eachLimit = require('./eachLimit'); - + var _eachLimit2 = _interopRequireDefault(_eachLimit); - + var _doLimit = require('./internal/doLimit'); - + var _doLimit2 = _interopRequireDefault(_doLimit); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. * @@ -8395,7 +8395,7 @@ module.exports = exports['default']; },{"./eachLimit":22,"./internal/doLimit":27}],26:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8405,7 +8405,7 @@ module.exports = exports["default"]; },{}],27:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8418,22 +8418,22 @@ module.exports = exports["default"]; },{}],28:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = doParallel; - + var _eachOf = require('../eachOf'); - + var _eachOf2 = _interopRequireDefault(_eachOf); - + var _wrapAsync = require('./wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + function doParallel(fn) { return function (obj, iteratee, callback) { return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); @@ -8442,34 +8442,34 @@ module.exports = exports['default']; },{"../eachOf":23,"./wrapAsync":40}],29:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _eachOfLimit; - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _once = require('./once'); - + var _once2 = _interopRequireDefault(_once); - + var _iterator = require('./iterator'); - + var _iterator2 = _interopRequireDefault(_iterator); - + var _onlyOnce = require('./onlyOnce'); - + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - + var _breakLoop = require('./breakLoop'); - + var _breakLoop2 = _interopRequireDefault(_breakLoop); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + function _eachOfLimit(limit) { return function (obj, iteratee, callback) { callback = (0, _once2.default)(callback || _noop2.default); @@ -8479,7 +8479,7 @@ var nextElem = (0, _iterator2.default)(obj); var done = false; var running = 0; - + function iterateeCallback(err, value) { running -= 1; if (err) { @@ -8492,7 +8492,7 @@ replenish(); } } - + function replenish() { while (running < limit && !done) { var elem = nextElem(); @@ -8507,32 +8507,32 @@ iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); } } - + replenish(); }; } module.exports = exports['default']; },{"./breakLoop":26,"./iterator":32,"./once":34,"./onlyOnce":35,"lodash/noop":229}],30:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + exports.default = function (coll) { return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); }; - + var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - + module.exports = exports['default']; },{}],31:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + exports.default = function (fn) { return function () /*...args, callback*/{ var args = (0, _slice2.default)(arguments); @@ -8540,36 +8540,36 @@ fn.call(this, args, callback); }; }; - + var _slice = require('./slice'); - + var _slice2 = _interopRequireDefault(_slice); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + module.exports = exports['default']; },{"./slice":38}],32:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = iterator; - + var _isArrayLike = require('lodash/isArrayLike'); - + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - + var _getIterator = require('./getIterator'); - + var _getIterator2 = _interopRequireDefault(_getIterator); - + var _keys = require('lodash/keys'); - + var _keys2 = _interopRequireDefault(_keys); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + function createArrayIterator(coll) { var i = -1; var len = coll.length; @@ -8577,7 +8577,7 @@ return ++i < len ? { value: coll[i], key: i } : null; }; } - + function createES2015Iterator(iterator) { var i = -1; return function next() { @@ -8587,7 +8587,7 @@ return { value: item.value, key: i }; }; } - + function createObjectIterator(obj) { var okeys = (0, _keys2.default)(obj); var i = -1; @@ -8597,41 +8597,41 @@ return i < len ? { value: obj[key], key: key } : null; }; } - + function iterator(coll) { if ((0, _isArrayLike2.default)(coll)) { return createArrayIterator(coll); } - + var iterator = (0, _getIterator2.default)(coll); return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); } module.exports = exports['default']; },{"./getIterator":30,"lodash/isArrayLike":221,"lodash/keys":228}],33:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _asyncMap; - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _wrapAsync = require('./wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + function _asyncMap(eachfn, arr, iteratee, callback) { callback = callback || _noop2.default; arr = arr || []; var results = []; var counter = 0; var _iteratee = (0, _wrapAsync2.default)(iteratee); - + eachfn(arr, function (value, _, callback) { var index = counter++; _iteratee(value, function (err, v) { @@ -8645,7 +8645,7 @@ module.exports = exports['default']; },{"./wrapAsync":40,"lodash/noop":229}],34:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8661,7 +8661,7 @@ module.exports = exports["default"]; },{}],35:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8677,34 +8677,34 @@ module.exports = exports["default"]; },{}],36:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = _parallel; - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _isArrayLike = require('lodash/isArrayLike'); - + var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - + var _slice = require('./slice'); - + var _slice2 = _interopRequireDefault(_slice); - + var _wrapAsync = require('./wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + function _parallel(eachfn, tasks, callback) { callback = callback || _noop2.default; var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; - + eachfn(tasks, function (task, key, callback) { (0, _wrapAsync2.default)(task)(function (err, result) { if (arguments.length > 2) { @@ -8721,27 +8721,27 @@ },{"./slice":38,"./wrapAsync":40,"lodash/isArrayLike":221,"lodash/noop":229}],37:[function(require,module,exports){ (function (process){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.hasNextTick = exports.hasSetImmediate = undefined; exports.fallback = fallback; exports.wrap = wrap; - + var _slice = require('./slice'); - + var _slice2 = _interopRequireDefault(_slice); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - + function fallback(fn) { setTimeout(fn, 0); } - + function wrap(defer) { return function (fn /*, ...args*/) { var args = (0, _slice2.default)(arguments, 1); @@ -8750,9 +8750,9 @@ }); }; } - + var _defer; - + if (hasSetImmediate) { _defer = setImmediate; } else if (hasNextTick) { @@ -8760,12 +8760,12 @@ } else { _defer = fallback; } - + exports.default = wrap(_defer); }).call(this,require('_process')) },{"./slice":38,"_process":257}],38:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8782,7 +8782,7 @@ module.exports = exports["default"]; },{}],39:[function(require,module,exports){ "use strict"; - + Object.defineProperty(exports, "__esModule", { value: true }); @@ -8795,47 +8795,47 @@ module.exports = exports["default"]; },{}],40:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.isAsync = undefined; - + var _asyncify = require('../asyncify'); - + var _asyncify2 = _interopRequireDefault(_asyncify); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + var supportsSymbol = typeof Symbol === 'function'; - + function isAsync(fn) { return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; } - + function wrapAsync(asyncFn) { return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; } - + exports.default = wrapAsync; exports.isAsync = isAsync; },{"../asyncify":20}],41:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + var _doParallel = require('./internal/doParallel'); - + var _doParallel2 = _interopRequireDefault(_doParallel); - + var _map = require('./internal/map'); - + var _map2 = _interopRequireDefault(_map); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * Produces a new collection of values by mapping each value in `coll` through * the `iteratee` function. The `iteratee` is called with an item from `coll` @@ -8876,22 +8876,22 @@ module.exports = exports['default']; },{"./internal/doParallel":28,"./internal/map":33}],42:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = parallelLimit; - + var _eachOf = require('./eachOf'); - + var _eachOf2 = _interopRequireDefault(_eachOf); - + var _parallel = require('./internal/parallel'); - + var _parallel2 = _interopRequireDefault(_parallel); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * Run the `tasks` collection of functions in parallel, without waiting until * the previous function has completed. If any of the functions pass an error to @@ -8967,26 +8967,26 @@ module.exports = exports['default']; },{"./eachOf":23,"./internal/parallel":36}],43:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); exports.default = retry; - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _constant = require('lodash/constant'); - + var _constant2 = _interopRequireDefault(_constant); - + var _wrapAsync = require('./internal/wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + /** * Attempts to get a successful response from `task` no more than `times` times * before returning an error. If the task is successful, the `callback` will be @@ -9074,18 +9074,18 @@ function retry(opts, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; - + var options = { times: DEFAULT_TIMES, intervalFunc: (0, _constant2.default)(DEFAULT_INTERVAL) }; - + function parseTimes(acc, t) { if (typeof t === 'object') { acc.times = +t.times || DEFAULT_TIMES; - + acc.intervalFunc = typeof t.interval === 'function' ? t.interval : (0, _constant2.default)(+t.interval || DEFAULT_INTERVAL); - + acc.errorFilter = t.errorFilter; } else if (typeof t === 'number' || typeof t === 'string') { acc.times = +t || DEFAULT_TIMES; @@ -9093,7 +9093,7 @@ throw new Error("Invalid arguments for async.retry"); } } - + if (arguments.length < 3 && typeof opts === 'function') { callback = task || _noop2.default; task = opts; @@ -9101,13 +9101,13 @@ parseTimes(options, opts); callback = callback || _noop2.default; } - + if (typeof task !== 'function') { throw new Error("Invalid arguments for async.retry"); } - + var _task = (0, _wrapAsync2.default)(task); - + var attempt = 1; function retryAttempt() { _task(function (err) { @@ -9118,67 +9118,67 @@ } }); } - + retryAttempt(); } module.exports = exports['default']; },{"./internal/wrapAsync":40,"lodash/constant":218,"lodash/noop":229}],44:[function(require,module,exports){ 'use strict'; - + Object.defineProperty(exports, "__esModule", { value: true }); - + exports.default = function (tasks, callback) { callback = (0, _once2.default)(callback || _noop2.default); if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); if (!tasks.length) return callback(); var taskIndex = 0; - + function nextTask(args) { var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); args.push((0, _onlyOnce2.default)(next)); task.apply(null, args); } - + function next(err /*, ...args*/) { if (err || taskIndex === tasks.length) { return callback.apply(null, arguments); } nextTask((0, _slice2.default)(arguments, 1)); } - + nextTask([]); }; - + var _isArray = require('lodash/isArray'); - + var _isArray2 = _interopRequireDefault(_isArray); - + var _noop = require('lodash/noop'); - + var _noop2 = _interopRequireDefault(_noop); - + var _once = require('./internal/once'); - + var _once2 = _interopRequireDefault(_once); - + var _slice = require('./internal/slice'); - + var _slice2 = _interopRequireDefault(_slice); - + var _onlyOnce = require('./internal/onlyOnce'); - + var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - + var _wrapAsync = require('./internal/wrapAsync'); - + var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - + function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - + module.exports = exports['default']; - + /** * Runs the `tasks` array of functions in series, each passing their results to * the next in the array. However, if any of the `tasks` pass an error to their @@ -9239,27 +9239,27 @@ },{"./internal/once":34,"./internal/onlyOnce":35,"./internal/slice":38,"./internal/wrapAsync":40,"lodash/isArray":220,"lodash/noop":229}],45:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var Backoff = require('./lib/backoff'); var ExponentialBackoffStrategy = require('./lib/strategy/exponential'); var FibonacciBackoffStrategy = require('./lib/strategy/fibonacci'); var FunctionCall = require('./lib/function_call.js'); - + module.exports.Backoff = Backoff; module.exports.FunctionCall = FunctionCall; module.exports.FibonacciStrategy = FibonacciBackoffStrategy; module.exports.ExponentialStrategy = ExponentialBackoffStrategy; - + // Constructs a Fibonacci backoff. module.exports.fibonacci = function(options) { return new Backoff(new FibonacciBackoffStrategy(options)); }; - + // Constructs an exponential backoff. module.exports.exponential = function(options) { return new Backoff(new ExponentialBackoffStrategy(options)); }; - + // Constructs a FunctionCall for the given function and arguments. module.exports.call = function(fn, vargs, callback) { var args = Array.prototype.slice.call(arguments); @@ -9268,47 +9268,47 @@ callback = args[args.length - 1]; return new FunctionCall(fn, vargs, callback); }; - + },{"./lib/backoff":46,"./lib/function_call.js":47,"./lib/strategy/exponential":48,"./lib/strategy/fibonacci":49}],46:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var events = require('events'); var precond = require('precond'); var util = require('util'); - + // A class to hold the state of a backoff operation. Accepts a backoff strategy // to generate the backoff delays. function Backoff(backoffStrategy) { events.EventEmitter.call(this); - + this.backoffStrategy_ = backoffStrategy; this.maxNumberOfRetry_ = -1; this.backoffNumber_ = 0; this.backoffDelay_ = 0; this.timeoutID_ = -1; - + this.handlers = { backoff: this.onBackoff_.bind(this) }; } util.inherits(Backoff, events.EventEmitter); - + // Sets a limit, greater than 0, on the maximum number of backoffs. A 'fail' // event will be emitted when the limit is reached. Backoff.prototype.failAfter = function(maxNumberOfRetry) { precond.checkArgument(maxNumberOfRetry > 0, 'Expected a maximum number of retry greater than 0 but got %s.', maxNumberOfRetry); - + this.maxNumberOfRetry_ = maxNumberOfRetry; }; - + // Starts a backoff operation. Accepts an optional parameter to let the // listeners know why the backoff operation was started. Backoff.prototype.backoff = function(err) { precond.checkState(this.timeoutID_ === -1, 'Backoff in progress.'); - + if (this.backoffNumber_ === this.maxNumberOfRetry_) { this.emit('fail', err); this.reset(); @@ -9318,14 +9318,14 @@ this.emit('backoff', this.backoffNumber_, this.backoffDelay_, err); } }; - + // Handles the backoff timeout completion. Backoff.prototype.onBackoff_ = function() { this.timeoutID_ = -1; this.emit('ready', this.backoffNumber_, this.backoffDelay_); this.backoffNumber_++; }; - + // Stops any backoff operation and resets the backoff delay to its inital value. Backoff.prototype.reset = function() { this.backoffNumber_ = 0; @@ -9333,43 +9333,43 @@ clearTimeout(this.timeoutID_); this.timeoutID_ = -1; }; - + module.exports = Backoff; - + },{"events":157,"precond":253,"util":333}],47:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var events = require('events'); var precond = require('precond'); var util = require('util'); - + var Backoff = require('./backoff'); var FibonacciBackoffStrategy = require('./strategy/fibonacci'); - + // Wraps a function to be called in a backoff loop. function FunctionCall(fn, args, callback) { events.EventEmitter.call(this); - + precond.checkIsFunction(fn, 'Expected fn to be a function.'); precond.checkIsArray(args, 'Expected args to be an array.'); precond.checkIsFunction(callback, 'Expected callback to be a function.'); - + this.function_ = fn; this.arguments_ = args; this.callback_ = callback; this.lastResult_ = []; this.numRetries_ = 0; - + this.backoff_ = null; this.strategy_ = null; this.failAfter_ = -1; this.retryPredicate_ = FunctionCall.DEFAULT_RETRY_PREDICATE_; - + this.state_ = FunctionCall.State_.PENDING; } util.inherits(FunctionCall, events.EventEmitter); - + // States in which the call can be. FunctionCall.State_ = { // Call isn't started yet. @@ -9382,32 +9382,32 @@ // The call was aborted. ABORTED: 3 }; - + // The default retry predicate which considers any error as retriable. FunctionCall.DEFAULT_RETRY_PREDICATE_ = function(err) { return true; }; - + // Checks whether the call is pending. FunctionCall.prototype.isPending = function() { return this.state_ == FunctionCall.State_.PENDING; }; - + // Checks whether the call is in progress. FunctionCall.prototype.isRunning = function() { return this.state_ == FunctionCall.State_.RUNNING; }; - + // Checks whether the call is completed. FunctionCall.prototype.isCompleted = function() { return this.state_ == FunctionCall.State_.COMPLETED; }; - + // Checks whether the call is aborted. FunctionCall.prototype.isAborted = function() { return this.state_ == FunctionCall.State_.ABORTED; }; - + // Sets the backoff strategy to use. Can only be called before the call is // started otherwise an exception will be thrown. FunctionCall.prototype.setStrategy = function(strategy) { @@ -9415,7 +9415,7 @@ this.strategy_ = strategy; return this; // Return this for chaining. }; - + // Sets the predicate which will be used to determine whether the errors // returned from the wrapped function should be retried or not, e.g. a // network error would be retriable while a type error would stop the @@ -9425,65 +9425,65 @@ this.retryPredicate_ = retryPredicate; return this; }; - + // Returns all intermediary results returned by the wrapped function since // the initial call. FunctionCall.prototype.getLastResult = function() { return this.lastResult_.concat(); }; - + // Returns the number of times the wrapped function call was retried. FunctionCall.prototype.getNumRetries = function() { return this.numRetries_; }; - + // Sets the backoff limit. FunctionCall.prototype.failAfter = function(maxNumberOfRetry) { precond.checkState(this.isPending(), 'FunctionCall in progress.'); this.failAfter_ = maxNumberOfRetry; return this; // Return this for chaining. }; - + // Aborts the call. FunctionCall.prototype.abort = function() { if (this.isCompleted() || this.isAborted()) { return; } - + if (this.isRunning()) { this.backoff_.reset(); } - + this.state_ = FunctionCall.State_.ABORTED; this.lastResult_ = [new Error('Backoff aborted.')]; this.emit('abort'); this.doCallback_(); }; - + // Initiates the call to the wrapped function. Accepts an optional factory // function used to create the backoff instance; used when testing. FunctionCall.prototype.start = function(backoffFactory) { precond.checkState(!this.isAborted(), 'FunctionCall is aborted.'); precond.checkState(this.isPending(), 'FunctionCall already started.'); - + var strategy = this.strategy_ || new FibonacciBackoffStrategy(); - + this.backoff_ = backoffFactory ? backoffFactory(strategy) : new Backoff(strategy); - + this.backoff_.on('ready', this.doCall_.bind(this, true /* isRetry */)); this.backoff_.on('fail', this.doCallback_.bind(this)); this.backoff_.on('backoff', this.handleBackoff_.bind(this)); - + if (this.failAfter_ > 0) { this.backoff_.failAfter(this.failAfter_); } - + this.state_ = FunctionCall.State_.RUNNING; this.doCall_(false /* isRetry */); }; - + // Calls the wrapped function. FunctionCall.prototype.doCall_ = function(isRetry) { if (isRetry) { @@ -9494,24 +9494,24 @@ var callback = this.handleFunctionCallback_.bind(this); this.function_.apply(null, this.arguments_.concat(callback)); }; - + // Calls the wrapped function's callback with the last result returned by the // wrapped function. FunctionCall.prototype.doCallback_ = function() { this.callback_.apply(null, this.lastResult_); }; - + // Handles wrapped function's completion. This method acts as a replacement // for the original callback function. FunctionCall.prototype.handleFunctionCallback_ = function() { if (this.isAborted()) { return; } - + var args = Array.prototype.slice.call(arguments); this.lastResult_ = args; // Save last callback arguments. events.EventEmitter.prototype.emit.apply(this, ['callback'].concat(args)); - + var err = args[0]; if (err && this.retryPredicate_(err)) { this.backoff_.backoff(err); @@ -9520,30 +9520,30 @@ this.doCallback_(); } }; - + // Handles the backoff event by reemitting it. FunctionCall.prototype.handleBackoff_ = function(number, delay, err) { this.emit('backoff', number, delay, err); }; - + module.exports = FunctionCall; - + },{"./backoff":46,"./strategy/fibonacci":49,"events":157,"precond":253,"util":333}],48:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var util = require('util'); var precond = require('precond'); - + var BackoffStrategy = require('./strategy'); - + // Exponential backoff strategy. function ExponentialBackoffStrategy(options) { BackoffStrategy.call(this, options); this.backoffDelay_ = 0; this.nextBackoffDelay_ = this.getInitialDelay(); this.factor_ = ExponentialBackoffStrategy.DEFAULT_FACTOR; - + if (options && options.factor !== undefined) { precond.checkArgument(options.factor > 1, 'Exponential factor should be greater than 1 but got %s.', @@ -9552,33 +9552,33 @@ } } util.inherits(ExponentialBackoffStrategy, BackoffStrategy); - + // Default multiplication factor used to compute the next backoff delay from // the current one. The value can be overridden by passing a custom factor as // part of the options. ExponentialBackoffStrategy.DEFAULT_FACTOR = 2; - + ExponentialBackoffStrategy.prototype.next_ = function() { this.backoffDelay_ = Math.min(this.nextBackoffDelay_, this.getMaxDelay()); this.nextBackoffDelay_ = this.backoffDelay_ * this.factor_; return this.backoffDelay_; }; - + ExponentialBackoffStrategy.prototype.reset_ = function() { this.backoffDelay_ = 0; this.nextBackoffDelay_ = this.getInitialDelay(); }; - + module.exports = ExponentialBackoffStrategy; - + },{"./strategy":50,"precond":253,"util":333}],49:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var util = require('util'); - + var BackoffStrategy = require('./strategy'); - + // Fibonacci backoff strategy. function FibonacciBackoffStrategy(options) { BackoffStrategy.call(this, options); @@ -9586,32 +9586,32 @@ this.nextBackoffDelay_ = this.getInitialDelay(); } util.inherits(FibonacciBackoffStrategy, BackoffStrategy); - + FibonacciBackoffStrategy.prototype.next_ = function() { var backoffDelay = Math.min(this.nextBackoffDelay_, this.getMaxDelay()); this.nextBackoffDelay_ += this.backoffDelay_; this.backoffDelay_ = backoffDelay; return backoffDelay; }; - + FibonacciBackoffStrategy.prototype.reset_ = function() { this.nextBackoffDelay_ = this.getInitialDelay(); this.backoffDelay_ = 0; }; - + module.exports = FibonacciBackoffStrategy; - + },{"./strategy":50,"util":333}],50:[function(require,module,exports){ // Copyright (c) 2012 Mathieu Turcotte // Licensed under the MIT license. - + var events = require('events'); var util = require('util'); - + function isDef(value) { return value !== undefined && value !== null; } - + // Abstract class defining the skeleton for the backoff strategies. Accepts an // object holding the options for the backoff strategy: // @@ -9622,39 +9622,39 @@ // * `maxDelay`: The backoff maximal delay in milliseconds. function BackoffStrategy(options) { options = options || {}; - + if (isDef(options.initialDelay) && options.initialDelay < 1) { throw new Error('The initial timeout must be greater than 0.'); } else if (isDef(options.maxDelay) && options.maxDelay < 1) { throw new Error('The maximal timeout must be greater than 0.'); } - + this.initialDelay_ = options.initialDelay || 100; this.maxDelay_ = options.maxDelay || 10000; - + if (this.maxDelay_ <= this.initialDelay_) { throw new Error('The maximal backoff delay must be ' + 'greater than the initial backoff delay.'); } - + if (isDef(options.randomisationFactor) && (options.randomisationFactor < 0 || options.randomisationFactor > 1)) { throw new Error('The randomisation factor must be between 0 and 1.'); } - + this.randomisationFactor_ = options.randomisationFactor || 0; } - + // Gets the maximal backoff delay. BackoffStrategy.prototype.getMaxDelay = function() { return this.maxDelay_; }; - + // Gets the initial backoff delay. BackoffStrategy.prototype.getInitialDelay = function() { return this.initialDelay_; }; - + // Template method that computes and returns the next backoff delay in // milliseconds. BackoffStrategy.prototype.next = function() { @@ -9663,52 +9663,52 @@ var randomizedDelay = Math.round(backoffDelay * randomisationMultiple); return randomizedDelay; }; - + // Computes and returns the next backoff delay. Intended to be overridden by // subclasses. BackoffStrategy.prototype.next_ = function() { throw new Error('BackoffStrategy.next_() unimplemented.'); }; - + // Template method that resets the backoff delay to its initial value. BackoffStrategy.prototype.reset = function() { this.reset_(); }; - + // Resets the backoff delay to its initial value. Intended to be overridden by // subclasses. BackoffStrategy.prototype.reset_ = function() { throw new Error('BackoffStrategy.reset_() unimplemented.'); }; - + module.exports = BackoffStrategy; - + },{"events":157,"util":333}],51:[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 } - + revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 - + function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } - + // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte @@ -9716,31 +9716,31 @@ // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } - + function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } - + function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) - + arr = new Arr((len * 3 / 4) - placeHolders) - + // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len - + var L = 0 - + for (i = 0; i < l; 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[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } - + if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF @@ -9749,14 +9749,14 @@ arr[L++] = (tmp >> 8) & 0xFF arr[L++] = 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 = [] @@ -9766,7 +9766,7 @@ } return output.join('') } - + function fromByteArray (uint8) { var tmp var len = uint8.length @@ -9774,12 +9774,12 @@ var output = '' 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] @@ -9793,72 +9793,72 @@ output += lookup[(tmp << 2) & 0x3F] output += '=' } - + parts.push(output) - + return parts.join('') } - + },{}],52:[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. * @@ -9892,9 +9892,9 @@ 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 @@ -9904,25 +9904,25 @@ 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":290}],53:[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) { @@ -9932,27 +9932,27 @@ 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'); } } @@ -9961,72 +9961,72 @@ } 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; @@ -10050,13 +10050,13 @@ ]; 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'); @@ -10065,13 +10065,13 @@ 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') { @@ -10099,23 +10099,23 @@ } 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; @@ -10123,7 +10123,7 @@ } 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); @@ -10131,7 +10131,7 @@ 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; @@ -10153,23 +10153,23 @@ } 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; @@ -10177,27 +10177,27 @@ } 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; @@ -10205,15 +10205,15 @@ 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; @@ -10222,7 +10222,7 @@ } } }; - + BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { @@ -10232,20 +10232,20 @@ 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) { @@ -10253,7 +10253,7 @@ } return this._normSign(); }; - + BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { @@ -10261,17 +10261,17 @@ } 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) { @@ -10293,9 +10293,9 @@ groupSizes[base] = groupSize; groupBases[base] = groupBase; } - + */ - + var zeros = [ '', '0', @@ -10324,7 +10324,7 @@ '000000000000000000000000', '0000000000000000000000000' ]; - + var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, @@ -10333,7 +10333,7 @@ 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, @@ -10342,11 +10342,11 @@ 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 = ''; @@ -10378,7 +10378,7 @@ } 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]; @@ -10390,7 +10390,7 @@ 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 { @@ -10408,10 +10408,10 @@ } 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) { @@ -10424,30 +10424,30 @@ } 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) { @@ -10455,29 +10455,29 @@ 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); @@ -10505,11 +10505,11 @@ 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) { @@ -10533,31 +10533,31 @@ } 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]); @@ -10566,71 +10566,71 @@ } 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) @@ -10640,32 +10640,32 @@ } 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 @@ -10678,99 +10678,99 @@ 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; @@ -10778,7 +10778,7 @@ num.negative = 1; return r._normSign(); } - + // a.length > b.length var a, b; if (this.length > num.length) { @@ -10788,7 +10788,7 @@ 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; @@ -10800,7 +10800,7 @@ this.words[i] = r & 0x3ffffff; carry = r >>> 26; } - + this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; @@ -10811,10 +10811,10 @@ this.words[i] = a.words[i]; } } - + return this; }; - + // Add `num` to `this` BN.prototype.add = function add (num) { var res; @@ -10829,12 +10829,12 @@ 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 @@ -10843,7 +10843,7 @@ var r = this.iadd(num); num.negative = 1; return r._normSign(); - + // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; @@ -10851,10 +10851,10 @@ 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; @@ -10862,7 +10862,7 @@ this.words[0] = 0; return this; } - + // a > b var a, b; if (cmp > 0) { @@ -10872,7 +10872,7 @@ 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; @@ -10884,43 +10884,43 @@ 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 @@ -10943,10 +10943,10 @@ } 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). @@ -11018,7 +11018,7 @@ var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; - + out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ @@ -11522,16 +11522,16 @@ } 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++) { @@ -11546,13 +11546,13 @@ 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; } @@ -11565,15 +11565,15 @@ } 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; @@ -11586,41 +11586,41 @@ } 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) { @@ -11629,42 +11629,42 @@ 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; } @@ -11672,7 +11672,7 @@ } } }; - + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; @@ -11680,135 +11680,135 @@ 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++) { @@ -11820,51 +11820,51 @@ 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); @@ -11872,44 +11872,44 @@ 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 @@ -11921,15 +11921,15 @@ } 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++) { @@ -11937,7 +11937,7 @@ } maskedWords.length = s; } - + if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { @@ -11949,103 +11949,103 @@ 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) { @@ -12053,20 +12053,20 @@ 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; @@ -12077,25 +12077,25 @@ } } 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; @@ -12106,34 +12106,34 @@ 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++) { @@ -12148,9 +12148,9 @@ carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } - + if (carry === 0) return this.strip(); - + // Subtraction overflow assert(carry === -1); carry = 0; @@ -12160,16 +12160,16 @@ 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); @@ -12179,11 +12179,11 @@ 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; @@ -12192,7 +12192,7 @@ q.words[i] = 0; } } - + var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; @@ -12200,15 +12200,15 @@ 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--; @@ -12226,84 +12226,84 @@ 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 { @@ -12311,7 +12311,7 @@ mod: this }; } - + // Very short reduction if (num.length === 1) { if (mode === 'div') { @@ -12320,119 +12320,119 @@ 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) { @@ -12442,12 +12442,12 @@ 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); @@ -12456,12 +12456,12 @@ C.iadd(yp); D.isub(xp); } - + C.iushrn(1); D.iushrn(1); } } - + if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); @@ -12472,35 +12472,35 @@ 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) { @@ -12509,11 +12509,11 @@ 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); @@ -12521,11 +12521,11 @@ if (x2.isOdd()) { x2.iadd(delta); } - + x2.iushrn(1); } } - + if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); @@ -12534,36 +12534,36 @@ 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); @@ -12571,7 +12571,7 @@ 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` @@ -12581,45 +12581,45 @@ } 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++) { @@ -12635,19 +12635,19 @@ } 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; @@ -12655,16 +12655,16 @@ 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` @@ -12672,23 +12672,23 @@ 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; @@ -12699,47 +12699,47 @@ } 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. @@ -12747,103 +12747,103 @@ 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, @@ -12851,7 +12851,7 @@ p192: null, p25519: null }; - + // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K @@ -12859,29 +12859,29 @@ 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; @@ -12891,18 +12891,18 @@ } 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, @@ -12910,27 +12910,27 @@ '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); @@ -12944,13 +12944,13 @@ 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++) { @@ -12959,7 +12959,7 @@ num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } - + // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; @@ -12969,7 +12969,7 @@ } return num; }; - + function P224 () { MPrime.call( this, @@ -12977,7 +12977,7 @@ 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); - + function P192 () { MPrime.call( this, @@ -12985,7 +12985,7 @@ 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); - + function P25519 () { // 2 ^ 255 - 19 MPrime.call( @@ -12994,7 +12994,7 @@ '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); - + P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; @@ -13002,7 +13002,7 @@ var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; - + num.words[i] = lo; carry = hi; } @@ -13011,12 +13011,12 @@ } 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(); @@ -13030,10 +13030,10 @@ throw new Error('Unknown prime ' + name); } primes[name] = prime; - + return prime; }; - + // // Base reduction engine // @@ -13048,106 +13048,106 @@ 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) @@ -13158,20 +13158,20 @@ 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); @@ -13183,16 +13183,16 @@ } 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) { @@ -13202,11 +13202,11 @@ 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); @@ -13214,7 +13214,7 @@ 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; @@ -13222,7 +13222,7 @@ 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--) { @@ -13230,99 +13230,99 @@ 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); @@ -13332,47 +13332,47 @@ } 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":55}],54:[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 @@ -13388,7 +13388,7 @@ self.msCrypto.getRandomValues(arr); return arr; }; - + // Safari's WebWorkers do not have `crypto` } else if (typeof window === 'object') { // Old junk @@ -13402,56 +13402,56 @@ 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":55}],55:[function(require,module,exports){ - + },{}],56:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js // https://code.google.com/p/crypto-js/ - + var Buffer = require('safe-buffer').Buffer - + function asUInt32Array (buf) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) - + var len = (buf.length / 4) | 0 var out = new Array(len) - + for (var i = 0; i < len; i++) { out[i] = buf.readUInt32BE(i * 4) } - + return out } - + function scrubVec (v) { for (var i = 0; i < v.length; v++) { v[i] = 0 } } - + function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { var SUB_MIX0 = SUB_MIX[0] var SUB_MIX1 = SUB_MIX[1] var SUB_MIX2 = SUB_MIX[2] var SUB_MIX3 = SUB_MIX[3] - + var s0 = M[0] ^ keySchedule[0] var s1 = M[1] ^ keySchedule[1] var s2 = M[2] ^ keySchedule[2] var s3 = M[3] ^ keySchedule[3] var t0, t1, t2, t3 var ksRow = 4 - + for (var round = 1; round < nRounds; round++) { t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] @@ -13462,7 +13462,7 @@ s2 = t2 s3 = t3 } - + t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] @@ -13471,10 +13471,10 @@ t1 = t1 >>> 0 t2 = t2 >>> 0 t3 = t3 >>> 0 - + return [t0, t1, t2, t3] } - + // AES constants var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] var G = (function () { @@ -13487,12 +13487,12 @@ d[j] = (j << 1) ^ 0x11b } } - + var SBOX = [] var INV_SBOX = [] var SUB_MIX = [[], [], [], []] var INV_SUB_MIX = [[], [], [], []] - + // Walk GF(2^8) var x = 0 var xi = 0 @@ -13502,26 +13502,26 @@ sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 SBOX[x] = sx INV_SBOX[sx] = x - + // Compute multiplication var x2 = d[x] var x4 = d[x2] var x8 = d[x4] - + // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100) SUB_MIX[0][x] = (t << 24) | (t >>> 8) SUB_MIX[1][x] = (t << 16) | (t >>> 16) SUB_MIX[2][x] = (t << 8) | (t >>> 24) SUB_MIX[3][x] = t - + // Compute inv sub bytes, inv mix columns tables t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) INV_SUB_MIX[3][sx] = t - + if (x === 0) { x = xi = 1 } else { @@ -13529,7 +13529,7 @@ xi ^= d[d[xi]] } } - + return { SBOX: SBOX, INV_SBOX: INV_SBOX, @@ -13537,12 +13537,12 @@ INV_SUB_MIX: INV_SUB_MIX } })() - + function AES (key) { this._key = asUInt32Array(key) this._reset() } - + AES.blockSize = 4 * 4 AES.keySize = 256 / 8 AES.prototype.blockSize = AES.blockSize @@ -13552,15 +13552,15 @@ var keySize = keyWords.length var nRounds = keySize + 6 var ksRows = (nRounds + 1) * 4 - + var keySchedule = [] for (var k = 0; k < keySize; k++) { keySchedule[k] = keyWords[k] } - + for (k = keySize; k < ksRows; k++) { var t = keySchedule[k - 1] - + if (k % keySize === 0) { t = (t << 8) | (t >>> 24) t = @@ -13568,7 +13568,7 @@ (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) - + t ^= RCON[(k / keySize) | 0] << 24 } else if (keySize > 6 && k % keySize === 4) { t = @@ -13577,15 +13577,15 @@ (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) } - + keySchedule[k] = keySchedule[k - keySize] ^ t } - + var invKeySchedule = [] for (var ik = 0; ik < ksRows; ik++) { var ksR = ksRows - ik var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] - + if (ik < 4 || ksR <= 4) { invKeySchedule[ik] = tt } else { @@ -13596,17 +13596,17 @@ G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] } } - + this._nRounds = nRounds this._keySchedule = keySchedule this._invKeySchedule = invKeySchedule } - + AES.prototype.encryptBlockRaw = function (M) { M = asUInt32Array(M) return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) } - + AES.prototype.encryptBlock = function (M) { var out = this.encryptBlockRaw(M) var buf = Buffer.allocUnsafe(16) @@ -13616,15 +13616,15 @@ buf.writeUInt32BE(out[3], 12) return buf } - + AES.prototype.decryptBlock = function (M) { M = asUInt32Array(M) - + // swap var m1 = M[1] M[1] = M[3] M[3] = m1 - + var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) @@ -13633,15 +13633,15 @@ buf.writeUInt32BE(out[1], 12) return buf } - + AES.prototype.scrub = function () { scrubVec(this._keySchedule) scrubVec(this._invKeySchedule) scrubVec(this._key) } - + module.exports.AES = AES - + },{"safe-buffer":290}],57:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer @@ -13650,19 +13650,19 @@ var GHASH = require('./ghash') var xor = require('buffer-xor') var incr32 = require('./incr32') - + function xorTest (a, b) { var out = 0 if (a.length !== b.length) out++ - + var len = Math.min(a.length, b.length) for (var i = 0; i < len; ++i) { out += (a[i] ^ b[i]) } - + return out } - + function calcIv (self, iv, ck) { if (iv.length === 12) { self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) @@ -13688,14 +13688,14 @@ } function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) - + var h = Buffer.alloc(4, 0) - + this._cipher = new aes.AES(key) var ck = this._cipher.encryptBlock(h) this._ghash = new GHASH(ck) iv = calcIv(this, iv, ck) - + this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) this._secCache = Buffer.allocUnsafe(0) @@ -13703,13 +13703,13 @@ this._alen = 0 this._len = 0 this._mode = mode - + this._authTag = null this._called = false } - + inherits(StreamCipher, Transform) - + StreamCipher.prototype._update = function (chunk) { if (!this._called && this._alen) { var rump = 16 - (this._alen % 16) @@ -13718,7 +13718,7 @@ this._ghash.update(rump) } } - + this._called = true var out = this._mode.encrypt(this, chunk) if (this._decrypt) { @@ -13729,53 +13729,53 @@ this._len += chunk.length return out } - + StreamCipher.prototype._final = function () { if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') - + var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') - + this._authTag = tag this._cipher.scrub() } - + StreamCipher.prototype.getAuthTag = function getAuthTag () { if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') - + return this._authTag } - + StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') - + this._authTag = tag } - + StreamCipher.prototype.setAAD = function setAAD (buf) { if (this._called) throw new Error('Attempting to set AAD in unsupported state') - + this._ghash.update(buf) this._alen += buf.length } - + module.exports = StreamCipher - + },{"./aes":56,"./ghash":61,"./incr32":62,"buffer-xor":83,"cipher-base":86,"inherits":180,"safe-buffer":290}],58:[function(require,module,exports){ var ciphers = require('./encrypter') var deciphers = require('./decrypter') var modes = require('./modes/list.json') - + function getCiphers () { return Object.keys(modes) } - + exports.createCipher = exports.Cipher = ciphers.createCipher exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers - + },{"./decrypter":59,"./encrypter":60,"./modes/list.json":70}],59:[function(require,module,exports){ var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer @@ -13785,10 +13785,10 @@ var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') - + function Decipher (mode, key, iv) { Transform.call(this) - + this._cache = new Splitter() this._last = void 0 this._cipher = new aes.AES(key) @@ -13796,9 +13796,9 @@ this._mode = mode this._autopadding = true } - + inherits(Decipher, Transform) - + Decipher.prototype._update = function (data) { this._cache.add(data) var chunk @@ -13810,7 +13810,7 @@ } return Buffer.concat(out) } - + Decipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { @@ -13819,20 +13819,20 @@ throw new Error('data not multiple of block length') } } - + Decipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } - + function Splitter () { this.cache = Buffer.allocUnsafe(0) } - + Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } - + Splitter.prototype.get = function (autoPadding) { var out if (autoPadding) { @@ -13848,14 +13848,14 @@ return out } } - + return null } - + Splitter.prototype.flush = function () { if (this.cache.length) return this.cache } - + function unpad (last) { var padded = last[15] var i = -1 @@ -13865,40 +13865,40 @@ } } if (padded === 16) return - + return last.slice(0, 16 - padded) } - + function createDecipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') - + if (typeof iv === 'string') iv = Buffer.from(iv) if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) - + if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) - + if (config.type === 'stream') { return new StreamCipher(config.module, password, iv, true) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv, true) } - + return new Decipher(config.module, password, iv) } - + function createDecipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') - + var keys = ebtk(password, false, config.key, config.iv) return createDecipheriv(suite, keys.key, keys.iv) } - + exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv - + },{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,"evp_bytestokey":158,"inherits":180,"safe-buffer":290}],60:[function(require,module,exports){ var MODES = require('./modes') var AuthCipher = require('./authCipher') @@ -13908,35 +13908,35 @@ var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') - + function Cipher (mode, key, iv) { Transform.call(this) - + this._cache = new Splitter() this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } - + inherits(Cipher, Transform) - + Cipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] - + while ((chunk = this._cache.get())) { thing = this._mode.encrypt(this, chunk) out.push(thing) } - + return Buffer.concat(out) } - + var PADDING = Buffer.alloc(16, 0x10) - + Cipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { @@ -13944,26 +13944,26 @@ this._cipher.scrub() return chunk } - + if (!chunk.equals(PADDING)) { this._cipher.scrub() throw new Error('data not multiple of block length') } } - + Cipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } - + function Splitter () { this.cache = Buffer.allocUnsafe(0) } - + Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } - + Splitter.prototype.get = function () { if (this.cache.length > 15) { var out = this.cache.slice(0, 16) @@ -13972,53 +13972,53 @@ } return null } - + Splitter.prototype.flush = function () { var len = 16 - this.cache.length var padBuff = Buffer.allocUnsafe(len) - + var i = -1 while (++i < len) { padBuff.writeUInt8(len, i) } - + return Buffer.concat([this.cache, padBuff]) } - + function createCipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') - + if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) - + if (typeof iv === 'string') iv = Buffer.from(iv) if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) - + if (config.type === 'stream') { return new StreamCipher(config.module, password, iv) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv) } - + return new Cipher(config.module, password, iv) } - + function createCipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') - + var keys = ebtk(password, false, config.key, config.iv) return createCipheriv(suite, keys.key, keys.iv) } - + exports.createCipheriv = createCipheriv exports.createCipher = createCipher - + },{"./aes":56,"./authCipher":57,"./modes":69,"./streamCipher":72,"cipher-base":86,"evp_bytestokey":158,"inherits":180,"safe-buffer":290}],61:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var ZEROES = Buffer.alloc(16, 0) - + function toArray (buf) { return [ buf.readUInt32BE(0), @@ -14027,7 +14027,7 @@ buf.readUInt32BE(12) ] } - + function fromArray (out) { var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0] >>> 0, 0) @@ -14036,13 +14036,13 @@ buf.writeUInt32BE(out[3] >>> 0, 12) return buf } - + function GHASH (key) { this.h = key this.state = Buffer.alloc(16, 0) this.cache = Buffer.allocUnsafe(0) } - + // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html // by Juho Vähä-Herttua GHASH.prototype.ghash = function (block) { @@ -14052,7 +14052,7 @@ } this._multiply() } - + GHASH.prototype._multiply = function () { var Vi = toArray(this.h) var Zi = [0, 0, 0, 0] @@ -14067,16 +14067,16 @@ Zi[2] ^= Vi[2] Zi[3] ^= Vi[3] } - + // Store the value of LSB(V_i) lsbVi = (Vi[3] & 1) !== 0 - + // V_i+1 = V_i >> 1 for (j = 3; j > 0; j--) { Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) } Vi[0] = Vi[0] >>> 1 - + // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R if (lsbVi) { Vi[0] = Vi[0] ^ (0xe1 << 24) @@ -14084,7 +14084,7 @@ } this.state = fromArray(Zi) } - + GHASH.prototype.update = function (buf) { this.cache = Buffer.concat([this.cache, buf]) var chunk @@ -14094,18 +14094,18 @@ this.ghash(chunk) } } - + GHASH.prototype.final = function (abl, bl) { if (this.cache.length) { this.ghash(Buffer.concat([this.cache, ZEROES], 16)) } - + this.ghash(fromArray([0, abl, 0, bl])) return this.state } - + module.exports = GHASH - + },{"safe-buffer":290}],62:[function(require,module,exports){ function incr32 (iv) { var len = iv.length @@ -14122,30 +14122,30 @@ } } module.exports = incr32 - + },{}],63:[function(require,module,exports){ var xor = require('buffer-xor') - + exports.encrypt = function (self, block) { var data = xor(block, self._prev) - + self._prev = self._cipher.encryptBlock(data) return self._prev } - + exports.decrypt = function (self, block) { var pad = self._prev - + self._prev = block var out = self._cipher.decryptBlock(block) - + return xor(out, pad) } - + },{"buffer-xor":83}],64:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var xor = require('buffer-xor') - + function encryptStart (self, data, decrypt) { var len = data.length var out = xor(data, self._cache) @@ -14153,17 +14153,17 @@ self._prev = Buffer.concat([self._prev, decrypt ? data : out]) return out } - + exports.encrypt = function (self, data, decrypt) { var out = Buffer.allocUnsafe(0) var len - + while (data.length) { if (self._cache.length === 0) { self._cache = self._cipher.encryptBlock(self._prev) self._prev = Buffer.allocUnsafe(0) } - + if (self._cache.length <= data.length) { len = self._cache.length out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) @@ -14173,13 +14173,13 @@ break } } - + return out } - + },{"buffer-xor":83,"safe-buffer":290}],65:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer - + function encryptByte (self, byteParam, decrypt) { var pad var i = -1 @@ -14195,70 +14195,70 @@ } return out } - + function shiftIn (buffer, value) { var len = buffer.length var i = -1 var out = Buffer.allocUnsafe(buffer.length) buffer = Buffer.concat([buffer, Buffer.from([value])]) - + while (++i < len) { out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) } - + return out } - + exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 - + while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } - + return out } - + },{"safe-buffer":290}],66:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer - + function encryptByte (self, byteParam, decrypt) { var pad = self._cipher.encryptBlock(self._prev) var out = pad[0] ^ byteParam - + self._prev = Buffer.concat([ self._prev.slice(1), Buffer.from([decrypt ? byteParam : out]) ]) - + return out } - + exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 - + while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } - + return out } - + },{"safe-buffer":290}],67:[function(require,module,exports){ var xor = require('buffer-xor') var Buffer = require('safe-buffer').Buffer var incr32 = require('../incr32') - + function getBlock (self) { var out = self._cipher.encryptBlockRaw(self._prev) incr32(self._prev) return out } - + var blockSize = 16 exports.encrypt = function (self, chunk) { var chunkNum = Math.ceil(chunk.length / blockSize) @@ -14279,16 +14279,16 @@ self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } - + },{"../incr32":62,"buffer-xor":83,"safe-buffer":290}],68:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } - + exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } - + },{}],69:[function(require,module,exports){ var modeModules = { ECB: require('./ecb'), @@ -14300,15 +14300,15 @@ CTR: require('./ctr'), GCM: require('./ctr') } - + var modes = require('./list.json') - + for (var key in modes) { modes[key].module = modeModules[modes[key].mode] } - + module.exports = modes - + },{"./cbc":63,"./cfb":64,"./cfb1":65,"./cfb8":66,"./ctr":67,"./ecb":68,"./list.json":70,"./ofb":71}],70:[function(require,module,exports){ module.exports={ "aes-128-ecb": { @@ -14501,36 +14501,36 @@ "type": "auth" } } - + },{}],71:[function(require,module,exports){ (function (Buffer){ var xor = require('buffer-xor') - + function getBlock (self) { self._prev = self._cipher.encryptBlock(self._prev) return self._prev } - + exports.encrypt = function (self, chunk) { while (self._cache.length < chunk.length) { self._cache = Buffer.concat([self._cache, getBlock(self)]) } - + var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } - + }).call(this,require("buffer").Buffer) },{"buffer":84,"buffer-xor":83}],72:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') var inherits = require('inherits') - + function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) - + this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) @@ -14538,19 +14538,19 @@ this._decrypt = decrypt this._mode = mode } - + inherits(StreamCipher, Transform) - + StreamCipher.prototype._update = function (chunk) { return this._mode.encrypt(this, chunk, this._decrypt) } - + StreamCipher.prototype._final = function () { this._cipher.scrub() } - + module.exports = StreamCipher - + },{"./aes":56,"cipher-base":86,"inherits":180,"safe-buffer":290}],73:[function(require,module,exports){ var ebtk = require('evp_bytestokey') var aes = require('browserify-aes/browser') @@ -14587,7 +14587,7 @@ var keys = ebtk(password, false, keyLen, ivLen) return createDecipheriv(suite, keys.key, keys.iv) } - + function createCipheriv (suite, key, iv) { suite = suite.toLowerCase() if (aesModes[suite]) { @@ -14625,13 +14625,13 @@ return Object.keys(desModes).concat(aes.getCiphers()) } exports.listCiphers = exports.getCiphers = getCiphers - + },{"browserify-aes/browser":58,"browserify-aes/modes":69,"browserify-des":74,"browserify-des/modes":75,"evp_bytestokey":158}],74:[function(require,module,exports){ (function (Buffer){ var CipherBase = require('cipher-base') var des = require('des.js') var inherits = require('inherits') - + var modes = { 'des-ede3-cbc': des.CBC.instantiate(des.EDE), 'des-ede3': des.EDE, @@ -14671,7 +14671,7 @@ DES.prototype._final = function () { return new Buffer(this._des.final()) } - + }).call(this,require("buffer").Buffer) },{"buffer":84,"cipher-base":86,"des.js":99,"inherits":180}],75:[function(require,module,exports){ exports['des-ecb'] = { @@ -14698,7 +14698,7 @@ key: 16, iv: 0 } - + },{}],76:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); @@ -14741,11 +14741,11 @@ } return r; } - + }).call(this,require("buffer").Buffer) },{"bn.js":53,"buffer":84,"randombytes":270}],77:[function(require,module,exports){ module.exports = require('./browser/algorithms.json') - + },{"./browser/algorithms.json":78}],78:[function(require,module,exports){ module.exports={ "sha224WithRSAEncryption": { @@ -14899,7 +14899,7 @@ "id": "3020300c06082a864886f70d020505000410" } } - + },{}],79:[function(require,module,exports){ module.exports={ "1.3.132.0.10": "secp256k1", @@ -14909,7 +14909,7 @@ "1.3.132.0.34": "p384", "1.3.132.0.35": "p521" } - + },{}],80:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash') @@ -14917,93 +14917,93 @@ var inherits = require('inherits') var sign = require('./sign') var verify = require('./verify') - + var algorithms = require('./algorithms.json') Object.keys(algorithms).forEach(function (key) { algorithms[key].id = new Buffer(algorithms[key].id, 'hex') algorithms[key.toLowerCase()] = algorithms[key] }) - + function Sign (algorithm) { stream.Writable.call(this) - + var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') - + this._hashType = data.hash this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Sign, stream.Writable) - + Sign.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } - + Sign.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) - + this._hash.update(data) return this } - + Sign.prototype.sign = function signMethod (key, enc) { this.end() var hash = this._hash.digest() var sig = sign(hash, key, this._hashType, this._signType, this._tag) - + return enc ? sig.toString(enc) : sig } - + function Verify (algorithm) { stream.Writable.call(this) - + var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') - + this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Verify, stream.Writable) - + Verify.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } - + Verify.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) - + this._hash.update(data) return this } - + Verify.prototype.verify = function verifyMethod (key, sig, enc) { if (typeof sig === 'string') sig = new Buffer(sig, enc) - + this.end() var hash = this._hash.digest() return verify(sig, hash, key, this._signType, this._tag) } - + function createSign (algorithm) { return new Sign(algorithm) } - + function createVerify (algorithm) { return new Verify(algorithm) } - + module.exports = { Sign: createSign, Verify: createVerify, createSign: createSign, createVerify: createVerify } - + }).call(this,require("buffer").Buffer) },{"./algorithms.json":78,"./sign":81,"./verify":82,"buffer":84,"create-hash":91,"inherits":180,"stream":311}],81:[function(require,module,exports){ (function (Buffer){ @@ -15014,7 +15014,7 @@ var BN = require('bn.js') var parseKeys = require('parse-asn1') var curves = require('./curves.json') - + function sign (hash, key, hashType, signType, tag) { var priv = parseKeys(key) if (priv.curve) { @@ -15034,22 +15034,22 @@ pad.push(0x00) var i = -1 while (++i < hash.length) pad.push(hash[i]) - + var out = crt(pad, priv) return out } - + function ecSign (hash, priv) { var curveId = curves[priv.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) - + var curve = new EC(curveId) var key = curve.keyFromPrivate(priv.privateKey) var out = key.sign(hash) - + return new Buffer(out.toDER()) } - + function dsaSign (hash, priv, algo) { var x = priv.params.priv_key var p = priv.params.p @@ -15071,21 +15071,21 @@ } return toDER(r, s) } - + function toDER (r, s) { r = r.toArray() s = s.toArray() - + // Pad values if (r[0] & 0x80) r = [ 0 ].concat(r) if (s[0] & 0x80) s = [ 0 ].concat(s) - + var total = r.length + s.length + 4 var res = [ 0x30, total, 0x02, r.length ] res = res.concat(r, [ 0x02, s.length ], s) return new Buffer(res) } - + function getKey (x, q, hash, algo) { x = new Buffer(x.toArray()) if (x.length < q.byteLength()) { @@ -15105,14 +15105,14 @@ v = createHmac(algo, k).update(v).digest() return { k: k, v: v } } - + function bits2int (obits, q) { var bits = new BN(obits) var shift = (obits.length << 3) - q.bitLength() if (shift > 0) bits.ishrn(shift) return bits } - + function bits2octets (bits, q) { bits = bits2int(bits, q) bits = bits.mod(q) @@ -15124,35 +15124,35 @@ } return out } - + function makeKey (q, kv, algo) { var t var k - + do { t = new Buffer(0) - + while (t.length * 8 < q.bitLength()) { kv.v = createHmac(algo, kv.k).update(kv.v).digest() t = Buffer.concat([ t, kv.v ]) } - + k = bits2int(t, q) kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() kv.v = createHmac(algo, kv.k).update(kv.v).digest() } while (k.cmp(q) !== -1) - + return k } - + function makeR (g, k, p, q) { return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) } - + module.exports = sign module.exports.getKey = getKey module.exports.makeKey = makeKey - + }).call(this,require("buffer").Buffer) },{"./curves.json":79,"bn.js":53,"browserify-rsa":76,"buffer":84,"create-hmac":94,"elliptic":109,"parse-asn1":245}],82:[function(require,module,exports){ (function (Buffer){ @@ -15161,7 +15161,7 @@ var EC = require('elliptic').ec var parseKeys = require('parse-asn1') var curves = require('./curves.json') - + function verify (sig, hash, key, signType, tag) { var pub = parseKeys(key) if (pub.type === 'ec') { @@ -15190,28 +15190,28 @@ pad = new Buffer(pad) var red = BN.mont(pub.modulus) sig = new BN(sig).toRed(red) - + sig = sig.redPow(new BN(pub.publicExponent)) sig = new Buffer(sig.fromRed().toArray()) var out = padNum < 8 ? 1 : 0 len = Math.min(sig.length, pad.length) if (sig.length !== pad.length) out = 1 - + i = -1 while (++i < len) out |= sig[i] ^ pad[i] return out === 0 } - + function ecVerify (sig, hash, pub) { var curveId = curves[pub.data.algorithm.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) - + var curve = new EC(curveId) var pubkey = pub.data.subjectPrivateKey.data - + return curve.verify(hash, sig, pubkey) } - + function dsaVerify (sig, hash, pub) { var p = pub.data.p var q = pub.data.q @@ -15232,28 +15232,28 @@ .mod(q) return v.cmp(r) === 0 } - + function checkValue (b, q) { if (b.cmpn(0) <= 0) throw new Error('invalid sig') if (b.cmp(q) >= q) throw new Error('invalid sig') } - + module.exports = verify - + }).call(this,require("buffer").Buffer) },{"./curves.json":79,"bn.js":53,"buffer":84,"elliptic":109,"parse-asn1":245}],83:[function(require,module,exports){ (function (Buffer){ module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) var buffer = new Buffer(length) - + for (var i = 0; i < length; ++i) { buffer[i] = a[i] ^ b[i] } - + return buffer } - + }).call(this,require("buffer").Buffer) },{"buffer":84}],84:[function(require,module,exports){ /*! @@ -15263,19 +15263,19 @@ * @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) @@ -15291,7 +15291,7 @@ * 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( @@ -15299,7 +15299,7 @@ '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' ) } - + function typedArraySupport () { // Can typed array instances can be augmented? try { @@ -15310,7 +15310,7 @@ return false } } - + function createBuffer (length) { if (length > K_MAX_LENGTH) { throw new RangeError('Invalid typed array length') @@ -15320,7 +15320,7 @@ 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 @@ -15330,7 +15330,7 @@ * * The `Uint8Array` prototype remains unmodified. */ - + function Buffer (arg, encodingOrOffset, length) { // Common case. if (typeof arg === 'number') { @@ -15343,7 +15343,7 @@ } return from(arg, encodingOrOffset, length) } - + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { @@ -15354,25 +15354,25 @@ writable: false }) } - + Buffer.poolSize = 8192 // not used by this implementation - + function from (value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } - + if (isArrayBuffer(value)) { return fromArrayBuffer(value, encodingOrOffset, length) } - + if (typeof value === 'string') { return fromString(value, encodingOrOffset) } - + return fromObject(value) } - + /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. @@ -15384,12 +15384,12 @@ 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 a number') @@ -15397,7 +15397,7 @@ throw new RangeError('"size" argument must not be negative') } } - + function alloc (size, fill, encoding) { assertSize(size) if (size <= 0) { @@ -15413,7 +15413,7 @@ } return createBuffer(size) } - + /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) @@ -15421,12 +15421,12 @@ 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. * */ @@ -15439,31 +15439,31 @@ 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('"encoding" must be a valid string 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) @@ -15472,16 +15472,16 @@ } return buf } - + function fromArrayBuffer (array, byteOffset, length) { if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } - + if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } - + var buf if (byteOffset === undefined && length === undefined) { buf = new Uint8Array(array) @@ -15490,25 +15490,25 @@ } 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) { if (isArrayBufferView(obj) || 'length' in obj) { if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { @@ -15516,15 +15516,15 @@ } return fromArrayLike(obj) } - + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { return fromArrayLike(obj.data) } } - + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } - + function checked (length) { // Note: cannot use `length < K_MAX_LENGTH` here because that fails when // length is NaN (which is otherwise coerced to zero.) @@ -15534,28 +15534,28 @@ } 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 } - + Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } - + 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] @@ -15563,12 +15563,12 @@ break } } - + if (x < y) return -1 if (y < x) return 1 return 0 } - + Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': @@ -15587,16 +15587,16 @@ 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 @@ -15604,7 +15604,7 @@ length += list[i].length } } - + var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { @@ -15617,7 +15617,7 @@ } return buffer } - + function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length @@ -15628,10 +15628,10 @@ if (typeof string !== 'string') { string = '' + string } - + var len = string.length if (len === 0) return 0 - + // Use a for loop to avoid recursion var loweredCase = false for (;;) { @@ -15661,13 +15661,13 @@ } } 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, @@ -15680,50 +15680,50 @@ 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() @@ -15731,7 +15731,7 @@ } } } - + // 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 @@ -15739,13 +15739,13 @@ // 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) { @@ -15756,7 +15756,7 @@ } return this } - + Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { @@ -15768,7 +15768,7 @@ } return this } - + Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { @@ -15782,20 +15782,20 @@ } 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.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 @@ -15805,12 +15805,12 @@ } return '' } - + Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } - + if (start === undefined) { start = 0 } @@ -15823,11 +15823,11 @@ 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 } @@ -15837,21 +15837,21 @@ 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] @@ -15859,12 +15859,12 @@ 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`. // @@ -15877,7 +15877,7 @@ 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 @@ -15892,7 +15892,7 @@ // 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) { @@ -15902,12 +15902,12 @@ 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 @@ -15926,15 +15926,15 @@ } 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' || @@ -15948,7 +15948,7 @@ byteOffset /= 2 } } - + function read (buf, i) { if (indexSize === 1) { return buf[i] @@ -15956,7 +15956,7 @@ return buf.readUInt16BE(i * indexSize) } } - + var i if (dir) { var foundIndex = -1 @@ -15982,22 +15982,22 @@ 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 @@ -16009,11 +16009,11 @@ length = remaining } } - + // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') - + if (length > strLen / 2) { length = strLen / 2 } @@ -16024,27 +16024,27 @@ } 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) { @@ -16071,43 +16071,43 @@ '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() @@ -16115,14 +16115,14 @@ } } } - + 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) @@ -16130,11 +16130,11 @@ 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] @@ -16143,10 +16143,10 @@ : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 - + if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint - + switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { @@ -16184,7 +16184,7 @@ } } } - + if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte @@ -16196,25 +16196,25 @@ 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 @@ -16226,40 +16226,40 @@ } 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 = '' @@ -16268,34 +16268,34 @@ } 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. */ @@ -16303,81 +16303,81 @@ 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 @@ -16385,17 +16385,17 @@ 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] @@ -16403,83 +16403,83 @@ 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 @@ -16488,17 +16488,17 @@ 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 @@ -16507,17 +16507,17 @@ 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 @@ -16525,7 +16525,7 @@ this[offset] = (value & 0xff) return offset + 1 } - + Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16534,7 +16534,7 @@ this[offset + 1] = (value >>> 8) return offset + 2 } - + Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16543,7 +16543,7 @@ this[offset + 1] = (value & 0xff) return offset + 2 } - + Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16554,7 +16554,7 @@ this[offset] = (value & 0xff) return offset + 4 } - + Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16565,16 +16565,16 @@ 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 @@ -16585,19 +16585,19 @@ } 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 @@ -16608,10 +16608,10 @@ } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } - + return offset + byteLength } - + Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16620,7 +16620,7 @@ this[offset] = (value & 0xff) return offset + 1 } - + Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16629,7 +16629,7 @@ this[offset + 1] = (value >>> 8) return offset + 2 } - + Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16638,7 +16638,7 @@ this[offset + 1] = (value & 0xff) return offset + 2 } - + Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16649,7 +16649,7 @@ this[offset + 3] = (value >>> 24) return offset + 4 } - + Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset >>> 0 @@ -16661,12 +16661,12 @@ 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 @@ -16676,15 +16676,15 @@ 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 @@ -16694,15 +16694,15 @@ 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 (!start) start = 0 @@ -16710,27 +16710,27 @@ 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('sourceStart out of bounds') 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 var i - + if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { @@ -16748,10 +16748,10 @@ targetStart ) } - + return len } - + // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) @@ -16782,21 +16782,21 @@ } 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) { @@ -16811,15 +16811,15 @@ this[i + start] = bytes[i % len] } } - + return this } - + // HELPER FUNCTIONS // ================ - + var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g - + function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = str.trim().replace(INVALID_BASE64_RE, '') @@ -16831,22 +16831,22 @@ } 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 @@ -16861,29 +16861,29 @@ 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 @@ -16913,10 +16913,10 @@ throw new Error('Invalid code point') } } - + return bytes } - + function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { @@ -16925,27 +16925,27 @@ } 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 @@ -16953,7 +16953,7 @@ } return i } - + // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 function isArrayBuffer (obj) { @@ -16961,16 +16961,16 @@ (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && typeof obj.byteLength === 'number') } - + // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` function isArrayBufferView (obj) { return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) } - + function numberIsNaN (obj) { return obj !== obj // eslint-disable-line no-self-compare } - + },{"base64-js":51,"ieee754":178}],85:[function(require,module,exports){ module.exports = { "100": "Continue", @@ -17036,13 +17036,13 @@ "510": "Not Extended", "511": "Network Authentication Required" } - + },{}],86:[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' @@ -17059,35 +17059,35 @@ 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 { @@ -17109,7 +17109,7 @@ } catch (e) { err = e } - + done(err) } CipherBase.prototype._finalOrDigest = function (outputEnc) { @@ -17119,34 +17119,34 @@ } 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":180,"safe-buffer":290,"stream":311,"string_decoder":317}],87:[function(require,module,exports){ (function (Buffer){ var clone = (function() { 'use strict'; - + function _instanceof(obj, type) { return type != null && obj instanceof type; } - + var nativeMap; try { nativeMap = Map; @@ -17155,21 +17155,21 @@ // value will ever be an instanceof. nativeMap = function() {}; } - + var nativeSet; try { nativeSet = Set; } catch(_) { nativeSet = function() {}; } - + var nativePromise; try { nativePromise = Promise; } catch(_) { nativePromise = function() {}; } - + /** * Clones (copies) an Object using deep copying. * @@ -17202,30 +17202,30 @@ // and children have the same index var allParents = []; var allChildren = []; - + var useBuffer = typeof Buffer != 'undefined'; - + if (typeof circular == 'undefined') circular = true; - + if (typeof depth == 'undefined') depth = Infinity; - + // recurse this function so we don't reset allParents and allChildren function _clone(parent, depth) { // cloning null always returns null if (parent === null) return null; - + if (depth === 0) return parent; - + var child; var proto; if (typeof parent != 'object') { return parent; } - + if (_instanceof(parent, nativeMap)) { child = new nativeMap(); } else if (_instanceof(parent, nativeSet)) { @@ -17267,17 +17267,17 @@ proto = prototype; } } - + if (circular) { var index = allParents.indexOf(parent); - + if (index != -1) { return allChildren[index]; } allParents.push(parent); allChildren.push(child); } - + if (_instanceof(parent, nativeMap)) { parent.forEach(function(value, key) { var keyChild = _clone(key, depth - 1); @@ -17291,19 +17291,19 @@ child.add(entryChild); }); } - + for (var i in parent) { var attrs; if (proto) { attrs = Object.getOwnPropertyDescriptor(proto, i); } - + if (attrs && attrs.set == null) { continue; } child[i] = _clone(parent[i], depth - 1); } - + if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(parent); for (var i = 0; i < symbols.length; i++) { @@ -17322,7 +17322,7 @@ } } } - + if (includeNonEnumerable) { var allPropertyNames = Object.getOwnPropertyNames(parent); for (var i = 0; i < allPropertyNames.length; i++) { @@ -17337,13 +17337,13 @@ }); } } - + return child; } - + return _clone(parent, depth); } - + /** * Simple flat clone using prototype, accepts only objects, usefull for property * override on FLAT configuration object (no nested props). @@ -17354,34 +17354,34 @@ clone.clonePrototype = function clonePrototype(parent) { if (parent === null) return null; - + var c = function () {}; c.prototype = parent; return new c(); }; - + // private utility functions - + function __objToStr(o) { return Object.prototype.toString.call(o); } clone.__objToStr = __objToStr; - + function __isDate(o) { return typeof o === 'object' && __objToStr(o) === '[object Date]'; } clone.__isDate = __isDate; - + function __isArray(o) { return typeof o === 'object' && __objToStr(o) === '[object Array]'; } clone.__isArray = __isArray; - + function __isRegExp(o) { return typeof o === 'object' && __objToStr(o) === '[object RegExp]'; } clone.__isRegExp = __isRegExp; - + function __getRegExpFlags(re) { var flags = ''; if (re.global) flags += 'g'; @@ -17390,20 +17390,20 @@ return flags; } clone.__getRegExpFlags = __getRegExpFlags; - + return clone; })(); - + if (typeof module === 'object' && module.exports) { module.exports = clone; } - + }).call(this,require("buffer").Buffer) },{"buffer":84}],88:[function(require,module,exports){ /* jshint node: true */ (function () { "use strict"; - + function CookieAccessInfo(domain, path, secure, script) { if (this instanceof CookieAccessInfo) { this.domain = domain || undefined; @@ -17416,7 +17416,7 @@ } CookieAccessInfo.All = Object.freeze(Object.create(null)); exports.CookieAccessInfo = CookieAccessInfo; - + function Cookie(cookiestr, request_domain, request_path) { if (cookiestr instanceof Cookie) { return cookiestr; @@ -17439,7 +17439,7 @@ return new Cookie(cookiestr, request_domain, request_path); } exports.Cookie = Cookie; - + Cookie.prototype.toString = function toString() { var str = [this.name + "=" + this.value]; if (this.expiration_date !== Infinity) { @@ -17459,11 +17459,11 @@ } return str.join("; "); }; - + Cookie.prototype.toValueString = function toValueString() { return this.name + "=" + this.value; }; - + var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; Cookie.prototype.parse = function parse(str, request_domain, request_path) { if (this instanceof Cookie) { @@ -17471,23 +17471,23 @@ return !!value; }); var i; - + var pair = parts[0].match(/([^=]+)=([\s\S]*)/); if (!pair) { console.warn("Invalid cookie header encountered. Header: '"+str+"'"); return; } - + var key = pair[1]; var value = pair[2]; if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); return; } - + this.name = key; this.value = value; - + for (i = 1; i < parts.length; i += 1) { pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); key = pair[1].trim().toLowerCase(); @@ -17518,19 +17518,19 @@ break; } } - + if (!this.explicit_path) { this.path = request_path || "/"; } if (!this.explicit_domain) { this.domain = request_domain; } - + return this; } return new Cookie().parse(str, request_domain, request_path); }; - + Cookie.prototype.matches = function matches(access_info) { if (access_info === CookieAccessInfo.All) { return true; @@ -17542,7 +17542,7 @@ } return true; }; - + Cookie.prototype.collidesWith = function collidesWith(access_info) { if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { return false; @@ -17570,12 +17570,12 @@ } return true; }; - + function CookieJar() { var cookies, cookies_list, collidable_cookie; if (this instanceof CookieJar) { cookies = Object.create(null); //name: [Cookie] - + this.setCookie = function setCookie(cookie, request_domain, request_path) { var remove, i; cookie = new Cookie(cookie, request_domain, request_path); @@ -17624,7 +17624,7 @@ } continue; } - + if (cookie.matches(access_info)) { return cookie; } @@ -17649,13 +17649,13 @@ }; return matches; }; - + return this; } return new CookieJar(); } exports.CookieJar = CookieJar; - + //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { cookies = Array.isArray(cookies) ? @@ -17676,7 +17676,7 @@ return successful; }; }()); - + },{}],89:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. @@ -17699,10 +17699,10 @@ // 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); @@ -17710,67 +17710,67 @@ 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' || @@ -17780,23 +17780,23 @@ 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":181}],90:[function(require,module,exports){ (function (Buffer){ var elliptic = require('elliptic'); var BN = require('bn.js'); - + module.exports = function createECDH(curve) { return new ECDH(curve); }; - + var aliases = { secp256k1: { name: 'secp256k1', @@ -17827,13 +17827,13 @@ byteLength: 66 } }; - + aliases.p224 = aliases.secp224r1; aliases.p256 = aliases.secp256r1 = aliases.prime256v1; aliases.p192 = aliases.secp192r1 = aliases.prime192v1; aliases.p384 = aliases.secp384r1; aliases.p521 = aliases.secp521r1; - + function ECDH(curve) { this.curveType = aliases[curve]; if (!this.curveType ) { @@ -17844,12 +17844,12 @@ this.curve = new elliptic.ec(this.curveType.name); this.keys = void 0; } - + ECDH.prototype.generateKeys = function (enc, format) { this.keys = this.curve.genKeyPair(); return this.getPublicKey(enc, format); }; - + ECDH.prototype.computeSecret = function (other, inenc, enc) { inenc = inenc || 'utf8'; if (!Buffer.isBuffer(other)) { @@ -17859,7 +17859,7 @@ var out = otherPub.mul(this.keys.getPrivate()).getX(); return formatReturnValue(out, enc, this.curveType.byteLength); }; - + ECDH.prototype.getPublicKey = function (enc, format) { var key = this.keys.getPublic(format === 'compressed', true); if (format === 'hybrid') { @@ -17871,11 +17871,11 @@ } return formatReturnValue(key, enc); }; - + ECDH.prototype.getPrivateKey = function (enc) { return formatReturnValue(this.keys.getPrivate(), enc); }; - + ECDH.prototype.setPublicKey = function (pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { @@ -17884,7 +17884,7 @@ this.keys._importPublic(pub); return this; }; - + ECDH.prototype.setPrivateKey = function (priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { @@ -17895,7 +17895,7 @@ this.keys._importPrivate(_priv); return this; }; - + function formatReturnValue(bn, enc, len) { if (!Array.isArray(bn)) { bn = bn.toArray(); @@ -17912,7 +17912,7 @@ return buf.toString(enc); } } - + }).call(this,require("buffer").Buffer) },{"bn.js":53,"buffer":84,"elliptic":109}],91:[function(require,module,exports){ (function (Buffer){ @@ -17921,54 +17921,54 @@ var md5 = require('./md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') - + var Base = require('cipher-base') - + function HashNoConstructor (hash) { Base.call(this, 'digest') - + this._hash = hash this.buffers = [] } - + inherits(HashNoConstructor, Base) - + HashNoConstructor.prototype._update = function (data) { this.buffers.push(data) } - + HashNoConstructor.prototype._final = function () { var buf = Buffer.concat(this.buffers) var r = this._hash(buf) this.buffers = null - + return r } - + 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 HashNoConstructor(md5) if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160()) - + return new Hash(sha(alg)) } - + }).call(this,require("buffer").Buffer) },{"./md5":93,"buffer":84,"cipher-base":86,"inherits":180,"ripemd160":288,"sha.js":304}],92:[function(require,module,exports){ (function (Buffer){ @@ -17976,24 +17976,24 @@ var intSize = 4 var zeroBuffer = new Buffer(intSize) zeroBuffer.fill(0) - + var charSize = 8 var hashSize = 16 - + function toArray (buf) { if ((buf.length % intSize) !== 0) { var len = buf.length + (intSize - (buf.length % intSize)) buf = Buffer.concat([buf, zeroBuffer], len) } - + var arr = new Array(buf.length >>> 2) for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { arr[j] = buf.readInt32LE(i) } - + return arr } - + module.exports = function hash (buf, fn) { var arr = fn(toArray(buf), buf.length * charSize) buf = new Buffer(hashSize) @@ -18002,7 +18002,7 @@ } return buf } - + }).call(this,require("buffer").Buffer) },{"buffer":84}],93:[function(require,module,exports){ 'use strict' @@ -18014,9 +18014,9 @@ * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ - + var makeHash = require('./make-hash') - + /* * Calculate the MD5 of an array of little-endian words, and a bit length */ @@ -18024,18 +18024,18 @@ /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32) x[(((len + 64) >>> 9) << 4) + 14] = len - + var a = 1732584193 var b = -271733879 var c = -1732584194 var d = 271733878 - + for (var i = 0; i < x.length; i += 16) { var olda = a var oldb = b var oldc = c var oldd = d - + a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) @@ -18052,7 +18052,7 @@ d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) - + a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) @@ -18069,7 +18069,7 @@ d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) - + a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) @@ -18086,7 +18086,7 @@ d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) - + a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) @@ -18103,39 +18103,39 @@ d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) - + a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } - + return [a, b, c, d] } - + /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } - + function md5_ff (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) } - + function md5_gg (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) } - + function md5_hh (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t) } - + function md5_ii (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) } - + /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. @@ -18145,18 +18145,18 @@ var msw = (x >> 16) + (y >> 16) + (lsw >> 16) return (msw << 16) | (lsw & 0xFFFF) } - + /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } - + module.exports = function md5 (buf) { return makeHash(buf, core_md5) } - + },{"./make-hash":92}],94:[function(require,module,exports){ 'use strict' var inherits = require('inherits') @@ -18165,19 +18165,19 @@ 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) { @@ -18186,10 +18186,10 @@ } 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 @@ -18197,19 +18197,19 @@ 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') { @@ -18220,55 +18220,55 @@ } return new Hmac(alg, key) } - + },{"./legacy":95,"cipher-base":86,"create-hash/md5":93,"inherits":180,"ripemd160":288,"safe-buffer":290,"sha.js":304}],95:[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":86,"inherits":180,"safe-buffer":290}],96:[function(require,module,exports){ var __root__ = (function (root) { function F() { this.fetch = false; } @@ -18276,13 +18276,13 @@ return new F(); })(typeof self !== 'undefined' ? self : this); (function(self) { - + (function(self) { - + if (self.fetch) { return } - + var support = { searchParams: 'URLSearchParams' in self, iterable: 'Symbol' in self && 'iterator' in Symbol, @@ -18297,7 +18297,7 @@ formData: 'FormData' in self, arrayBuffer: 'ArrayBuffer' in self }; - + if (support.arrayBuffer) { var viewClasses = [ '[object Int8Array]', @@ -18310,16 +18310,16 @@ '[object Float32Array]', '[object Float64Array]' ]; - + var isDataView = function(obj) { return obj && DataView.prototype.isPrototypeOf(obj) }; - + var isArrayBufferView = ArrayBuffer.isView || function(obj) { return obj && viewClasses.indexOf(Object.prototype.toString.call(obj)) > -1 }; } - + function normalizeName(name) { if (typeof name !== 'string') { name = String(name); @@ -18329,14 +18329,14 @@ } return name.toLowerCase() } - + function normalizeValue(value) { if (typeof value !== 'string') { value = String(value); } return value } - + // Build a destructive iterator for the value list function iteratorFor(items) { var iterator = { @@ -18345,19 +18345,19 @@ return {done: value === undefined, value: value} } }; - + if (support.iterable) { iterator[Symbol.iterator] = function() { return iterator }; } - + return iterator } - + function Headers(headers) { this.map = {}; - + if (headers instanceof Headers) { headers.forEach(function(value, name) { this.append(name, value); @@ -18372,31 +18372,31 @@ }, this); } } - + Headers.prototype.append = function(name, value) { name = normalizeName(name); value = normalizeValue(value); var oldValue = this.map[name]; this.map[name] = oldValue ? oldValue+','+value : value; }; - + Headers.prototype['delete'] = function(name) { delete this.map[normalizeName(name)]; }; - + Headers.prototype.get = function(name) { name = normalizeName(name); return this.has(name) ? this.map[name] : null }; - + Headers.prototype.has = function(name) { return this.map.hasOwnProperty(normalizeName(name)) }; - + Headers.prototype.set = function(name, value) { this.map[normalizeName(name)] = normalizeValue(value); }; - + Headers.prototype.forEach = function(callback, thisArg) { for (var name in this.map) { if (this.map.hasOwnProperty(name)) { @@ -18404,36 +18404,36 @@ } } }; - + Headers.prototype.keys = function() { var items = []; this.forEach(function(value, name) { items.push(name); }); return iteratorFor(items) }; - + Headers.prototype.values = function() { var items = []; this.forEach(function(value) { items.push(value); }); return iteratorFor(items) }; - + Headers.prototype.entries = function() { var items = []; this.forEach(function(value, name) { items.push([name, value]); }); return iteratorFor(items) }; - + if (support.iterable) { Headers.prototype[Symbol.iterator] = Headers.prototype.entries; } - + function consumed(body) { if (body.bodyUsed) { return Promise.reject(new TypeError('Already read')) } body.bodyUsed = true; } - + function fileReaderReady(reader) { return new Promise(function(resolve, reject) { reader.onload = function() { @@ -18444,31 +18444,31 @@ }; }) } - + function readBlobAsArrayBuffer(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsArrayBuffer(blob); return promise } - + function readBlobAsText(blob) { var reader = new FileReader(); var promise = fileReaderReady(reader); reader.readAsText(blob); return promise } - + function readArrayBufferAsText(buf) { var view = new Uint8Array(buf); var chars = new Array(view.length); - + for (var i = 0; i < view.length; i++) { chars[i] = String.fromCharCode(view[i]); } return chars.join('') } - + function bufferClone(buf) { if (buf.slice) { return buf.slice(0) @@ -18478,10 +18478,10 @@ return view.buffer } } - + function Body() { this.bodyUsed = false; - + this._initBody = function(body) { this._bodyInit = body; if (!body) { @@ -18503,7 +18503,7 @@ } else { throw new Error('unsupported BodyInit type') } - + if (!this.headers.get('content-type')) { if (typeof body === 'string') { this.headers.set('content-type', 'text/plain;charset=UTF-8'); @@ -18514,14 +18514,14 @@ } } }; - + if (support.blob) { this.blob = function() { var rejected = consumed(this); if (rejected) { return rejected } - + if (this._bodyBlob) { return Promise.resolve(this._bodyBlob) } else if (this._bodyArrayBuffer) { @@ -18532,7 +18532,7 @@ return Promise.resolve(new Blob([this._bodyText])) } }; - + this.arrayBuffer = function() { if (this._bodyArrayBuffer) { return consumed(this) || Promise.resolve(this._bodyArrayBuffer) @@ -18541,13 +18541,13 @@ } }; } - + this.text = function() { var rejected = consumed(this); if (rejected) { return rejected } - + if (this._bodyBlob) { return readBlobAsText(this._bodyBlob) } else if (this._bodyArrayBuffer) { @@ -18558,32 +18558,32 @@ return Promise.resolve(this._bodyText) } }; - + if (support.formData) { this.formData = function() { return this.text().then(decode) }; } - + this.json = function() { return this.text().then(JSON.parse) }; - + return this } - + // HTTP methods whose capitalization should be normalized var methods = ['DELETE', 'GET', 'HEAD', 'OPTIONS', 'POST', 'PUT']; - + function normalizeMethod(method) { var upcased = method.toUpperCase(); return (methods.indexOf(upcased) > -1) ? upcased : method } - + function Request(input, options) { options = options || {}; var body = options.body; - + if (input instanceof Request) { if (input.bodyUsed) { throw new TypeError('Already read') @@ -18602,7 +18602,7 @@ } else { this.url = String(input); } - + this.credentials = options.credentials || this.credentials || 'omit'; if (options.headers || !this.headers) { this.headers = new Headers(options.headers); @@ -18610,17 +18610,17 @@ this.method = normalizeMethod(options.method || this.method || 'GET'); this.mode = options.mode || this.mode || null; this.referrer = null; - + if ((this.method === 'GET' || this.method === 'HEAD') && body) { throw new TypeError('Body not allowed for GET or HEAD requests') } this._initBody(body); } - + Request.prototype.clone = function() { return new Request(this, { body: this._bodyInit }) }; - + function decode(body) { var form = new FormData(); body.trim().split('&').forEach(function(bytes) { @@ -18633,7 +18633,7 @@ }); return form } - + function parseHeaders(rawHeaders) { var headers = new Headers(); // Replace instances of \r\n and \n followed by at least one space or horizontal tab with a space @@ -18649,14 +18649,14 @@ }); return headers } - + Body.call(Request.prototype); - + function Response(bodyInit, options) { if (!options) { options = {}; } - + this.type = 'default'; this.status = options.status === undefined ? 200 : options.status; this.ok = this.status >= 200 && this.status < 300; @@ -18665,9 +18665,9 @@ this.url = options.url || ''; this._initBody(bodyInit); } - + Body.call(Response.prototype); - + Response.prototype.clone = function() { return new Response(this._bodyInit, { status: this.status, @@ -18676,32 +18676,32 @@ url: this.url }) }; - + Response.error = function() { var response = new Response(null, {status: 0, statusText: ''}); response.type = 'error'; return response }; - + var redirectStatuses = [301, 302, 303, 307, 308]; - + Response.redirect = function(url, status) { if (redirectStatuses.indexOf(status) === -1) { throw new RangeError('Invalid status code') } - + return new Response(null, {status: status, headers: {location: url}}) }; - + self.Headers = Headers; self.Request = Request; self.Response = Response; - + self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init); var xhr = new XMLHttpRequest(); - + xhr.onload = function() { var options = { status: xhr.status, @@ -18712,31 +18712,31 @@ var body = 'response' in xhr ? xhr.response : xhr.responseText; resolve(new Response(body, options)); }; - + xhr.onerror = function() { reject(new TypeError('Network request failed')); }; - + xhr.ontimeout = function() { reject(new TypeError('Network request failed')); }; - + xhr.open(request.method, request.url, true); - + if (request.credentials === 'include') { xhr.withCredentials = true; } else if (request.credentials === 'omit') { xhr.withCredentials = false; } - + if ('responseType' in xhr && support.blob) { xhr.responseType = 'blob'; } - + request.headers.forEach(function(value, name) { xhr.setRequestHeader(name, value); }); - + xhr.send(typeof request._bodyInit === 'undefined' ? null : request._bodyInit); }) }; @@ -18752,27 +18752,27 @@ // Needed for TypeScript consumers without esModuleInterop. module.exports.default = fetch; } - + },{}],97:[function(require,module,exports){ 'use strict' - + exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') exports.createHash = exports.Hash = require('create-hash') exports.createHmac = exports.Hmac = require('create-hmac') - + var algos = require('browserify-sign/algos') var algoKeys = Object.keys(algos) var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) exports.getHashes = function () { return hashes } - + var p = require('pbkdf2') exports.pbkdf2 = p.pbkdf2 exports.pbkdf2Sync = p.pbkdf2Sync - + var aes = require('browserify-cipher') - + exports.Cipher = aes.Cipher exports.createCipher = aes.createCipher exports.Cipheriv = aes.Cipheriv @@ -18783,31 +18783,31 @@ exports.createDecipheriv = aes.createDecipheriv exports.getCiphers = aes.getCiphers exports.listCiphers = aes.listCiphers - + var dh = require('diffie-hellman') - + exports.DiffieHellmanGroup = dh.DiffieHellmanGroup exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup exports.getDiffieHellman = dh.getDiffieHellman exports.createDiffieHellman = dh.createDiffieHellman exports.DiffieHellman = dh.DiffieHellman - + var sign = require('browserify-sign') - + exports.createSign = sign.createSign exports.Sign = sign.Sign exports.createVerify = sign.createVerify exports.Verify = sign.Verify - + exports.createECDH = require('create-ecdh') - + var publicEncrypt = require('public-encrypt') - + exports.publicEncrypt = publicEncrypt.publicEncrypt exports.privateEncrypt = publicEncrypt.privateEncrypt exports.publicDecrypt = publicEncrypt.publicDecrypt exports.privateDecrypt = publicEncrypt.privateDecrypt - + // the least I can do is make error messages for the rest of the node.js/crypto api. // ;[ // 'createCredentials' @@ -18820,12 +18820,12 @@ // ].join('\n')) // } // }) - + var rf = require('randomfill') - + exports.randomFill = rf.randomFill exports.randomFillSync = rf.randomFillSync - + exports.createCredentials = function () { throw new Error([ 'sorry, createCredentials is not implemented yet', @@ -18833,7 +18833,7 @@ 'https://github.com/crypto-browserify/crypto-browserify' ].join('\n')) } - + exports.constants = { 'DH_CHECK_P_NOT_SAFE_PRIME': 2, 'DH_CHECK_P_NOT_PRIME': 1, @@ -18851,13 +18851,13 @@ 'POINT_CONVERSION_UNCOMPRESSED': 4, 'POINT_CONVERSION_HYBRID': 6 } - + },{"browserify-cipher":73,"browserify-sign":80,"browserify-sign/algos":77,"create-ecdh":90,"create-hash":91,"create-hmac":94,"diffie-hellman":105,"pbkdf2":247,"public-encrypt":259,"randombytes":270,"randomfill":271}],98:[function(require,module,exports){ 'use strict'; var token = '%[a-f0-9]{2}'; var singleMatcher = new RegExp(token, 'gi'); var multiMatcher = new RegExp('(' + token + ')+', 'gi'); - + function decodeComponents(components, split) { try { // Try to decode the entire string first @@ -18865,43 +18865,43 @@ } catch (err) { // Do nothing } - + if (components.length === 1) { return components; } - + split = split || 1; - + // Split the array in 2 parts var left = components.slice(0, split); var right = components.slice(split); - + return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right)); } - + function decode(input) { try { return decodeURIComponent(input); } catch (err) { var tokens = input.match(singleMatcher); - + for (var i = 1; i < tokens.length; i++) { input = decodeComponents(tokens, i).join(''); - + tokens = input.match(singleMatcher); } - + return input; } } - + function customDecodeURIComponent(input) { // Keep track of all the replacements and prefill the map with the `BOM` var replaceMap = { '%FE%FF': '\uFFFD\uFFFD', '%FF%FE': '\uFFFD\uFFFD' }; - + var match = multiMatcher.exec(input); while (match) { try { @@ -18909,37 +18909,37 @@ replaceMap[match[0]] = decodeURIComponent(match[0]); } catch (err) { var result = decode(match[0]); - + if (result !== match[0]) { replaceMap[match[0]] = result; } } - + match = multiMatcher.exec(input); } - + // Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else replaceMap['%C2'] = '\uFFFD'; - + var entries = Object.keys(replaceMap); - + for (var i = 0; i < entries.length; i++) { // Replace all decoded components var key = entries[i]; input = input.replace(new RegExp(key, 'g'), replaceMap[key]); } - + return input; } - + module.exports = function (encodedURI) { if (typeof encodedURI !== 'string') { throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`'); } - + try { encodedURI = encodedURI.replace(/\+/g, ' '); - + // Try the built in decoder first return decodeURIComponent(encodedURI); } catch (err) { @@ -18947,269 +18947,269 @@ return customDecodeURIComponent(encodedURI); } }; - + },{}],99:[function(require,module,exports){ 'use strict'; - + exports.utils = require('./des/utils'); exports.Cipher = require('./des/cipher'); exports.DES = require('./des/des'); exports.CBC = require('./des/cbc'); exports.EDE = require('./des/ede'); - + },{"./des/cbc":100,"./des/cipher":101,"./des/des":102,"./des/ede":103,"./des/utils":104}],100:[function(require,module,exports){ 'use strict'; - + var assert = require('minimalistic-assert'); var inherits = require('inherits'); - + var proto = {}; - + function CBCState(iv) { assert.equal(iv.length, 8, 'Invalid IV length'); - + this.iv = new Array(8); for (var i = 0; i < this.iv.length; i++) this.iv[i] = iv[i]; } - + function instantiate(Base) { function CBC(options) { Base.call(this, options); this._cbcInit(); } inherits(CBC, Base); - + var keys = Object.keys(proto); for (var i = 0; i < keys.length; i++) { var key = keys[i]; CBC.prototype[key] = proto[key]; } - + CBC.create = function create(options) { return new CBC(options); }; - + return CBC; } - + exports.instantiate = instantiate; - + proto._cbcInit = function _cbcInit() { var state = new CBCState(this.options.iv); this._cbcState = state; }; - + proto._update = function _update(inp, inOff, out, outOff) { var state = this._cbcState; var superProto = this.constructor.super_.prototype; - + var iv = state.iv; if (this.type === 'encrypt') { for (var i = 0; i < this.blockSize; i++) iv[i] ^= inp[inOff + i]; - + superProto._update.call(this, iv, 0, out, outOff); - + for (var i = 0; i < this.blockSize; i++) iv[i] = out[outOff + i]; } else { superProto._update.call(this, inp, inOff, out, outOff); - + for (var i = 0; i < this.blockSize; i++) out[outOff + i] ^= iv[i]; - + for (var i = 0; i < this.blockSize; i++) iv[i] = inp[inOff + i]; } }; - + },{"inherits":180,"minimalistic-assert":234}],101:[function(require,module,exports){ 'use strict'; - + var assert = require('minimalistic-assert'); - + function Cipher(options) { this.options = options; - + this.type = this.options.type; this.blockSize = 8; this._init(); - + this.buffer = new Array(this.blockSize); this.bufferOff = 0; } module.exports = Cipher; - + Cipher.prototype._init = function _init() { // Might be overrided }; - + Cipher.prototype.update = function update(data) { if (data.length === 0) return []; - + if (this.type === 'decrypt') return this._updateDecrypt(data); else return this._updateEncrypt(data); }; - + Cipher.prototype._buffer = function _buffer(data, off) { // Append data to buffer var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); for (var i = 0; i < min; i++) this.buffer[this.bufferOff + i] = data[off + i]; this.bufferOff += min; - + // Shift next return min; }; - + Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { this._update(this.buffer, 0, out, off); this.bufferOff = 0; return this.blockSize; }; - + Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { var inputOff = 0; var outputOff = 0; - + var count = ((this.bufferOff + data.length) / this.blockSize) | 0; var out = new Array(count * this.blockSize); - + if (this.bufferOff !== 0) { inputOff += this._buffer(data, inputOff); - + if (this.bufferOff === this.buffer.length) outputOff += this._flushBuffer(out, outputOff); } - + // Write blocks var max = data.length - ((data.length - inputOff) % this.blockSize); for (; inputOff < max; inputOff += this.blockSize) { this._update(data, inputOff, out, outputOff); outputOff += this.blockSize; } - + // Queue rest for (; inputOff < data.length; inputOff++, this.bufferOff++) this.buffer[this.bufferOff] = data[inputOff]; - + return out; }; - + Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { var inputOff = 0; var outputOff = 0; - + var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; var out = new Array(count * this.blockSize); - + // TODO(indutny): optimize it, this is far from optimal for (; count > 0; count--) { inputOff += this._buffer(data, inputOff); outputOff += this._flushBuffer(out, outputOff); } - + // Buffer rest of the input inputOff += this._buffer(data, inputOff); - + return out; }; - + Cipher.prototype.final = function final(buffer) { var first; if (buffer) first = this.update(buffer); - + var last; if (this.type === 'encrypt') last = this._finalEncrypt(); else last = this._finalDecrypt(); - + if (first) return first.concat(last); else return last; }; - + Cipher.prototype._pad = function _pad(buffer, off) { if (off === 0) return false; - + while (off < buffer.length) buffer[off++] = 0; - + return true; }; - + Cipher.prototype._finalEncrypt = function _finalEncrypt() { if (!this._pad(this.buffer, this.bufferOff)) return []; - + var out = new Array(this.blockSize); this._update(this.buffer, 0, out, 0); return out; }; - + Cipher.prototype._unpad = function _unpad(buffer) { return buffer; }; - + Cipher.prototype._finalDecrypt = function _finalDecrypt() { assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); var out = new Array(this.blockSize); this._flushBuffer(out, 0); - + return this._unpad(out); }; - + },{"minimalistic-assert":234}],102:[function(require,module,exports){ 'use strict'; - + var assert = require('minimalistic-assert'); var inherits = require('inherits'); - + var des = require('../des'); var utils = des.utils; var Cipher = des.Cipher; - + function DESState() { this.tmp = new Array(2); this.keys = null; } - + function DES(options) { Cipher.call(this, options); - + var state = new DESState(); this._desState = state; - + this.deriveKeys(state, options.key); } inherits(DES, Cipher); module.exports = DES; - + DES.create = function create(options) { return new DES(options); }; - + var shiftTable = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ]; - + DES.prototype.deriveKeys = function deriveKeys(state, key) { state.keys = new Array(16 * 2); - + assert.equal(key.length, this.blockSize, 'Invalid key length'); - + var kL = utils.readUInt32BE(key, 0); var kR = utils.readUInt32BE(key, 4); - + utils.pc1(kL, kR, state.tmp, 0); kL = state.tmp[0]; kR = state.tmp[1]; @@ -19220,115 +19220,115 @@ utils.pc2(kL, kR, state.keys, i); } }; - + DES.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._desState; - + var l = utils.readUInt32BE(inp, inOff); var r = utils.readUInt32BE(inp, inOff + 4); - + // Initial Permutation utils.ip(l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; - + if (this.type === 'encrypt') this._encrypt(state, l, r, state.tmp, 0); else this._decrypt(state, l, r, state.tmp, 0); - + l = state.tmp[0]; r = state.tmp[1]; - + utils.writeUInt32BE(out, l, outOff); utils.writeUInt32BE(out, r, outOff + 4); }; - + DES.prototype._pad = function _pad(buffer, off) { var value = buffer.length - off; for (var i = off; i < buffer.length; i++) buffer[i] = value; - + return true; }; - + DES.prototype._unpad = function _unpad(buffer) { var pad = buffer[buffer.length - 1]; for (var i = buffer.length - pad; i < buffer.length; i++) assert.equal(buffer[i], pad); - + return buffer.slice(0, buffer.length - pad); }; - + DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { var l = lStart; var r = rStart; - + // Apply f() x16 times for (var i = 0; i < state.keys.length; i += 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; - + // f(r, k) utils.expand(r, state.tmp, 0); - + keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); - + var t = r; r = (l ^ f) >>> 0; l = t; } - + // Reverse Initial Permutation utils.rip(r, l, out, off); }; - + DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { var l = rStart; var r = lStart; - + // Apply f() x16 times for (var i = state.keys.length - 2; i >= 0; i -= 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; - + // f(r, k) utils.expand(l, state.tmp, 0); - + keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); - + var t = l; l = (r ^ f) >>> 0; r = t; } - + // Reverse Initial Permutation utils.rip(l, r, out, off); }; - + },{"../des":99,"inherits":180,"minimalistic-assert":234}],103:[function(require,module,exports){ 'use strict'; - + var assert = require('minimalistic-assert'); var inherits = require('inherits'); - + var des = require('../des'); var Cipher = des.Cipher; var DES = des.DES; - + function EDEState(type, key) { assert.equal(key.length, 24, 'Invalid key length'); - + var k1 = key.slice(0, 8); var k2 = key.slice(8, 16); var k3 = key.slice(16, 24); - + if (type === 'encrypt') { this.ciphers = [ DES.create({ type: 'encrypt', key: k1 }), @@ -19343,35 +19343,35 @@ ]; } } - + function EDE(options) { Cipher.call(this, options); - + var state = new EDEState(this.type, this.options.key); this._edeState = state; } inherits(EDE, Cipher); - + module.exports = EDE; - + EDE.create = function create(options) { return new EDE(options); }; - + EDE.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._edeState; - + state.ciphers[0]._update(inp, inOff, out, outOff); state.ciphers[1]._update(out, outOff, out, outOff); state.ciphers[2]._update(out, outOff, out, outOff); }; - + EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; - + },{"../des":99,"inherits":180,"minimalistic-assert":234}],104:[function(require,module,exports){ 'use strict'; - + exports.readUInt32BE = function readUInt32BE(bytes, off) { var res = (bytes[0 + off] << 24) | (bytes[1 + off] << 16) | @@ -19379,18 +19379,18 @@ bytes[3 + off]; return res >>> 0; }; - + exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { bytes[0 + off] = value >>> 24; bytes[1 + off] = (value >>> 16) & 0xff; bytes[2 + off] = (value >>> 8) & 0xff; bytes[3 + off] = value & 0xff; }; - + exports.ip = function ip(inL, inR, out, off) { var outL = 0; var outR = 0; - + for (var i = 6; i >= 0; i -= 2) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; @@ -19401,7 +19401,7 @@ outL |= (inL >>> (j + i)) & 1; } } - + for (var i = 6; i >= 0; i -= 2) { for (var j = 1; j <= 25; j += 8) { outR <<= 1; @@ -19412,15 +19412,15 @@ outR |= (inL >>> (j + i)) & 1; } } - + out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; - + exports.rip = function rip(inL, inR, out, off) { var outL = 0; var outR = 0; - + for (var i = 0; i < 4; i++) { for (var j = 24; j >= 0; j -= 8) { outL <<= 1; @@ -19437,15 +19437,15 @@ outR |= (inL >>> (j + i)) & 1; } } - + out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; - + exports.pc1 = function pc1(inL, inR, out, off) { var outL = 0; var outR = 0; - + // 7, 15, 23, 31, 39, 47, 55, 63 // 6, 14, 22, 30, 39, 47, 55, 63 // 5, 13, 21, 29, 39, 47, 55, 63 @@ -19464,7 +19464,7 @@ outL <<= 1; outL |= (inR >> (j + i)) & 1; } - + // 1, 9, 17, 25, 33, 41, 49, 57 // 2, 10, 18, 26, 34, 42, 50, 58 // 3, 11, 19, 27, 35, 43, 51, 59 @@ -19483,31 +19483,31 @@ outR <<= 1; outR |= (inL >> (j + i)) & 1; } - + out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; - + exports.r28shl = function r28shl(num, shift) { return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); }; - + var pc2table = [ // inL => outL 14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, - + // inR => outR 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24 ]; - + exports.pc2 = function pc2(inL, inR, out, off) { var outL = 0; var outR = 0; - + var len = pc2table.length >>> 1; for (var i = 0; i < len; i++) { outL <<= 1; @@ -19517,15 +19517,15 @@ outR <<= 1; outR |= (inR >>> pc2table[i]) & 0x1; } - + out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; - + exports.expand = function expand(r, out, off) { var outL = 0; var outR = 0; - + outL = ((r & 1) << 5) | (r >>> 27); for (var i = 23; i >= 15; i -= 4) { outL <<= 6; @@ -19536,77 +19536,77 @@ outR <<= 6; } outR |= ((r & 0x1f) << 1) | (r >>> 31); - + out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; - + var sTable = [ 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, - + 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, - + 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, - + 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, - + 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, - + 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, - + 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, - + 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 ]; - + exports.substitute = function substitute(inL, inR) { var out = 0; for (var i = 0; i < 4; i++) { var b = (inL >>> (18 - i * 6)) & 0x3f; var sb = sTable[i * 0x40 + b]; - + out <<= 4; out |= sb; } for (var i = 0; i < 4; i++) { var b = (inR >>> (18 - i * 6)) & 0x3f; var sb = sTable[4 * 0x40 + i * 0x40 + b]; - + out <<= 4; out |= sb; } return out >>> 0; }; - + var permuteTable = [ 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 ]; - + exports.permute = function permute(num) { var out = 0; for (var i = 0; i < permuteTable.length; i++) { @@ -19615,63 +19615,63 @@ } return out >>> 0; }; - + exports.padSplit = function padSplit(num, size, group) { var str = num.toString(2); while (str.length < size) str = '0' + str; - + var out = []; for (var i = 0; i < size; i += group) out.push(str.slice(i, i + group)); return out.join(' '); }; - + },{}],105:[function(require,module,exports){ (function (Buffer){ var generatePrime = require('./lib/generatePrime') var primes = require('./lib/primes.json') - + var DH = require('./lib/dh') - + function getDiffieHellman (mod) { var prime = new Buffer(primes[mod].prime, 'hex') var gen = new Buffer(primes[mod].gen, 'hex') - + return new DH(prime, gen) } - + var ENCODINGS = { 'binary': true, 'hex': true, 'base64': true } - + function createDiffieHellman (prime, enc, generator, genc) { if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { return createDiffieHellman(prime, 'binary', enc, generator) } - + enc = enc || 'binary' genc = genc || 'binary' generator = generator || new Buffer([2]) - + if (!Buffer.isBuffer(generator)) { generator = new Buffer(generator, genc) } - + if (typeof prime === 'number') { return new DH(generatePrime(prime, generator), generator, true) } - + if (!Buffer.isBuffer(prime)) { prime = new Buffer(prime, enc) } - + return new DH(prime, generator, true) } - + exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman - + }).call(this,require("buffer").Buffer) },{"./lib/dh":106,"./lib/generatePrime":107,"./lib/primes.json":108,"buffer":84}],106:[function(require,module,exports){ (function (Buffer){ @@ -19686,7 +19686,7 @@ var primes = require('./generatePrime'); var randomBytes = require('randombytes'); module.exports = DH; - + function setPublicKey(pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { @@ -19695,7 +19695,7 @@ this._pub = new BN(pub); return this; } - + function setPrivateKey(priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { @@ -19704,7 +19704,7 @@ this._priv = new BN(priv); return this; } - + var primeCache = {}; function checkPrime(prime, generator) { var gen = generator.toString('hex'); @@ -19713,14 +19713,14 @@ return primeCache[hex]; } var error = 0; - + if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { //not a prime so +1 error += 1; - + if (gen === '02' || gen === '05') { // we'd be able to check the generator // it would fail so +8 @@ -19758,7 +19758,7 @@ primeCache[hex] = error; return error; } - + function DH(prime, generator, malleable) { this.setGenerator(generator); this.__prime = new BN(prime); @@ -19790,7 +19790,7 @@ this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); return this.getPublicKey(); }; - + DH.prototype.computeSecret = function (other) { other = new BN(other); other = other.toRed(this._prime); @@ -19804,23 +19804,23 @@ } return out; }; - + DH.prototype.getPublicKey = function getPublicKey(enc) { return formatReturnValue(this._pub, enc); }; - + DH.prototype.getPrivateKey = function getPrivateKey(enc) { return formatReturnValue(this._priv, enc); }; - + DH.prototype.getPrime = function (enc) { return formatReturnValue(this.__prime, enc); }; - + DH.prototype.getGenerator = function (enc) { return formatReturnValue(this._gen, enc); }; - + DH.prototype.setGenerator = function (gen, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(gen)) { @@ -19830,7 +19830,7 @@ this._gen = new BN(gen); return this; }; - + function formatReturnValue(bn, enc) { var buf = new Buffer(bn.toArray()); if (!enc) { @@ -19839,7 +19839,7 @@ return buf.toString(enc); } } - + }).call(this,require("buffer").Buffer) },{"./generatePrime":107,"bn.js":53,"buffer":84,"miller-rabin":233,"randombytes":270}],107:[function(require,module,exports){ var randomBytes = require('randombytes'); @@ -19862,11 +19862,11 @@ var FOUR = new BN(4); var TWELVE = new BN(12); var primes = null; - + function _getPrimes() { if (primes !== null) return primes; - + var limit = 0x100000; var res = []; res[0] = 2; @@ -19875,19 +19875,19 @@ for (var j = 0; j < i && res[j] <= sqrt; j++) if (k % res[j] === 0) break; - + if (i !== j && res[j] <= sqrt) continue; - + res[i++] = k; } primes = res; return res; } - + function simpleSieve(p) { var primes = _getPrimes(); - + for (var i = 0; i < primes.length; i++) if (p.modn(primes[i]) === 0) { if (p.cmpn(primes[i]) === 0) { @@ -19896,15 +19896,15 @@ return false; } } - + return true; } - + function fermatTest(p) { var red = BN.mont(p); return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; } - + function findPrime(bits, gen) { if (bits < 16) { // this is what openssl does @@ -19915,9 +19915,9 @@ } } gen = new BN(gen); - + var num, n2; - + while (true) { num = new BN(randomBytes(Math.ceil(bits / 8))); while (num.bitLength() > bits) { @@ -19945,9 +19945,9 @@ return num; } } - + } - + },{"bn.js":53,"miller-rabin":233,"randombytes":270}],108:[function(require,module,exports){ module.exports={ "modp1": { @@ -19985,51 +19985,51 @@ } },{}],109:[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":124,"./elliptic/curve":112,"./elliptic/curves":115,"./elliptic/ec":116,"./elliptic/eddsa":119,"./elliptic/utils":123,"brorand":54}],110:[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) { @@ -20040,23 +20040,23 @@ } } 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) { @@ -20065,7 +20065,7 @@ 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--) { @@ -20080,18 +20080,18 @@ } 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--) { @@ -20101,7 +20101,7 @@ if (i >= 0) k++; acc = acc.dblp(k); - + if (i < 0) break; var z = naf[i]; @@ -20122,7 +20122,7 @@ } return p.type === 'affine' ? acc.toP() : acc; }; - + BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, points, coeffs, @@ -20131,7 +20131,7 @@ 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++) { @@ -20140,7 +20140,7 @@ 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; @@ -20152,14 +20152,14 @@ 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]); @@ -20171,7 +20171,7 @@ 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 */ @@ -20183,7 +20183,7 @@ 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); @@ -20191,18 +20191,18 @@ 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++) { @@ -20220,7 +20220,7 @@ acc = acc.dblp(k); if (i < 0) break; - + for (var j = 0; j < len; j++) { var z = tmp[j]; var p; @@ -20230,7 +20230,7 @@ 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 @@ -20240,33 +20240,33 @@ // 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) { @@ -20274,10 +20274,10 @@ 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) { @@ -20285,29 +20285,29 @@ } 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, @@ -20317,25 +20317,25 @@ 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) { @@ -20348,11 +20348,11 @@ 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(); @@ -20363,133 +20363,133 @@ 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":109,"bn.js":53}],111:[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 - 1) / (d y^2 + 1) var y2 = y.redSqr(); var lhs = y2.redSub(this.one); var rhs = y2.redMul(this.d).redAdd(this.one); 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.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) { @@ -20512,7 +20512,7 @@ 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); @@ -20522,19 +20522,19 @@ } } 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 ''; @@ -20542,18 +20542,18 @@ ' y: ' + this.y.fromRed().toString(16, 2) + ' z: ' + this.z.fromRed().toString(16, 2) + '>'; }; - + 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; }; - + 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 @@ -20581,21 +20581,21 @@ 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; @@ -20639,23 +20639,23 @@ } 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) @@ -20682,13 +20682,13 @@ 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 @@ -20721,38 +20721,38 @@ } 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); @@ -20763,77 +20763,77 @@ 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; } return false; }; - + // Compatibility with BaseCurve Point.prototype.toP = Point.prototype.normalize; Point.prototype.mixedAdd = Point.prototype.add; - + },{"../../elliptic":109,"../curve":112,"bn.js":53,"inherits":180}],112:[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":110,"./edwards":111,"./mont":113,"./short":114}],113:[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(); @@ -20842,16 +20842,16 @@ } 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) { @@ -20867,47 +20867,47 @@ } } 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 @@ -20924,15 +20924,15 @@ 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 @@ -20951,16 +20951,16 @@ 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 @@ -20976,53 +20976,53 @@ } 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":109,"../curve":112,"bn.js":53,"inherits":180}],114:[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); @@ -21030,12 +21030,12 @@ } 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; @@ -21059,7 +21059,7 @@ 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) { @@ -21072,14 +21072,14 @@ } 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 @@ -21087,18 +21087,18 @@ 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; @@ -21107,7 +21107,7 @@ 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; @@ -21117,7 +21117,7 @@ // Second vector var a2; var b2; - + var prevR; var i = 0; var r; @@ -21127,7 +21127,7 @@ 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; @@ -21137,7 +21137,7 @@ break; } prevR = r; - + v = u; u = r; x2 = x1; @@ -21147,14 +21147,14 @@ } 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(); @@ -21164,63 +21164,63 @@ 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; @@ -21229,7 +21229,7 @@ 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); @@ -21238,14 +21238,14 @@ 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; @@ -21253,7 +21253,7 @@ } return res; }; - + function Point(curve, x, y, isRed) { Base.BasePoint.call(this, curve, 'affine'); if (x === null && y === null) { @@ -21276,23 +21276,23 @@ } } 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; @@ -21314,11 +21314,11 @@ } 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, @@ -21330,18 +21330,18 @@ } } ]; }; - + 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, @@ -21356,39 +21356,39 @@ }; 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()); @@ -21396,38 +21396,38 @@ 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) @@ -21435,7 +21435,7 @@ else return this.curve._wnafMul(this, k); }; - + Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { var points = [ this, p2 ]; var coeffs = [ k1, k2 ]; @@ -21444,7 +21444,7 @@ 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 ]; @@ -21453,17 +21453,17 @@ 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; @@ -21483,15 +21483,15 @@ } 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) { @@ -21509,40 +21509,40 @@ 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(); @@ -21550,7 +21550,7 @@ 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) { @@ -21559,34 +21559,34 @@ 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) { @@ -21595,18 +21595,18 @@ 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; @@ -21614,24 +21614,24 @@ 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++) { @@ -21639,7 +21639,7 @@ 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); @@ -21648,19 +21648,19 @@ 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) @@ -21668,7 +21668,7 @@ else return this._dbl(); }; - + JPoint.prototype._zeroDbl = function _zeroDbl() { var nx; var ny; @@ -21678,7 +21678,7 @@ // 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 @@ -21692,12 +21692,12 @@ 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 @@ -21708,7 +21708,7 @@ // 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 @@ -21722,12 +21722,12 @@ 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 @@ -21736,10 +21736,10 @@ 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; @@ -21749,7 +21749,7 @@ // 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 @@ -21775,7 +21775,7 @@ } 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 @@ -21799,47 +21799,47 @@ 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 @@ -21880,55 +21880,55 @@ 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; } return false; }; - + JPoint.prototype.inspect = function inspect() { if (this.isInfinity()) return ''; @@ -21936,22 +21936,22 @@ ' y: ' + this.y.toString(16, 2) + ' z: ' + this.z.toString(16, 2) + '>'; }; - + JPoint.prototype.isInfinity = function isInfinity() { // XXX This code assumes that zero is always zero in red return this.z.cmpn(0) === 0; }; - + },{"../../elliptic":109,"../curve":112,"bn.js":53,"inherits":180}],115:[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); @@ -21962,12 +21962,12 @@ 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, @@ -21983,7 +21983,7 @@ } }); } - + defineCurve('p192', { type: 'short', prime: 'p192', @@ -21998,7 +21998,7 @@ '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' ] }); - + defineCurve('p224', { type: 'short', prime: 'p224', @@ -22013,7 +22013,7 @@ 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' ] }); - + defineCurve('p256', { type: 'short', prime: null, @@ -22028,7 +22028,7 @@ '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' ] }); - + defineCurve('p384', { type: 'short', prime: null, @@ -22049,7 +22049,7 @@ '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' ] }); - + defineCurve('p521', { type: 'short', prime: null, @@ -22076,7 +22076,7 @@ '3fad0761 353c7086 a272c240 88be9476 9fd16650' ] }); - + defineCurve('curve25519', { type: 'mont', prime: 'p25519', @@ -22090,7 +22090,7 @@ '9' ] }); - + defineCurve('ed25519', { type: 'edwards', prime: 'p25519', @@ -22104,19 +22104,19 @@ gRed: false, g: [ '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - + // 4/5 '6666666666666666666666666666666666666666666666666666666666666658' ] }); - + var pre; try { pre = require('./precomputed/secp256k1'); } catch (e) { pre = undefined; } - + defineCurve('secp256k1', { type: 'short', prime: 'k256', @@ -22126,7 +22126,7 @@ n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', h: '1', hash: hash.sha256, - + // Precomputed endomorphism beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', @@ -22140,7 +22140,7 @@ b: '3086d221a7d46bcde86c90e49284eb15' } ], - + gRed: false, g: [ '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', @@ -22148,64 +22148,64 @@ pre ] }); - + },{"../elliptic":109,"./precomputed/secp256k1":122,"hash.js":162}],116:[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, @@ -22215,19 +22215,19 @@ 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) @@ -22237,7 +22237,7 @@ else return msg; }; - + EC.prototype.sign = function sign(msg, key, enc, options) { if (typeof enc === 'object') { options = enc; @@ -22245,17 +22245,17 @@ } 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, @@ -22264,10 +22264,10 @@ 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) : @@ -22275,39 +22275,39 @@ 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; @@ -22315,68 +22315,68 @@ 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 { @@ -22384,26 +22384,26 @@ } catch (e) { continue; } - + if (Qprime.eq(Q)) return i; } throw new Error('Unable to find valid recovery factor'); }; - + },{"../../elliptic":109,"./key":117,"./signature":118,"bn.js":53,"hmac-drbg":174}],117:[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); @@ -22411,71 +22411,71 @@ 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. @@ -22492,42 +22492,42 @@ } 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":109,"bn.js":53}],118:[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); @@ -22537,11 +22537,11 @@ this.recoveryParam = options.recoveryParam; } module.exports = Signature; - + function Position() { this.place = 0; } - + function getLength(buf, p) { var initial = buf[p.place++]; if (!(initial & 0x80)) { @@ -22556,7 +22556,7 @@ p.place = off; return val; } - + function rmPadding(buf) { var i = 0; var len = buf.length - 1; @@ -22568,7 +22568,7 @@ } return buf.slice(i); } - + Signature.prototype._importDER = function _importDER(data, enc) { data = utils.toArray(data, enc); var p = new Position(); @@ -22599,14 +22599,14 @@ 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); @@ -22619,21 +22619,21 @@ } 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); } @@ -22648,10 +22648,10 @@ res = res.concat(backHalf); return utils.encode(res, enc); }; - + },{"../../elliptic":109,"bn.js":53}],119:[function(require,module,exports){ 'use strict'; - + var hash = require('hash.js'); var elliptic = require('../../elliptic'); var utils = elliptic.utils; @@ -22659,25 +22659,25 @@ 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 @@ -22694,7 +22694,7 @@ 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 @@ -22710,28 +22710,28 @@ 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 * @@ -22745,39 +22745,39 @@ 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":109,"./key":120,"./signature":121,"hash.js":162}],120:[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 @@ -22795,88 +22795,88 @@ 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":109}],121:[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 - @@ -22887,54 +22887,54 @@ */ 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":109,"bn.js":53}],122:[function(require,module,exports){ module.exports = { doubles: { @@ -23716,21 +23716,21 @@ ] } }; - + },{}],123:[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 = []; @@ -23749,31 +23749,31 @@ 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; @@ -23792,7 +23792,7 @@ u1 = m14; } jsf[0].push(u1); - + var u2; if ((m24 & 1) === 0) { u2 = 0; @@ -23804,7 +23804,7 @@ u2 = m24; } jsf[1].push(u2); - + // Second phase if (2 * d1 === u1 + 1) d1 = 1 - d1; @@ -23813,11 +23813,11 @@ k1.iushrn(1); k2.iushrn(1); } - + return jsf; } utils.getJSF = getJSF; - + function cachedProperty(obj, name, computer) { var key = '_' + name; obj.prototype[name] = function cachedProperty() { @@ -23826,19 +23826,19 @@ }; } 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":53,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],124:[function(require,module,exports){ module.exports={ "_from": "elliptic@^6.0.0", @@ -23927,21 +23927,21 @@ }, "version": "6.4.0" } - + },{}],125:[function(require,module,exports){ 'use strict' - + const ethjsUtil = require('ethjs-util') - + module.exports = { incrementHexNumber, formatHex, } - + function incrementHexNumber(hexNum) { return formatHex(ethjsUtil.intToHex((parseInt(hexNum, 16) + 1))) } - + function formatHex (hexNum) { let stripped = ethjsUtil.stripHexPrefix(hexNum) while (stripped[0] === '0') { @@ -23949,7 +23949,7 @@ } return `0x${stripped}` } - + },{"ethjs-util":155}],126:[function(require,module,exports){ // const EthQuery = require('ethjs-query') const EthQuery = require('eth-query') @@ -23959,9 +23959,9 @@ const incrementHexNumber = hexUtils.incrementHexNumber const sec = 1000 const min = 60 * sec - + class RpcBlockTracker extends EventEmitter { - + constructor(opts = {}) { super() if (!opts.provider) throw new Error('RpcBlockTracker - no provider specified.') @@ -23979,15 +23979,15 @@ this._performSync = this._performSync.bind(this) this._handleNewBlockNotification = this._handleNewBlockNotification.bind(this) } - + getTrackingBlock () { return this._trackingBlock } - + getCurrentBlock () { return this._currentBlock } - + async awaitCurrentBlock () { // return if available if (this._currentBlock) return this._currentBlock @@ -23996,7 +23996,7 @@ // return newly set current block return this._currentBlock } - + async start (opts = {}) { // abort if already started if (this._isRunning) return @@ -24018,18 +24018,18 @@ }) } } - + async stop () { this._isRunning = false if (this._provider.on) { await this._removeSubscription() } } - + // // private // - + async _setTrackingBlock (newBlock) { if (this._trackingBlock && (this._trackingBlock.hash === newBlock.hash)) return // check for large timestamp lapse @@ -24045,7 +24045,7 @@ this.emit('block', newBlock) } } - + async _setCurrentBlock (newBlock) { if (this._currentBlock && (this._currentBlock.hash === newBlock.hash)) return const oldBlock = this._currentBlock @@ -24053,23 +24053,23 @@ this.emit('latest', newBlock) this.emit('sync', { newBlock, oldBlock }) } - + async _warpToLatest() { // set latest as tracking block await this._setTrackingBlock(await this._fetchLatestBlock()) } - + async _pollForNextBlock () { setTimeout(() => this._performSync(), this._pollingInterval) } - + async _performSync () { if (!this._isRunning) return const trackingBlock = this.getTrackingBlock() if (!trackingBlock) throw new Error('RpcBlockTracker - tracking block is missing') const nextNumber = incrementHexNumber(trackingBlock.number) try { - + const newBlock = await this._fetchBlockByNumber(nextNumber) if (newBlock) { // set as new tracking block @@ -24082,9 +24082,9 @@ // setup poll for next block this._pollForNextBlock() } - + } catch (err) { - + // hotfix for https://github.com/ethereumjs/testrpc/issues/290 if (err.message.includes('index out of range') || err.message.includes("Couldn't find block by reference")) { @@ -24096,25 +24096,25 @@ console.error(err) this._pollForNextBlock() } - + } } - + async _handleNewBlockNotification(err, notification) { if (notification.id != this._subscriptionId) return // this notification isn't for us - + if (err) { this.emit('error', err) await this._removeSubscription() } - + await this._setTrackingBlock(await this._fetchBlockByNumber(notification.result.number)) } - + async _initSubscription() { this._provider.on('data', this._handleNewBlockNotification) - + let result = await pify(this._provider.sendAsync || this._provider.send)({ jsonrpc: '2.0', id: new Date().getTime(), @@ -24123,15 +24123,15 @@ 'newHeads' ], }) - + this._subscriptionId = result.result } - + async _removeSubscription() { if (!this._subscriptionId) throw new Error("Not subscribed.") - + this._provider.removeListener('data', this._handleNewBlockNotification) - + await pify(this._provider.sendAsync || this._provider.send)({ jsonrpc: '2.0', id: new Date().getTime(), @@ -24140,23 +24140,23 @@ this._subscriptionId ], }) - + delete this._subscriptionId } - + _fetchLatestBlock () { return pify(this._query.getBlockByNumber).call(this._query, 'latest', true) } - + _fetchBlockByNumber (hexNumber) { const cleanHex = hexUtils.formatHex(hexNumber) return pify(this._query.getBlockByNumber).call(this._query, cleanHex, true) } - + } - + module.exports = RpcBlockTracker - + // ├─ difficulty: 0x2892ddca // ├─ extraData: 0xd983010507846765746887676f312e372e348777696e646f7773 // ├─ gasLimit: 0x47e7c4 @@ -24192,40 +24192,40 @@ // │ └─ s: 0x1610cdac2782c91065fd43584cd8974f7f3b4e6d46a2aafe7b101788285bf3f2 // ├─ transactionsRoot: 0xb090c32d840dec1e9752719f21bbae4a73e58333aecb89bc3b8ed559fb2712a3 // └─ uncles - + },{"./hexUtils":125,"eth-query":135,"events":157,"pify":252}],127:[function(require,module,exports){ (function (Buffer){ var sha3 = require('js-sha3').keccak_256 var uts46 = require('idna-uts46-hx') - + function namehash (inputName) { // Reject empty names: var node = '' for (var i = 0; i < 32; i++) { node += '00' } - + name = normalize(inputName) - + if (name) { var labels = name.split('.') - + for(var i = labels.length - 1; i >= 0; i--) { var labelSha = sha3(labels[i]) node = sha3(new Buffer(node + labelSha, 'hex')) } } - + return '0x' + node } - + function normalize(name) { return name ? uts46.toUnicode(name, {useStd3ASCII: true, transitional: false}) : name } - + exports.hash = namehash exports.normalize = normalize - + }).call(this,require("buffer").Buffer) },{"buffer":84,"idna-uts46-hx":177,"js-sha3":128}],128:[function(require,module,exports){ (function (process,global){ @@ -24240,7 +24240,7 @@ /*jslint bitwise: true */ (function () { 'use strict'; - + var root = typeof window === 'object' ? window : {}; var NODE_JS = !root.JS_SHA3_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node; if (NODE_JS) { @@ -24260,19 +24260,19 @@ var BITS = [224, 256, 384, 512]; var SHAKE_BITS = [128, 256]; var OUTPUT_TYPES = ['hex', 'buffer', 'arrayBuffer', 'array']; - + var createOutputMethod = function (bits, padding, outputType) { return function (message) { return new Keccak(bits, padding, bits).update(message)[outputType](); }; }; - + var createShakeOutputMethod = function (bits, padding, outputType) { return function (message, outputBits) { return new Keccak(bits, padding, outputBits).update(message)[outputType](); }; }; - + var createMethod = function (bits, padding) { var method = createOutputMethod(bits, padding, 'hex'); method.create = function () { @@ -24287,7 +24287,7 @@ } return method; }; - + var createShakeMethod = function (bits, padding) { var method = createShakeOutputMethod(bits, padding, 'hex'); method.create = function (outputBits) { @@ -24302,15 +24302,15 @@ } return method; }; - + var algorithms = [ {name: 'keccak', padding: KECCAK_PADDING, bits: BITS, createMethod: createMethod}, {name: 'sha3', padding: PADDING, bits: BITS, createMethod: createMethod}, {name: 'shake', padding: SHAKE_PADDING, bits: SHAKE_BITS, createMethod: createShakeMethod} ]; - + var methods = {}, methodNames = []; - + for (var i = 0; i < algorithms.length; ++i) { var algorithm = algorithms[i]; var bits = algorithm.bits; @@ -24320,7 +24320,7 @@ methods[methodName] = algorithm.createMethod(bits[j], algorithm.padding); } } - + function Keccak(bits, padding, outputBits) { this.blocks = []; this.s = []; @@ -24333,12 +24333,12 @@ this.byteCount = this.blockCount << 2; this.outputBlocks = outputBits >> 5; this.extraBytes = (outputBits & 31) >> 3; - + for (var i = 0; i < 50; ++i) { this.s[i] = 0; } } - + Keccak.prototype.update = function (message) { var notString = typeof message !== 'string'; if (notString && message.constructor === ArrayBuffer) { @@ -24346,7 +24346,7 @@ } var length = message.length, blocks = this.blocks, byteCount = this.byteCount, blockCount = this.blockCount, index = 0, s = this.s, i, code; - + while (index < length) { if (this.reset) { this.reset = false; @@ -24395,7 +24395,7 @@ } return this; }; - + Keccak.prototype.finalize = function () { var blocks = this.blocks, i = this.lastByteIndex, blockCount = this.blockCount, s = this.s; blocks[i >> 2] |= this.padding[i & 3]; @@ -24411,10 +24411,10 @@ } f(s); }; - + Keccak.prototype.toString = Keccak.prototype.hex = function () { this.finalize(); - + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var hex = '', block; @@ -24445,10 +24445,10 @@ } return hex; }; - + Keccak.prototype.arrayBuffer = function () { this.finalize(); - + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var bytes = this.outputBits >> 3; @@ -24473,12 +24473,12 @@ } return buffer; }; - + Keccak.prototype.buffer = Keccak.prototype.arrayBuffer; - + Keccak.prototype.digest = Keccak.prototype.array = function () { this.finalize(); - + var blockCount = this.blockCount, s = this.s, outputBlocks = this.outputBlocks, extraBytes = this.extraBytes, i = 0, j = 0; var array = [], offset, block; @@ -24510,7 +24510,7 @@ } return array; }; - + var f = function (s) { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, @@ -24527,7 +24527,7 @@ c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - + h = c8 ^ ((c2 << 1) | (c3 >>> 31)); l = c9 ^ ((c3 << 1) | (c2 >>> 31)); s[0] ^= h; @@ -24588,7 +24588,7 @@ s[39] ^= l; s[48] ^= h; s[49] ^= l; - + b0 = s[0]; b1 = s[1]; b32 = (s[11] << 4) | (s[10] >>> 28); @@ -24639,7 +24639,7 @@ b27 = (s[39] << 8) | (s[38] >>> 24); b8 = (s[48] << 14) | (s[49] >>> 18); b9 = (s[49] << 14) | (s[48] >>> 18); - + s[0] = b0 ^ (~b2 & b4); s[1] = b1 ^ (~b3 & b5); s[10] = b10 ^ (~b12 & b14); @@ -24690,12 +24690,12 @@ s[39] = b39 ^ (~b31 & b33); s[48] = b48 ^ (~b40 & b42); s[49] = b49 ^ (~b41 & b43); - + s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } }; - + if (COMMON_JS) { module.exports = methods; } else { @@ -24704,27 +24704,27 @@ } } })(); - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":257}],129:[function(require,module,exports){ const RpcEngine = require('json-rpc-engine') const providerFromEngine = require('eth-json-rpc-middleware/providerFromEngine') const createInfuraMiddleware = require('./index') - - + + module.exports = createProvider - + function createProvider(opts){ const engine = new RpcEngine() engine.push(createInfuraMiddleware(opts)) return providerFromEngine(engine) } - + },{"./index":130,"eth-json-rpc-middleware/providerFromEngine":131,"json-rpc-engine":188}],130:[function(require,module,exports){ const createAsyncMiddleware = require('json-rpc-engine/src/createAsyncMiddleware') const JsonRpcError = require('json-rpc-error') const fetch = require('cross-fetch') - + const POST_METHODS = ['eth_call', 'eth_estimateGas', 'eth_sendRawTransaction'] const RETRIABLE_ERRORS = [ // ignore server overload errors @@ -24735,16 +24735,16 @@ // or truncated json responses 'SyntaxError', ] - + module.exports = createInfuraMiddleware module.exports.fetchConfigFromReq = fetchConfigFromReq - + function createInfuraMiddleware(opts = {}) { const network = opts.network || 'mainnet' const maxAttempts = opts.maxAttempts || 5 // validate options if (!maxAttempts) throw new Error(`Invalid value for 'maxAttempts': "${maxAttempts}" (${typeof maxAttempts})`) - + return createAsyncMiddleware(async (req, res, next) => { // retry MAX_ATTEMPTS times, if error matches filter for (let attempt = 1; attempt <= maxAttempts; attempt++) { @@ -24774,18 +24774,18 @@ // request was handled correctly, end }) } - + function timeout(length) { return new Promise((resolve) => { setTimeout(resolve, length) }) } - + function isRetriableError(err) { const errMessage = err.toString() return RETRIABLE_ERRORS.some(phrase => errMessage.includes(phrase)) } - + async function performFetch(network, req, res){ const { fetchUrl, fetchParams } = fetchConfigFromReq({ network, req }) const response = await fetch(fetchUrl, fetchParams) @@ -24795,37 +24795,37 @@ switch (response.status) { case 405: throw new JsonRpcError.MethodNotFound() - + case 418: throw createRatelimitError() - + case 503: case 504: throw createTimeoutError() - + default: throw createInternalError(rawData) } } - + // special case for now if (req.method === 'eth_getBlockByNumber' && rawData === 'Not Found') { res.result = null return } - + // parse JSON const data = JSON.parse(rawData) - + // finally return result res.result = data.result res.error = data.error } - + function fetchConfigFromReq({ network, req }) { const cleanReq = normalizeReq(req) const { method, params } = cleanReq - + const fetchParams = {} let fetchUrl = `https://api.infura.io/v1/jsonrpc/${network}` const isPostMethod = POST_METHODS.includes(method) @@ -24841,10 +24841,10 @@ const paramsString = encodeURIComponent(JSON.stringify(params)) fetchUrl += `/${method}?params=${paramsString}` } - + return { fetchUrl, fetchParams } } - + // strips out extra keys that could be rejected by strict nodes like parity function normalizeReq(req) { return { @@ -24854,31 +24854,31 @@ params: req.params, } } - + function createRatelimitError () { let msg = `Request is being rate limited.` return createInternalError(msg) } - + function createTimeoutError () { let msg = `Gateway timeout. The request took too long to process. ` msg += `This can happen when querying logs over too wide a block range.` return createInternalError(msg) } - + function createInternalError (msg) { const err = new Error(msg) return new JsonRpcError.InternalError(err) } - + },{"cross-fetch":96,"json-rpc-engine/src/createAsyncMiddleware":187,"json-rpc-error":189}],131:[function(require,module,exports){ module.exports = providerFromEngine - + function providerFromEngine (engine) { const provider = { sendAsync: engine.handle.bind(engine) } return provider } - + },{}],132:[function(require,module,exports){ var generate = function generate(num, fn) { var a = []; @@ -24886,17 +24886,17 @@ a.push(fn(i)); }return a; }; - + var replicate = function replicate(num, val) { return generate(num, function () { return val; }); }; - + var concat = function concat(a, b) { return a.concat(b); }; - + var flatten = function flatten(a) { var r = []; for (var j = 0, J = a.length; j < J; ++j) { @@ -24905,14 +24905,14 @@ } }return r; }; - + var chunksOf = function chunksOf(n, a) { var b = []; for (var i = 0, l = a.length; i < l; i += n) { b.push(a.slice(i, i + n)); }return b; }; - + module.exports = { generate: generate, replicate: replicate, @@ -24922,11 +24922,11 @@ }; },{}],133:[function(require,module,exports){ var A = require("./array.js"); - + var at = function at(bytes, index) { return parseInt(bytes.slice(index * 2 + 2, index * 2 + 4), 16); }; - + var random = function random(bytes) { var rnd = void 0; if (typeof window !== "undefined" && window.crypto && window.crypto.getRandomValues) rnd = window.crypto.getRandomValues(new Uint8Array(bytes));else if (typeof require !== "undefined") rnd = require("c" + "rypto").randomBytes(bytes);else throw "Safe random numbers not available."; @@ -24935,21 +24935,21 @@ hex += ("00" + rnd[i].toString(16)).slice(-2); }return hex; }; - + var length = function length(a) { return (a.length - 2) / 2; }; - + var flatten = function flatten(a) { return "0x" + a.reduce(function (r, s) { return r + s.slice(2); }, ""); }; - + var slice = function slice(i, j, bs) { return "0x" + bs.slice(i * 2 + 2, j * 2 + 2); }; - + var reverse = function reverse(hex) { var rev = "0x"; for (var i = 0, l = length(hex); i < l; ++i) { @@ -24957,22 +24957,22 @@ } return rev; }; - + var pad = function pad(l, hex) { return hex.length === l * 2 + 2 ? hex : pad(l, "0x" + "0" + hex.slice(2)); }; - + var padRight = function padRight(l, hex) { return hex.length === l * 2 + 2 ? hex : padRight(l, hex + "0"); }; - + var toArray = function toArray(hex) { var arr = []; for (var i = 2, l = hex.length; i < l; i += 2) { arr.push(parseInt(hex.slice(i, i + 2), 16)); }return arr; }; - + var fromArray = function fromArray(arr) { var hex = "0x"; for (var i = 0, l = arr.length; i < l; ++i) { @@ -24981,50 +24981,50 @@ } return hex; }; - + var toUint8Array = function toUint8Array(hex) { return new Uint8Array(toArray(hex)); }; - + var fromUint8Array = function fromUint8Array(arr) { return fromArray([].slice.call(arr, 0)); }; - + var fromNumber = function fromNumber(num) { var hex = num.toString(16); return hex.length % 2 === 0 ? "0x" + hex : "0x0" + hex; }; - + var toNumber = function toNumber(hex) { return parseInt(hex.slice(2), 16); }; - + var concat = function concat(a, b) { return a.concat(b.slice(2)); }; - + var fromNat = function fromNat(bn) { return bn === "0x0" ? "0x" : bn.length % 2 === 0 ? bn : "0x0" + bn.slice(2); }; - + var toNat = function toNat(bn) { return bn[2] === "0" ? "0x" + bn.slice(3) : bn; }; - + var fromAscii = function fromAscii(ascii) { var hex = "0x"; for (var i = 0; i < ascii.length; ++i) { hex += ("00" + ascii.charCodeAt(i).toString(16)).slice(-2); }return hex; }; - + var toAscii = function toAscii(hex) { var ascii = ""; for (var i = 2; i < hex.length; i += 2) { ascii += String.fromCharCode(parseInt(hex.slice(i, i + 2), 16)); }return ascii; }; - + // From https://gist.github.com/pascaldekloe/62546103a1576803dade9269ccf76330 var fromString = function fromString(s) { var makeByte = function makeByte(uint8) { @@ -25058,7 +25058,7 @@ } return bytes; }; - + var toString = function toString(bytes) { var s = ''; var i = 0; @@ -25086,7 +25086,7 @@ } return s; }; - + module.exports = { random: random, length: length, @@ -25114,7 +25114,7 @@ // modifications and pruning. It is licensed under MIT: // // Copyright 2015-2016 Chen, Yi-Cyuan - // + // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including @@ -25122,10 +25122,10 @@ // 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 @@ -25133,12 +25133,12 @@ // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - + var HEX_CHARS = '0123456789abcdef'.split(''); var KECCAK_PADDING = [1, 256, 65536, 16777216]; var SHIFT = [0, 8, 16, 24]; var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - + var Keccak = function Keccak(bits) { return { blocks: [], @@ -25152,7 +25152,7 @@ }([0, 0, 0, 0, 0, 0, 0, 0, 0, 0]) }; }; - + var update = function update(state, message) { var length = message.length, blocks = state.blocks, @@ -25163,7 +25163,7 @@ index = 0, i, code; - + // update while (index < length) { if (state.reset) { @@ -25211,7 +25211,7 @@ state.start = i; } } - + // finalize i = state.lastByteIndex; blocks[i >> 2] |= KECCAK_PADDING[i & 3]; @@ -25226,7 +25226,7 @@ s[i] ^= blocks[i]; } f(s); - + // toString var hex = '', i = 0, @@ -25244,10 +25244,10 @@ } return "0x" + hex; }; - + var f = function f(s) { var h, l, n, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - + for (n = 0; n < 48; n += 2) { c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; @@ -25259,7 +25259,7 @@ c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - + h = c8 ^ (c2 << 1 | c3 >>> 31); l = c9 ^ (c3 << 1 | c2 >>> 31); s[0] ^= h; @@ -25320,7 +25320,7 @@ s[39] ^= l; s[48] ^= h; s[49] ^= l; - + b0 = s[0]; b1 = s[1]; b32 = s[11] << 4 | s[10] >>> 28; @@ -25371,7 +25371,7 @@ b27 = s[39] << 8 | s[38] >>> 24; b8 = s[48] << 14 | s[49] >>> 18; b9 = s[49] << 14 | s[48] >>> 18; - + s[0] = b0 ^ ~b2 & b4; s[1] = b1 ^ ~b3 & b5; s[10] = b10 ^ ~b12 & b14; @@ -25422,12 +25422,12 @@ s[39] = b39 ^ ~b31 & b33; s[48] = b48 ^ ~b40 & b42; s[49] = b49 ^ ~b41 & b43; - + s[0] ^= RC[n]; s[1] ^= RC[n + 1]; } }; - + var keccak = function keccak(bits) { return function (str) { var msg; @@ -25442,7 +25442,7 @@ return update(Keccak(bits, bits), msg); }; }; - + module.exports = { keccak256: keccak(256), keccak512: keccak(512), @@ -25452,19 +25452,19 @@ },{}],135:[function(require,module,exports){ const extend = require('xtend') const createRandomId = require('json-rpc-random-id')() - + module.exports = EthQuery - - + + function EthQuery(provider){ const self = this self.currentProvider = provider } - + // // base queries // - + // default block EthQuery.prototype.getBalance = generateFnWithDefaultBlockFor(2, 'eth_getBalance') EthQuery.prototype.getCode = generateFnWithDefaultBlockFor(2, 'eth_getCode') @@ -25510,9 +25510,9 @@ EthQuery.prototype.getWork = generateFnFor('eth_getWork') EthQuery.prototype.submitWork = generateFnFor('eth_submitWork') EthQuery.prototype.submitHashrate = generateFnFor('eth_submitHashrate') - + // network level - + EthQuery.prototype.sendAsync = function(opts, cb){ const self = this self.currentProvider.sendAsync(createPayload(opts), function(err, response){ @@ -25521,9 +25521,9 @@ cb(null, response.result) }) } - + // util - + function generateFnFor(methodName){ return function(){ const self = this @@ -25535,7 +25535,7 @@ }, cb) } } - + function generateFnWithDefaultBlockFor(argCount, methodName){ return function(){ const self = this @@ -25549,7 +25549,7 @@ }, cb) } } - + function createPayload(data){ return extend({ // defaults @@ -25559,13 +25559,13 @@ // user-specified }, data) } - + },{"json-rpc-random-id":191,"xtend":423}],136:[function(require,module,exports){ const ethUtil = require('ethereumjs-util') const ethAbi = require('ethereumjs-abi') - + module.exports = { - + concatSig: function (v, r, s) { const rSig = ethUtil.fromSigned(r) const sSig = ethUtil.fromSigned(s) @@ -25575,24 +25575,24 @@ const vStr = ethUtil.stripHexPrefix(ethUtil.intToHex(vSig)) return ethUtil.addHexPrefix(rStr.concat(sStr, vStr)).toString('hex') }, - + normalize: function (input) { if (!input) return - + if (typeof input === 'number') { const buffer = ethUtil.toBuffer(input) input = ethUtil.bufferToHex(buffer) } - + if (typeof input !== 'string') { var msg = 'eth-sig-util.normalize() requires hex string or integer input.' msg += ' received ' + (typeof input) + ': ' + input throw new Error(msg) } - + return ethUtil.addHexPrefix(input.toLowerCase()) }, - + personalSign: function (privateKey, msgParams) { var message = ethUtil.toBuffer(msgParams.data) var msgHash = ethUtil.hashPersonalMessage(message) @@ -25600,39 +25600,39 @@ var serialized = ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s)) return serialized }, - + recoverPersonalSignature: function (msgParams) { const publicKey = getPublicKeyFor(msgParams) const sender = ethUtil.publicToAddress(publicKey) const senderHex = ethUtil.bufferToHex(sender) return senderHex }, - + extractPublicKey: function (msgParams) { const publicKey = getPublicKeyFor(msgParams) return '0x' + publicKey.toString('hex') }, - + typedSignatureHash: function (typedData) { const hashBuffer = typedSignatureHash(typedData) return ethUtil.bufferToHex(hashBuffer) }, - + signTypedData: function (privateKey, msgParams) { const msgHash = typedSignatureHash(msgParams.data) const sig = ethUtil.ecsign(msgHash, privateKey) return ethUtil.bufferToHex(this.concatSig(sig.v, sig.r, sig.s)) }, - + recoverTypedSignature: function (msgParams) { const msgHash = typedSignatureHash(msgParams.data) const publicKey = recoverPublicKey(msgHash, msgParams.sig) const sender = ethUtil.publicToAddress(publicKey) return ethUtil.bufferToHex(sender) } - + } - + /** * @param typedData - Array of data along with types, as per EIP712. * @returns Buffer @@ -25640,7 +25640,7 @@ function typedSignatureHash(typedData) { const error = new Error('Expect argument to be non-empty array') if (typeof typedData !== 'object' || !typedData.length) throw error - + const data = typedData.map(function (e) { return e.type === 'bytes' ? ethUtil.toBuffer(e.value) : e.value }) @@ -25649,7 +25649,7 @@ if (!e.name) throw error return e.type + ' ' + e.name }) - + return ethAbi.soliditySHA3( ['bytes32', 'bytes32'], [ @@ -25658,20 +25658,20 @@ ] ) } - + function recoverPublicKey(hash, sig) { const signature = ethUtil.toBuffer(sig) const sigParams = ethUtil.fromRpcSig(signature) return ethUtil.ecrecover(hash, sigParams.v, sigParams.r, sigParams.s) } - + function getPublicKeyFor (msgParams) { const message = ethUtil.toBuffer(msgParams.data) const msgHash = ethUtil.hashPersonalMessage(message) return recoverPublicKey(msgHash, msgParams.sig) } - - + + function padWithZeroes (number, length) { var myString = '' + number while (myString.length < length) { @@ -25679,7 +25679,7 @@ } return myString } - + },{"ethereumjs-abi":138,"ethereumjs-util":141}],137:[function(require,module,exports){ module.exports={ "genesisGasLimit": { @@ -25742,7 +25742,7 @@ "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." @@ -25755,7 +25755,7 @@ "v": 10, "d": "Times ceil(log256(exponent)) for the EXP instruction." }, - + "sha3Gas": { "v": 30, "d": "Once per SHA3 operation." @@ -25784,7 +25784,7 @@ "v": 1, "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero." }, - + "logGas": { "v": 375, "d": "Per LOG* operation." @@ -25797,12 +25797,12 @@ "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." @@ -25819,12 +25819,12 @@ "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." @@ -25833,7 +25833,7 @@ "v": 512, "d": "Divisor for the quadratic particle of the memory cost equation." }, - + "createDataGas": { "v": 200, "d": "" @@ -25854,12 +25854,12 @@ "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": "" @@ -25916,18 +25916,18 @@ "v": 2 } } - + },{}],138:[function(require,module,exports){ module.exports = require('./lib/index.js') - + },{"./lib/index.js":139}],139:[function(require,module,exports){ (function (Buffer){ const utils = require('ethereumjs-util') const BN = require('bn.js') - + var ABI = function () { } - + // Convert from short to canonical names // FIXME: optimise or make this nicer? function elementaryName (name) { @@ -25950,28 +25950,28 @@ } return name } - + ABI.eventID = function (name, types) { // FIXME: use node.js util.format? var sig = name + '(' + types.map(elementaryName).join(',') + ')' return utils.sha3(new Buffer(sig)) } - + ABI.methodID = function (name, types) { return ABI.eventID(name, types).slice(0, 4) } - + // Parse N from type function parseTypeN (type) { return parseInt(/^\D+(\d+)$/.exec(type)[1], 10) } - + // Parse N,M from typex function parseTypeNxM (type) { var tmp = /^\D+(\d+)x(\d+)$/.exec(type) return [ parseInt(tmp[1], 10), parseInt(tmp[2], 10) ] } - + // Parse N in type[] where "type" can itself be an array type. function parseTypeArray (type) { var tmp = type.match(/(.*)\[(.*?)\]$/) @@ -25980,7 +25980,7 @@ } return null } - + function parseNumber (arg) { var type = typeof arg if (type === 'string') { @@ -25998,7 +25998,7 @@ throw new Error('Argument is not a number') } } - + // someMethod(bytes,uint) // someMethod(bytes,uint):(boolean) function parseSignature (sig) { @@ -26006,9 +26006,9 @@ if (tmp.length !== 3) { throw new Error('Invalid method signature') } - + var args = /^(.+)\):\((.+)$/.exec(tmp[2]) - + if (args !== null && args.length === 3) { return { method: tmp[1], @@ -26022,12 +26022,12 @@ } } } - + // Encodes a single item (can be dynamic array) // @returns: Buffer function encodeSingle (type, arg) { var size, num, ret, i - + if (type === 'address') { return encodeSingle('uint160', parseNumber(arg)) } else if (type === 'bool') { @@ -26059,68 +26059,68 @@ return Buffer.concat(ret) } else if (type === 'bytes') { arg = new Buffer(arg) - + ret = Buffer.concat([ encodeSingle('uint256', arg.length), arg ]) - + if ((arg.length % 32) !== 0) { ret = Buffer.concat([ ret, utils.zeros(32 - (arg.length % 32)) ]) } - + return ret } else if (type.startsWith('bytes')) { size = parseTypeN(type) if (size < 1 || size > 32) { throw new Error('Invalid bytes width: ' + size) } - + return utils.setLengthRight(arg, 32) } else if (type.startsWith('uint')) { size = parseTypeN(type) if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid uint width: ' + size) } - + num = parseNumber(arg) if (num.bitLength() > size) { throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()) } - + if (num < 0) { throw new Error('Supplied uint is negative') } - + return num.toArrayLike(Buffer, 'be', 32) } else if (type.startsWith('int')) { size = parseTypeN(type) if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid int width: ' + size) } - + num = parseNumber(arg) if (num.bitLength() > size) { throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()) } - + return num.toTwos(256).toArrayLike(Buffer, 'be', 32) } else if (type.startsWith('ufixed')) { size = parseTypeNxM(type) - + num = parseNumber(arg) - + if (num < 0) { throw new Error('Supplied ufixed is negative') } - + return encodeSingle('uint256', num.mul(new BN(2).pow(new BN(size[1])))) } else if (type.startsWith('fixed')) { size = parseTypeNxM(type) - + return encodeSingle('int256', parseNumber(arg).mul(new BN(2).pow(new BN(size[1])))) } - + throw new Error('Unsupported or invalid type: ' + type) } - + // Decodes a single item (can be dynamic array) // @returns: array // FIXME: this method will need a lot of attention at checking limits and validation @@ -26129,7 +26129,7 @@ parsedType = parseType(parsedType) } var size, num, ret, i - + if (parsedType.name === 'address') { return decodeSingle(parsedType.rawType, data, offset).toArrayLike(Buffer, 'be', 20).toString('hex') } else if (parsedType.name === 'bool') { @@ -26142,7 +26142,7 @@ // NOTE: we catch here all calls to arrays, that simplifies the rest ret = [] size = parsedType.size - + if (parsedType.size === 'dynamic') { offset = decodeSingle('uint256', data, offset).toNumber() size = decodeSingle('uint256', data, offset).toNumber() @@ -26171,7 +26171,7 @@ if (num.bitLength() > parsedType.size) { throw new Error('Decoded uint exceeds width: ' + parsedType.size + ' vs ' + num.bitLength()) } - + return num } else if (parsedType.name.startsWith('ufixed')) { size = new BN(2).pow(new BN(parsedType.size[1])) @@ -26190,7 +26190,7 @@ } throw new Error('Unsupported or invalid type: ' + parsedType.name) } - + // Parse the given type // @returns: {} containing the type itself, memory usage and (including size and subArray if applicable) function parseType (type) { @@ -26226,13 +26226,13 @@ name: type, memoryUsage: 32 } - + if (type.startsWith('bytes') && type !== 'bytes' || type.startsWith('uint') || type.startsWith('int')) { ret.size = parseTypeN(type) } else if (type.startsWith('ufixed') || type.startsWith('fixed')) { ret.size = parseTypeNxM(type) } - + if (type.startsWith('bytes') && type !== 'bytes' && (ret.size < 1 || ret.size > 32)) { throw new Error('Invalid bytes width: ' + ret.size) } @@ -26242,31 +26242,31 @@ return ret } } - + // Is a type dynamic? function isDynamic (type) { // FIXME: handle all types? I don't think anything is missing now return (type === 'string') || (type === 'bytes') || (parseTypeArray(type) === 'dynamic') } - + // Is a type an array? function isArray (type) { return type.lastIndexOf(']') === type.length - 1 } - + // Encode a method/event with arguments // @types an array of string type names // @args an array of the appropriate values ABI.rawEncode = function (types, values) { var output = [] var data = [] - + var headLength = 0 - + types.forEach(function (type) { if (isArray(type)) { var size = parseTypeArray(type) - + if (size !== 'dynamic') { headLength += 32 * size } else { @@ -26276,12 +26276,12 @@ headLength += 32 } }) - + for (var i = 0; i < types.length; i++) { var type = elementaryName(types[i]) var value = values[i] var cur = encodeSingle(type, value) - + // Use the head/tail method for storing dynamic data if (isDynamic(type)) { output.push(encodeSingle('uint256', headLength)) @@ -26291,10 +26291,10 @@ output.push(cur) } } - + return Buffer.concat(output.concat(data)) } - + ABI.rawDecode = function (types, data) { var ret = [] data = new Buffer(data) @@ -26308,30 +26308,30 @@ } return ret } - + ABI.simpleEncode = function (method) { var args = Array.prototype.slice.call(arguments).slice(1) var sig = parseSignature(method) - + // FIXME: validate/convert arguments if (args.length !== sig.args.length) { throw new Error('Argument count mismatch') } - + return Buffer.concat([ ABI.methodID(sig.method, sig.args), ABI.rawEncode(sig.args, args) ]) } - + ABI.simpleDecode = function (method, data) { var sig = parseSignature(method) - + // FIXME: validate/convert arguments if (!sig.retargs) { throw new Error('No return values in method') } - + return ABI.rawDecode(sig.retargs, data) } - + function stringify (type, value) { if (type.startsWith('address') || type.startsWith('bytes')) { return '0x' + value.toString('hex') @@ -26339,14 +26339,14 @@ return value.toString() } } - + ABI.stringify = function (types, values) { var ret = [] - + for (var i in types) { var type = types[i] var value = values[i] - + // if it is an array type, concat the items if (/^[^\[]+\[.*\]$/.test(type)) { value = value.map(function (item) { @@ -26355,25 +26355,25 @@ } else { value = stringify(type, value) } - + ret.push(value) } - + return ret } - + ABI.solidityPack = function (types, values) { if (types.length !== values.length) { throw new Error('Number of types are not matching the values') } - + var size, num var ret = [] - + for (var i = 0; i < types.length; i++) { var type = elementaryName(types[i]) var value = values[i] - + if (type === 'bytes') { ret.push(value) } else if (type === 'string') { @@ -26387,65 +26387,65 @@ if (size < 1 || size > 32) { throw new Error('Invalid bytes width: ' + size) } - + ret.push(utils.setLengthRight(value, size)) } else if (type.startsWith('uint')) { size = parseTypeN(type) if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid uint width: ' + size) } - + num = parseNumber(value) if (num.bitLength() > size) { throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()) } - + ret.push(num.toArrayLike(Buffer, 'be', size / 8)) } else if (type.startsWith('int')) { size = parseTypeN(type) if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid int width: ' + size) } - + num = parseNumber(value) if (num.bitLength() > size) { throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()) } - + ret.push(num.toTwos(size).toArrayLike(Buffer, 'be', size / 8)) } else { // FIXME: support all other types throw new Error('Unsupported or invalid type: ' + type) } } - + return Buffer.concat(ret) } - + ABI.soliditySHA3 = function (types, values) { return utils.sha3(ABI.solidityPack(types, values)) } - + ABI.soliditySHA256 = function (types, values) { return utils.sha256(ABI.solidityPack(types, values)) } - + ABI.solidityRIPEMD160 = function (types, values) { return utils.ripemd160(ABI.solidityPack(types, values), true) } - + // Serpent's users are familiar with this encoding // - s: string // - b: bytes // - b: bytes // - i: int256 // - a: int256[] - + function isNumeric (c) { // FIXME: is this correct? Seems to work return (c >= '0') && (c <= '9') } - + // For a "documentation" refer to https://github.com/ethereum/serpent/blob/develop/preprocess.cpp ABI.fromSerpent = function (sig) { var ret = [] @@ -26472,7 +26472,7 @@ } return ret } - + ABI.toSerpent = function (types) { var ret = [] for (var i = 0; i < types.length; i++) { @@ -26491,23 +26491,23 @@ } return ret.join('') } - + module.exports = ABI - + }).call(this,require("buffer").Buffer) },{"bn.js":53,"buffer":84,"ethereumjs-util":141}],140:[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. * @@ -26544,11 +26544,11 @@ * @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 = [{ @@ -26599,7 +26599,7 @@ allowLess: true, default: new Buffer([]) }]; - + /** * Returns the rlp encoding of the transaction * @method serialize @@ -26609,7 +26609,7 @@ */ // attached serialize ethUtil.defineProperties(this, fields, data); - + /** * @property {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters. * @name from @@ -26620,42 +26620,42 @@ 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; @@ -26671,27 +26671,27 @@ 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; @@ -26700,33 +26700,33 @@ 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) { @@ -26736,16 +26736,16 @@ } 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); @@ -26754,13 +26754,13 @@ } 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); @@ -26769,13 +26769,13 @@ } 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()) { @@ -26783,51 +26783,51 @@ } 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":84,"ethereum-common/params.json":137,"ethereumjs-util":141}],141:[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'); @@ -26836,79 +26836,79 @@ 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 @@ -26918,7 +26918,7 @@ exports.zeros = function (bytes) { return Buffer.allocUnsafe(bytes).fill(0); }; - + /** * Returns a zero address * @method zeroAddress @@ -26929,7 +26929,7 @@ 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. @@ -26956,7 +26956,7 @@ 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. @@ -26967,7 +26967,7 @@ 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 @@ -27011,7 +27011,7 @@ } return v; }; - + /** * Converts a `Buffer` to a `Number` * @param {Buffer} buf @@ -27021,7 +27021,7 @@ exports.bufferToInt = function (buf) { return new BN(exports.toBuffer(buf)).toNumber(); }; - + /** * Converts a `Buffer` into a hex `String` * @param {Buffer} buf @@ -27031,7 +27031,7 @@ 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 @@ -27040,7 +27040,7 @@ 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 @@ -27049,7 +27049,7 @@ 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 @@ -27059,10 +27059,10 @@ 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 @@ -27071,7 +27071,7 @@ 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 @@ -27079,7 +27079,7 @@ * @return {Buffer} */ exports.sha3 = exports.keccak; - + /** * Creates SHA256 hash of the input * @param {Buffer|Array|String|Number} a the input data @@ -27089,7 +27089,7 @@ 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 @@ -27105,7 +27105,7 @@ return hash; } }; - + /** * Creates SHA-3 hash of the RLP encoded version of the input * @param {Buffer|Array|String|Number} a the input data @@ -27114,7 +27114,7 @@ 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 @@ -27123,7 +27123,7 @@ 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. @@ -27136,14 +27136,14 @@ // 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. @@ -27160,7 +27160,7 @@ // 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 @@ -27171,7 +27171,7 @@ // 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 @@ -27184,7 +27184,7 @@ } return publicKey; }; - + /** * ECDSA sign * @param {Buffer} msgHash @@ -27193,14 +27193,14 @@ */ 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` @@ -27213,7 +27213,7 @@ 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 @@ -27231,7 +27231,7 @@ 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 @@ -27244,12 +27244,12 @@ 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 @@ -27258,25 +27258,25 @@ */ 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 @@ -27285,7 +27285,7 @@ exports.privateToAddress = function (privateKey) { return exports.publicToAddress(privateToPublic(privateKey)); }; - + /** * Checks if the address is a valid. Accepts checksummed addresses too * @param {String} address @@ -27295,7 +27295,7 @@ return (/^0x[0-9a-fA-F]{40}$/.test(address) ); }; - + /** * Checks if a given address is a zero address * @method isZeroAddress @@ -27306,7 +27306,7 @@ var zeroAddress = exports.zeroAddress(); return zeroAddress === exports.addHexPrefix(address); }; - + /** * Returns a checksummed address * @param {String} address @@ -27316,7 +27316,7 @@ 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(); @@ -27324,10 +27324,10 @@ ret += address[i]; } } - + return ret; }; - + /** * Checks if the address is a valid checksummed address * @param {Buffer} address @@ -27336,7 +27336,7 @@ 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 @@ -27346,7 +27346,7 @@ 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 @@ -27354,11 +27354,11 @@ } 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 @@ -27368,7 +27368,7 @@ 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 @@ -27378,10 +27378,10 @@ if (typeof str !== 'string') { return str; } - + return exports.isHexPrefixed(str) ? str : '0x' + str; }; - + /** * Validate ECDSA signature * @method isValidSignature @@ -27391,33 +27391,33 @@ * @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 @@ -27434,7 +27434,7 @@ 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 @@ -27448,7 +27448,7 @@ exports.defineProperties = function (self, fields, data) { self.raw = []; self._fields = []; - + // attach the `toJSON` self.toJSON = function (label) { if (label) { @@ -27460,11 +27460,11 @@ } 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() { @@ -27472,32 +27472,32 @@ } 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, { @@ -27508,22 +27508,22 @@ }); } }); - + // 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); @@ -28459,7 +28459,7 @@ }()); exports.AbiCoder = AbiCoder; exports.defaultAbiCoder = new AbiCoder(); - + },{"./address":144,"./bignumber":145,"./bytes":146,"./errors":147,"./properties":149,"./utf8":152}],144:[function(require,module,exports){ 'use strict'; var __importDefault = (this && this.__importDefault) || function (mod) { @@ -28585,7 +28585,7 @@ ])).substring(26)); } exports.getContractAddress = getContractAddress; - + },{"./bytes":146,"./errors":147,"./keccak256":148,"./rlp":150,"bn.js":53}],145:[function(require,module,exports){ 'use strict'; var __extends = (this && this.__extends) || (function () { @@ -28779,7 +28779,7 @@ exports.ConstantOne = bigNumberify(1); exports.ConstantTwo = bigNumberify(2); exports.ConstantWeiPerEther = bigNumberify('1000000000000000000'); - + },{"./bytes":146,"./errors":147,"./properties":149,"./types":151,"bn.js":53}],146:[function(require,module,exports){ "use strict"; /** @@ -29043,7 +29043,7 @@ ])); } exports.joinSignature = joinSignature; - + },{"./errors":147}],147:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); @@ -29147,7 +29147,7 @@ _permanentCensorErrors = !!permanent; } exports.setCensorship = setCensorship; - + },{}],148:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); @@ -29157,7 +29157,7 @@ return '0x' + sha3.keccak_256(bytes_1.arrayify(data)); } exports.keccak256 = keccak256; - + },{"./bytes":146,"js-sha3":142}],149:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); @@ -29209,7 +29209,7 @@ return JSON.parse(JSON.stringify(object)); } exports.jsonCopy = jsonCopy; - + },{}],150:[function(require,module,exports){ "use strict"; //See: https://github.com/ethereum/wiki/wiki/RLP @@ -29327,7 +29327,7 @@ return decoded.result; } exports.decode = decode; - + },{"./bytes":146}],151:[function(require,module,exports){ "use strict"; /////////////////////////////// @@ -29384,7 +29384,7 @@ return HDNode; }()); exports.HDNode = HDNode; - + },{}],152:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); @@ -29509,16 +29509,16 @@ return result; } exports.toUtf8String = toUtf8String; - + },{"./bytes":146}],153:[function(require,module,exports){ 'use strict'; - + var BN = require('bn.js'); var numberToBN = require('number-to-bn'); - + var zero = new BN(0); var negative1 = new BN(-1); - + // complete ethereum unit map var unitMap = { 'noether': '0', // eslint-disable-line @@ -29548,7 +29548,7 @@ 'mether': '1000000000000000000000000', // eslint-disable-line 'gether': '1000000000000000000000000000', // eslint-disable-line 'tether': '1000000000000000000000000000000' }; - + /** * Returns value of unit in Wei * @@ -29560,14 +29560,14 @@ function getValueOfUnit(unitInput) { var unit = unitInput ? unitInput.toLowerCase() : 'ether'; var unitValue = unitMap[unit]; // eslint-disable-line - + if (typeof unitValue !== 'string') { throw new Error('[ethjs-unit] the unit provided ' + unitInput + ' doesn\'t exists, please use the one of the following units ' + JSON.stringify(unitMap, null, 2)); } - + return new BN(unitValue, 10); } - + function numberToString(arg) { if (typeof arg === 'string') { if (!arg.match(/^-?[0-9.]+$/)) { @@ -29586,67 +29586,67 @@ } throw new Error('while converting number to string, invalid number value \'' + arg + '\' type ' + typeof arg + '.'); } - + function fromWei(weiInput, unit, optionsInput) { var wei = numberToBN(weiInput); // eslint-disable-line var negative = wei.lt(zero); // eslint-disable-line var base = getValueOfUnit(unit); var baseLength = unitMap[unit].length - 1 || 1; var options = optionsInput || {}; - + if (negative) { wei = wei.mul(negative1); } - + var fraction = wei.mod(base).toString(10); // eslint-disable-line - + while (fraction.length < baseLength) { fraction = '0' + fraction; } - + if (!options.pad) { fraction = fraction.match(/^([0-9]*[1-9]|0)(0*)/)[1]; } - + var whole = wei.div(base).toString(10); // eslint-disable-line - + if (options.commify) { whole = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ','); } - + var value = '' + whole + (fraction == '0' ? '' : '.' + fraction); // eslint-disable-line - + if (negative) { value = '-' + value; } - + return value; } - + function toWei(etherInput, unit) { var ether = numberToString(etherInput); // eslint-disable-line var base = getValueOfUnit(unit); var baseLength = unitMap[unit].length - 1 || 1; - + // Is it negative? var negative = ether.substring(0, 1) === '-'; // eslint-disable-line if (negative) { ether = ether.substring(1); } - + if (ether === '.') { throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, invalid value'); } - + // Split it into a whole and fractional part var comps = ether.split('.'); // eslint-disable-line if (comps.length > 2) { throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal points'); } - + var whole = comps[0], fraction = comps[1]; // eslint-disable-line - + if (!whole) { whole = '0'; } @@ -29656,22 +29656,22 @@ if (fraction.length > baseLength) { throw new Error('[ethjs-unit] while converting number ' + etherInput + ' to wei, too many decimal places'); } - + while (fraction.length < baseLength) { fraction += '0'; } - + whole = new BN(whole); fraction = new BN(fraction); var wei = whole.mul(base).add(fraction); // eslint-disable-line - + if (negative) { wei = wei.mul(negative1); } - + return new BN(wei.toString(10), 10); } - + module.exports = { unitMap: unitMap, numberToString: numberToString, @@ -29682,12 +29682,12 @@ },{"bn.js":154,"number-to-bn":237}],154:[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) { @@ -29697,27 +29697,27 @@ 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'); } } @@ -29726,72 +29726,72 @@ } else { exports.BN = BN; } - + BN.BN = BN; BN.wordSize = 26; - + var Buffer; try { Buffer = require('buf' + 'fer').Buffer; } catch (e) { } - + BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } - + return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; - + BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; - + BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; - + BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } - + if (typeof number === 'object') { return this._initArray(number, base, endian); } - + if (base === 'hex') { base = 16; } assert(base === (base | 0) && base >= 2 && base <= 36); - + number = number.toString().replace(/\s+/g, ''); var start = 0; if (number[0] === '-') { start++; } - + if (base === 16) { this._parseHex(number, start); } else { this._parseBase(number, base, start); } - + if (number[0] === '-') { this.negative = 1; } - + this.strip(); - + if (endian !== 'le') return; - + this._initArray(this.toArray(), base, endian); }; - + BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; @@ -29815,13 +29815,13 @@ ]; 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'); @@ -29830,13 +29830,13 @@ 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') { @@ -29864,23 +29864,23 @@ } 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; @@ -29888,7 +29888,7 @@ } 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); @@ -29896,7 +29896,7 @@ 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; @@ -29918,23 +29918,23 @@ } 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; @@ -29942,27 +29942,27 @@ } 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; @@ -29970,15 +29970,15 @@ 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; @@ -29987,7 +29987,7 @@ } } }; - + BN.prototype.copy = function copy (dest) { dest.words = new Array(this.length); for (var i = 0; i < this.length; i++) { @@ -29997,20 +29997,20 @@ 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) { @@ -30018,7 +30018,7 @@ } return this._normSign(); }; - + BN.prototype._normSign = function _normSign () { // -0 = 0 if (this.length === 1 && this.words[0] === 0) { @@ -30026,17 +30026,17 @@ } 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) { @@ -30058,9 +30058,9 @@ groupSizes[base] = groupSize; groupBases[base] = groupBase; } - + */ - + var zeros = [ '', '0', @@ -30089,7 +30089,7 @@ '000000000000000000000000', '0000000000000000000000000' ]; - + var groupSizes = [ 0, 0, 25, 16, 12, 11, 10, 9, 8, @@ -30098,7 +30098,7 @@ 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, @@ -30107,11 +30107,11 @@ 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 = ''; @@ -30143,7 +30143,7 @@ } 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]; @@ -30155,7 +30155,7 @@ 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 { @@ -30173,10 +30173,10 @@ } 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) { @@ -30189,30 +30189,30 @@ } 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) { @@ -30220,29 +30220,29 @@ 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); @@ -30270,11 +30270,11 @@ 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) { @@ -30298,31 +30298,31 @@ } 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]); @@ -30331,71 +30331,71 @@ } 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) @@ -30405,32 +30405,32 @@ } 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 @@ -30443,99 +30443,99 @@ 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; @@ -30543,7 +30543,7 @@ num.negative = 1; return r._normSign(); } - + // a.length > b.length var a, b; if (this.length > num.length) { @@ -30553,7 +30553,7 @@ 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; @@ -30565,7 +30565,7 @@ this.words[i] = r & 0x3ffffff; carry = r >>> 26; } - + this.length = a.length; if (carry !== 0) { this.words[this.length] = carry; @@ -30576,10 +30576,10 @@ this.words[i] = a.words[i]; } } - + return this; }; - + // Add `num` to `this` BN.prototype.add = function add (num) { var res; @@ -30594,12 +30594,12 @@ 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 @@ -30608,7 +30608,7 @@ var r = this.iadd(num); num.negative = 1; return r._normSign(); - + // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; @@ -30616,10 +30616,10 @@ 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; @@ -30627,7 +30627,7 @@ this.words[0] = 0; return this; } - + // a > b var a, b; if (cmp > 0) { @@ -30637,7 +30637,7 @@ 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; @@ -30649,43 +30649,43 @@ 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 @@ -30708,10 +30708,10 @@ } 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). @@ -30783,7 +30783,7 @@ var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; - + out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ @@ -31287,16 +31287,16 @@ } 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++) { @@ -31311,13 +31311,13 @@ 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; } @@ -31330,15 +31330,15 @@ } 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; @@ -31351,41 +31351,41 @@ } 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) { @@ -31394,42 +31394,42 @@ 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; } @@ -31437,7 +31437,7 @@ } } }; - + FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; @@ -31445,135 +31445,135 @@ 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++) { @@ -31585,51 +31585,51 @@ 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); @@ -31637,44 +31637,44 @@ 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 @@ -31686,15 +31686,15 @@ } 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++) { @@ -31702,7 +31702,7 @@ } maskedWords.length = s; } - + if (s === 0) { // No-op, we should not move anything at all } else if (this.length > s) { @@ -31714,103 +31714,103 @@ 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) { @@ -31818,20 +31818,20 @@ 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; @@ -31842,25 +31842,25 @@ } } 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; @@ -31871,34 +31871,34 @@ 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++) { @@ -31913,9 +31913,9 @@ carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } - + if (carry === 0) return this.strip(); - + // Subtraction overflow assert(carry === -1); carry = 0; @@ -31925,16 +31925,16 @@ 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); @@ -31944,11 +31944,11 @@ 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; @@ -31957,7 +31957,7 @@ q.words[i] = 0; } } - + var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; @@ -31965,15 +31965,15 @@ 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--; @@ -31991,84 +31991,84 @@ 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 { @@ -32076,7 +32076,7 @@ mod: this }; } - + // Very short reduction if (num.length === 1) { if (mode === 'div') { @@ -32085,119 +32085,119 @@ 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) { @@ -32207,12 +32207,12 @@ 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); @@ -32221,12 +32221,12 @@ C.iadd(yp); D.isub(xp); } - + C.iushrn(1); D.iushrn(1); } } - + if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); @@ -32237,35 +32237,35 @@ 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) { @@ -32274,11 +32274,11 @@ 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); @@ -32286,11 +32286,11 @@ if (x2.isOdd()) { x2.iadd(delta); } - + x2.iushrn(1); } } - + if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); @@ -32299,36 +32299,36 @@ 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); @@ -32336,7 +32336,7 @@ 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` @@ -32346,45 +32346,45 @@ } 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++) { @@ -32400,19 +32400,19 @@ } 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; @@ -32420,16 +32420,16 @@ 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` @@ -32437,23 +32437,23 @@ 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; @@ -32464,47 +32464,47 @@ } 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. @@ -32512,103 +32512,103 @@ 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, @@ -32616,7 +32616,7 @@ p192: null, p25519: null }; - + // Pseudo-Mersenne prime function MPrime (name, p) { // P = 2 ^ N - K @@ -32624,29 +32624,29 @@ 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; @@ -32656,18 +32656,18 @@ } 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, @@ -32675,27 +32675,27 @@ '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); @@ -32709,13 +32709,13 @@ 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++) { @@ -32724,7 +32724,7 @@ num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 0); } - + // Fast length reduction if (num.words[num.length - 1] === 0) { num.length--; @@ -32734,7 +32734,7 @@ } return num; }; - + function P224 () { MPrime.call( this, @@ -32742,7 +32742,7 @@ 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); } inherits(P224, MPrime); - + function P192 () { MPrime.call( this, @@ -32750,7 +32750,7 @@ 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); } inherits(P192, MPrime); - + function P25519 () { // 2 ^ 255 - 19 MPrime.call( @@ -32759,7 +32759,7 @@ '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); } inherits(P25519, MPrime); - + P25519.prototype.imulK = function imulK (num) { // K = 0x13 var carry = 0; @@ -32767,7 +32767,7 @@ var hi = (num.words[i] | 0) * 0x13 + carry; var lo = hi & 0x3ffffff; hi >>>= 26; - + num.words[i] = lo; carry = hi; } @@ -32776,12 +32776,12 @@ } 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(); @@ -32795,10 +32795,10 @@ throw new Error('Unknown prime ' + name); } primes[name] = prime; - + return prime; }; - + // // Base reduction engine // @@ -32813,106 +32813,106 @@ 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) @@ -32923,20 +32923,20 @@ 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); @@ -32948,16 +32948,16 @@ } 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) { @@ -32967,11 +32967,11 @@ return this.imod(inv); } }; - + Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1); if (num.cmpn(1) === 0) return a.clone(); - + var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); @@ -32979,7 +32979,7 @@ 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; @@ -32987,7 +32987,7 @@ 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--) { @@ -32995,99 +32995,99 @@ 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); @@ -33097,24 +33097,24 @@ } 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); - + },{}],155:[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 @@ -33122,18 +33122,18 @@ */ 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 @@ -33141,10 +33141,10 @@ */ function intToHex(i) { var hex = i.toString(16); // eslint-disable-line - + return '0x' + hex; } - + /** * Converts an `Number` to a `Buffer` * @param {Number} i @@ -33152,10 +33152,10 @@ */ 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 @@ -33165,10 +33165,10 @@ 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. @@ -33185,12 +33185,12 @@ 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 * @@ -33200,10 +33200,10 @@ */ 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 * @@ -33215,19 +33215,19 @@ 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 * @@ -33238,10 +33238,10 @@ */ 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 * @@ -33258,10 +33258,10 @@ 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] * @@ -33278,9 +33278,9 @@ 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 @@ -33291,10 +33291,10 @@ } result.push(value); } - + return result; } - + /** * Is the string a hex string. * @@ -33307,14 +33307,14 @@ 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, @@ -33333,7 +33333,7 @@ }).call(this,require("buffer").Buffer) },{"buffer":84,"is-hex-prefixed":185,"strip-hex-prefix":318}],156:[function(require,module,exports){ 'use strict'; - + // // We store our EE objects in a plain object whose properties are event names. // If `Object.create(null)` is not supported we prefix the event names with a @@ -33343,7 +33343,7 @@ // is an ES6 Symbol. // var prefix = typeof Object.create !== 'function' ? '~' : false; - + /** * Representation of a single EventEmitter function. * @@ -33357,7 +33357,7 @@ this.context = context; this.once = once || false; } - + /** * Minimal EventEmitter interface that is molded against the Node.js * EventEmitter interface. @@ -33366,7 +33366,7 @@ * @api public */ function EventEmitter() { /* Nothing to set */ } - + /** * Holds the assigned EventEmitters by name. * @@ -33374,7 +33374,7 @@ * @private */ EventEmitter.prototype._events = undefined; - + /** * Return a list of assigned event listeners. * @@ -33386,18 +33386,18 @@ EventEmitter.prototype.listeners = function listeners(event, exists) { var evt = prefix ? prefix + event : event , available = this._events && this._events[evt]; - + if (exists) return !!available; if (!available) return []; if (available.fn) return [available.fn]; - + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { ee[i] = available[i].fn; } - + return ee; }; - + /** * Emit an event to all registered event listeners. * @@ -33407,17 +33407,17 @@ */ EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { var evt = prefix ? prefix + event : event; - + if (!this._events || !this._events[evt]) return false; - + var listeners = this._events[evt] , len = arguments.length , args , i; - + if ('function' === typeof listeners.fn) { if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - + switch (len) { case 1: return listeners.fn.call(listeners.context), true; case 2: return listeners.fn.call(listeners.context, a1), true; @@ -33426,19 +33426,19 @@ case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; } - + for (i = 1, args = new Array(len -1); i < len; i++) { args[i - 1] = arguments[i]; } - + listeners.fn.apply(listeners.context, args); } else { var length = listeners.length , j; - + for (i = 0; i < length; i++) { if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - + switch (len) { case 1: listeners[i].fn.call(listeners[i].context); break; case 2: listeners[i].fn.call(listeners[i].context, a1); break; @@ -33447,15 +33447,15 @@ if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { args[j - 1] = arguments[j]; } - + listeners[i].fn.apply(listeners[i].context, args); } } } - + return true; }; - + /** * Register a new EventListener for the given event. * @@ -33467,7 +33467,7 @@ EventEmitter.prototype.on = function on(event, fn, context) { var listener = new EE(fn, context || this) , evt = prefix ? prefix + event : event; - + if (!this._events) this._events = prefix ? {} : Object.create(null); if (!this._events[evt]) this._events[evt] = listener; else { @@ -33476,10 +33476,10 @@ this._events[evt], listener ]; } - + return this; }; - + /** * Add an EventListener that's only called once. * @@ -33491,7 +33491,7 @@ EventEmitter.prototype.once = function once(event, fn, context) { var listener = new EE(fn, context || this, true) , evt = prefix ? prefix + event : event; - + if (!this._events) this._events = prefix ? {} : Object.create(null); if (!this._events[evt]) this._events[evt] = listener; else { @@ -33500,10 +33500,10 @@ this._events[evt], listener ]; } - + return this; }; - + /** * Remove event listeners. * @@ -33515,12 +33515,12 @@ */ EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { var evt = prefix ? prefix + event : event; - + if (!this._events || !this._events[evt]) return this; - + var listeners = this._events[evt] , events = []; - + if (fn) { if (listeners.fn) { if ( @@ -33542,7 +33542,7 @@ } } } - + // // Reset the array, or remove it completely if we have no more listeners. // @@ -33551,10 +33551,10 @@ } else { delete this._events[evt]; } - + return this; }; - + /** * Remove all listeners or only the listeners for the specified event. * @@ -33563,38 +33563,38 @@ */ EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { if (!this._events) return this; - + if (event) delete this._events[prefix ? prefix + event : event]; else this._events = prefix ? {} : Object.create(null); - + return this; }; - + // // Alias methods names because people roll like that. // EventEmitter.prototype.off = EventEmitter.prototype.removeListener; EventEmitter.prototype.addListener = EventEmitter.prototype.on; - + // // This function doesn't apply anymore. // EventEmitter.prototype.setMaxListeners = function setMaxListeners() { return this; }; - + // // Expose the prefix. // EventEmitter.prefixed = prefix; - + // // Expose the module. // if ('undefined' !== typeof module) { module.exports = EventEmitter; } - + },{}],157:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -33616,23 +33616,23 @@ // 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. - + function EventEmitter() { this._events = this._events || {}; 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. EventEmitter.defaultMaxListeners = 10; - + // 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(n) { @@ -33641,13 +33641,13 @@ this._maxListeners = n; return this; }; - + EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; - + if (!this._events) this._events = {}; - + // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || @@ -33663,12 +33663,12 @@ } } } - + handler = this._events[type]; - + if (isUndefined(handler)) return false; - + if (isFunction(handler)) { switch (arguments.length) { // fast cases @@ -33693,26 +33693,26 @@ for (i = 0; i < len; i++) listeners[i].apply(this, args); } - + return true; }; - + EventEmitter.prototype.addListener = function(type, listener) { var m; - + if (!isFunction(listener)) throw TypeError('listener must be a function'); - + if (!this._events) this._events = {}; - + // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); - + if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; @@ -33722,7 +33722,7 @@ else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; - + // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { @@ -33730,7 +33730,7 @@ } else { m = EventEmitter.defaultMaxListeners; } - + if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + @@ -33743,53 +33743,53 @@ } } } - + return this; }; - + EventEmitter.prototype.on = EventEmitter.prototype.addListener; - + EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); - + var fired = false; - + function g() { this.removeListener(type, g); - + if (!fired) { fired = true; listener.apply(this, arguments); } } - + g.listener = listener; this.on(type, g); - + return this; }; - + // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; - + if (!isFunction(listener)) throw TypeError('listener must be a function'); - + if (!this._events || !this._events[type]) return this; - + list = this._events[type]; length = list.length; position = -1; - + if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); - + } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || @@ -33798,30 +33798,30 @@ break; } } - + if (position < 0) return this; - + if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } - + if (this._events.removeListener) this.emit('removeListener', type, listener); } - + return this; }; - + EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; - + if (!this._events) return this; - + // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) @@ -33830,7 +33830,7 @@ delete this._events[type]; return this; } - + // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { @@ -33841,9 +33841,9 @@ this._events = {}; return this; } - + listeners = this._events[type]; - + if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { @@ -33852,10 +33852,10 @@ this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; - + return this; }; - + EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) @@ -33866,11 +33866,11 @@ ret = this._events[type].slice(); return ret; }; - + EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; - + if (isFunction(evlistener)) return 1; else if (evlistener) @@ -33878,31 +33878,31 @@ } return 0; }; - + EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; - + function isFunction(arg) { return typeof arg === 'function'; } - + function isNumber(arg) { return typeof arg === 'number'; } - + function isObject(arg) { return typeof arg === 'object' && arg !== null; } - + function isUndefined(arg) { return arg === void 0; } - + },{}],158:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var MD5 = require('md5.js') - + /* eslint-disable camelcase */ function EVP_BytesToKey (password, salt, keyBits, ivLen) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') @@ -33910,28 +33910,28 @@ if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') } - + var keyLen = keyBits / 8 var key = Buffer.alloc(keyLen) var iv = Buffer.alloc(ivLen || 0) var tmp = Buffer.alloc(0) - + while (keyLen > 0 || ivLen > 0) { var hash = new MD5() hash.update(tmp) hash.update(password) if (salt) hash.update(salt) tmp = hash.digest() - + var used = 0 - + if (keyLen > 0) { var keyStart = key.length - keyLen used = Math.min(keyLen, tmp.length) tmp.copy(key, keyStart, 0, used) keyLen -= used } - + if (used < tmp.length && ivLen > 0) { var ivStart = iv.length - ivLen var length = Math.min(ivLen, tmp.length - used) @@ -33939,21 +33939,21 @@ ivLen -= length } } - + tmp.fill(0) return { key: key, iv: iv } } - + module.exports = EVP_BytesToKey - + },{"md5.js":231,"safe-buffer":290}],159:[function(require,module,exports){ 'use strict'; - + var isCallable = require('is-callable'); - + var toStr = Object.prototype.toString; var hasOwnProperty = Object.prototype.hasOwnProperty; - + var forEachArray = function forEachArray(array, iterator, receiver) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { @@ -33965,7 +33965,7 @@ } } }; - + var forEachString = function forEachString(string, iterator, receiver) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. @@ -33976,7 +33976,7 @@ } } }; - + var forEachObject = function forEachObject(object, iterator, receiver) { for (var k in object) { if (hasOwnProperty.call(object, k)) { @@ -33988,17 +33988,17 @@ } } }; - + var forEach = function forEach(list, iterator, thisArg) { if (!isCallable(iterator)) { throw new TypeError('iterator must be a function'); } - + var receiver; if (arguments.length >= 3) { receiver = thisArg; } - + if (toStr.call(list) === '[object Array]') { forEachArray(list, iterator, receiver); } else if (typeof list === 'string') { @@ -34007,13 +34007,13 @@ forEachObject(list, iterator, receiver); } }; - + module.exports = forEach; - + },{"is-callable":182}],160:[function(require,module,exports){ (function (global){ var win; - + if (typeof window !== "undefined") { win = window; } else if (typeof global !== "undefined") { @@ -34023,29 +34023,29 @@ } else { win = {}; } - + module.exports = win; - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],161:[function(require,module,exports){ (function (Buffer){ 'use strict' var Transform = require('stream').Transform var inherits = require('inherits') - + function HashBase (blockSize) { Transform.call(this) - + this._block = new Buffer(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 { @@ -34054,10 +34054,10 @@ } catch (err) { error = err } - + callback(error) } - + HashBase.prototype._flush = function (callback) { var error = null try { @@ -34065,15 +34065,15 @@ } catch (err) { error = err } - + callback(error) } - + HashBase.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 = new Buffer(data, encoding || 'binary') - + // consume data var block = this._block var offset = 0 @@ -34083,46 +34083,46 @@ 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 (data) { 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) return digest } - + HashBase.prototype._digest = function () { throw new Error('_digest is not implemented') } - + module.exports = HashBase - + }).call(this,require("buffer").Buffer) },{"buffer":84,"inherits":180,"stream":311}],162:[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; @@ -34130,13 +34130,13 @@ hash.sha384 = hash.sha.sha384; hash.sha512 = hash.sha.sha512; hash.ripemd160 = hash.ripemd.ripemd160; - + },{"./hash/common":163,"./hash/hmac":164,"./hash/ripemd":165,"./hash/sha":166,"./hash/utils":173}],163:[function(require,module,exports){ 'use strict'; - + var utils = require('./utils'); var assert = require('minimalistic-assert'); - + function BlockHash() { this.pending = null; this.pendingTotal = 0; @@ -34145,12 +34145,12 @@ 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); @@ -34159,32 +34159,32 @@ 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; @@ -34193,13 +34193,13 @@ 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; @@ -34217,20 +34217,20 @@ res[i++] = 0; res[i++] = 0; res[i++] = 0; - + for (t = 8; t < this.padLength; t++) res[i++] = 0; } - + return res; }; - + },{"./utils":173,"minimalistic-assert":234}],164:[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); @@ -34239,70 +34239,70 @@ 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":173,"minimalistic-assert":234}],165:[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]; @@ -34343,14 +34343,14 @@ 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; @@ -34363,7 +34363,7 @@ else return x ^ (y | (~z)); } - + function K(j) { if (j <= 15) return 0x00000000; @@ -34376,7 +34376,7 @@ else return 0xa953fd4e; } - + function Kh(j) { if (j <= 15) return 0x50a28be6; @@ -34389,7 +34389,7 @@ 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, @@ -34397,7 +34397,7 @@ 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, @@ -34405,7 +34405,7 @@ 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, @@ -34413,7 +34413,7 @@ 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, @@ -34421,68 +34421,68 @@ 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":163,"./utils":173}],166:[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":167,"./sha/224":168,"./sha/256":169,"./sha/384":170,"./sha/512":171}],167:[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]); @@ -34492,31 +34492,31 @@ 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":163,"../utils":173,"./common":172}],168:[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, @@ -34524,12 +34524,12 @@ } 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') @@ -34537,16 +34537,16 @@ else return utils.split32(this.h.slice(0, 7), 'big'); }; - - + + },{"../utils":173,"./256":169}],169:[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; @@ -34556,9 +34556,9 @@ 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, @@ -34577,11 +34577,11 @@ 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, @@ -34592,20 +34592,20 @@ } 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]; @@ -34614,7 +34614,7 @@ 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]); @@ -34628,7 +34628,7 @@ 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); @@ -34638,25 +34638,25 @@ 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":163,"../utils":173,"./common":172,"minimalistic-assert":234}],170:[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, @@ -34670,26 +34670,26 @@ } 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":173,"./512":171}],171:[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; @@ -34701,9 +34701,9 @@ 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, @@ -34746,11 +34746,11 @@ 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]; - + function SHA512() { if (!(this instanceof SHA512)) return new SHA512(); - + BlockHash.call(this); this.h = [ 0x6a09e667, 0xf3bcc908, @@ -34766,15 +34766,15 @@ } 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]; @@ -34787,7 +34787,7 @@ 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, @@ -34800,12 +34800,12 @@ 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]; @@ -34822,7 +34822,7 @@ 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; @@ -34835,7 +34835,7 @@ 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, @@ -34848,40 +34848,40 @@ 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); @@ -34891,136 +34891,136 @@ 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":163,"../utils":173,"minimalistic-assert":234}],172:[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); @@ -35030,50 +35030,50 @@ 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":173}],173:[function(require,module,exports){ 'use strict'; - + var assert = require('minimalistic-assert'); var inherits = require('inherits'); - + exports.inherits = inherits; - + function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); @@ -35105,7 +35105,7 @@ return res; } exports.toArray = toArray; - + function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) @@ -35113,7 +35113,7 @@ return res; } exports.toHex = toHex; - + function htonl(w) { var res = (w >>> 24) | ((w >>> 8) & 0xff00) | @@ -35122,7 +35122,7 @@ return res >>> 0; } exports.htonl = htonl; - + function toHex32(msg, endian) { var res = ''; for (var i = 0; i < msg.length; i++) { @@ -35134,7 +35134,7 @@ return res; } exports.toHex32 = toHex32; - + function zero2(word) { if (word.length === 1) return '0' + word; @@ -35142,7 +35142,7 @@ return word; } exports.zero2 = zero2; - + function zero8(word) { if (word.length === 7) return '0' + word; @@ -35162,7 +35162,7 @@ return word; } exports.zero8 = zero8; - + function join32(msg, start, end, endian) { var len = end - start; assert(len % 4 === 0); @@ -35178,7 +35178,7 @@ 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) { @@ -35198,61 +35198,61 @@ 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; @@ -35262,18 +35262,18 @@ 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; @@ -35285,63 +35285,63 @@ 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":180,"minimalistic-assert":234}],174:[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'); @@ -35350,26 +35350,26 @@ 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) @@ -35380,7 +35380,7 @@ this.V = this._hmac().update(this.V).digest(); if (!seed) return; - + this.K = this._hmac() .update(this.V) .update([ 0x01 ]) @@ -35388,7 +35388,7 @@ .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') { @@ -35396,66 +35396,66 @@ 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":162,"minimalistic-assert":234,"minimalistic-crypto-utils":235}],175:[function(require,module,exports){ var http = require('http') var url = require('url') - + var https = module.exports - + for (var key in http) { if (http.hasOwnProperty(key)) https[key] = http[key] } - + https.request = function (params, cb) { params = validateParams(params) return http.request.call(this, params, cb) } - + https.get = function (params, cb) { params = validateParams(params) return http.get.call(this, params, cb) } - + function validateParams (params) { if (typeof params === 'string') { params = url.parse(params) @@ -35468,12 +35468,12 @@ } return params } - + },{"http":312,"url":327}],176:[function(require,module,exports){ /* This file is generated from the Unicode IDNA table, using the build-unicode-tables.py script. Please edit that script instead of this file. */ - + /* istanbul ignore next */ (function (root, factory) { if (typeof define === 'function' && define.amd) { @@ -36211,7 +36211,7 @@ ]; var blockIdxes = new Uint16Array([616,616,565,147,161,411,330,2,131,131,328,454,241,408,86,86,696,113,285,350,325,301,473,214,639,232,447,64,369,598,124,672,567,223,621,154,107,86,86,86,86,86,86,505,86,68,634,86,218,218,218,218,486,218,218,513,188,608,216,86,217,463,668,85,700,360,184,86,86,86,647,402,153,10,346,718,662,260,145,298,117,1,443,342,138,54,563,86,240,572,218,70,387,86,118,460,641,602,86,86,306,218,86,692,86,86,86,86,86,162,707,86,458,26,86,218,638,86,86,86,86,86,65,449,86,86,306,183,86,58,391,667,86,157,131,131,131,131,86,433,131,406,31,218,247,86,86,693,218,581,351,86,438,295,69,462,45,126,173,650,14,295,69,97,168,187,641,78,523,390,69,108,287,664,173,219,83,295,69,108,431,426,173,694,412,115,628,52,257,398,641,118,501,121,69,579,151,423,173,620,464,121,69,382,151,476,173,27,53,121,86,594,578,226,173,86,632,130,86,96,228,268,641,622,563,86,86,21,148,650,131,131,321,43,144,343,381,531,131,131,178,20,86,399,156,375,164,541,30,60,715,198,92,118,131,131,86,86,306,407,86,280,457,196,488,358,131,131,244,86,86,143,86,86,86,86,86,667,563,86,86,86,86,86,86,86,86,86,86,86,86,86,336,363,86,86,336,86,86,380,678,67,86,86,86,678,86,86,86,512,86,307,86,708,86,86,86,86,86,528,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,563,307,86,86,86,86,86,104,450,337,86,720,86,32,450,397,86,86,86,587,218,558,708,708,293,708,86,86,86,86,86,694,205,86,8,86,86,86,86,549,86,667,697,697,679,86,458,460,86,86,650,86,708,543,86,86,86,245,86,86,86,140,218,127,708,708,458,197,131,131,131,131,500,86,86,483,251,86,306,510,515,86,722,86,86,86,65,201,86,86,483,580,470,86,86,86,368,131,131,131,694,114,110,555,86,86,123,721,163,142,713,418,86,317,675,209,218,218,218,371,545,592,629,490,603,199,46,320,525,680,310,279,388,111,42,252,593,607,235,617,410,377,50,548,135,356,17,520,189,116,392,600,349,332,482,699,690,535,119,106,451,71,152,667,131,218,218,265,671,637,492,504,533,683,269,269,658,86,86,86,86,86,86,86,86,86,491,619,86,86,6,86,86,86,86,86,86,86,86,86,86,86,229,86,86,86,86,86,86,86,86,86,86,86,86,667,86,86,171,131,118,131,656,206,234,571,89,334,670,246,311,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,534,86,86,86,86,86,86,82,86,86,86,86,86,430,86,86,86,86,86,86,86,86,86,599,86,324,86,470,69,640,264,131,626,101,174,86,86,667,233,105,73,374,394,221,204,84,28,326,86,86,471,86,86,86,109,573,86,171,200,200,200,200,218,218,86,86,86,86,460,131,131,131,86,506,86,86,86,86,86,220,404,34,614,47,442,305,25,612,338,601,648,7,344,255,131,131,51,86,312,507,563,86,86,86,86,588,86,86,86,86,86,530,511,86,458,3,435,384,556,522,230,527,86,118,86,86,717,86,137,273,79,181,484,23,93,112,655,249,417,703,370,87,98,313,684,585,155,465,596,481,695,18,416,428,61,701,706,282,643,495,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,86,86,86,171,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,650,131,422,542,420,263,24,172,86,86,86,86,86,566,86,86,132,540,395,353,494,519,19,485,284,472,131,131,131,16,714,86,211,708,86,86,86,694,698,86,86,483,704,708,218,272,86,86,120,86,159,478,86,307,247,86,86,663,597,459,627,667,86,86,277,455,39,302,86,250,86,86,86,271,99,452,306,281,329,400,200,86,86,362,549,352,646,461,323,586,86,86,4,708,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,717,86,518,86,86,650,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,125,554,480,300,613,72,333,288,561,544,604,48,719,91,169,176,590,224,76,191,29,559,560,231,537,166,477,538,256,437,131,131,469,167,40,0,685,266,441,705,239,642,475,568,640,610,299,673,517,318,385,22,202,180,179,359,424,215,90,66,521,653,467,682,453,409,479,88,131,661,35,303,15,262,666,630,712,131,131,618,659,175,218,195,347,193,227,261,150,165,709,546,294,569,710,270,413,376,524,55,242,38,419,529,170,657,3,304,122,379,278,131,651,86,67,576,458,458,131,131,86,86,86,86,86,86,86,118,309,86,86,547,86,86,86,86,667,650,664,131,131,86,86,56,131,131,131,131,131,131,131,131,86,307,86,86,86,664,238,650,86,86,717,86,118,86,86,315,86,59,86,86,574,549,131,131,340,57,436,86,86,86,86,86,86,458,708,499,691,62,86,650,86,86,694,86,86,86,319,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,86,549,694,131,131,131,131,131,131,131,131,131,77,86,86,139,86,502,86,86,86,667,595,131,131,131,86,12,86,13,86,609,131,131,131,131,86,86,86,625,86,669,86,86,182,129,86,5,694,104,86,86,86,86,131,131,86,86,386,171,86,86,86,345,86,324,86,589,86,213,36,131,131,131,131,131,86,86,86,86,104,131,131,131,141,290,80,677,86,86,86,267,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,515,86,86,33,136,669,86,711,515,86,86,550,640,86,104,708,515,86,159,372,717,86,86,444,515,86,86,663,37,86,563,460,86,390,624,702,131,131,131,131,389,59,708,86,86,341,208,708,635,295,69,108,431,508,100,190,131,131,131,131,131,131,131,131,86,86,86,649,516,660,131,131,86,86,86,218,631,708,131,131,131,131,131,131,131,131,131,131,86,86,341,575,238,514,131,131,86,86,86,218,291,708,307,131,86,86,306,367,708,131,131,131,86,378,697,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,615,253,86,86,86,292,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,104,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,69,86,341,553,549,86,307,86,86,645,275,455,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,708,131,131,131,131,131,131,86,86,86,86,86,86,667,460,86,86,86,86,86,86,86,86,86,86,86,86,717,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,667,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,104,86,667,459,131,131,131,131,131,131,86,458,225,86,86,86,516,549,11,390,405,86,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,460,44,218,197,711,515,131,131,131,131,664,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,307,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,118,307,104,286,591,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,549,86,86,681,86,86,75,185,314,582,86,358,496,474,86,104,131,86,86,86,86,146,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,171,86,640,131,131,131,131,131,131,131,131,246,503,689,339,674,81,258,415,439,128,562,366,414,246,503,689,583,222,557,316,636,665,186,355,95,670,246,503,689,339,674,557,258,415,439,186,355,95,670,246,503,689,446,644,536,652,331,532,335,440,274,421,297,570,74,425,364,425,606,552,403,509,134,365,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,218,218,218,498,218,218,577,627,551,497,572,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,553,354,236,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,296,455,131,131,456,243,103,86,41,459,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,9,276,158,716,393,564,383,489,401,654,210,654,131,131,131,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,650,86,86,86,86,86,86,717,667,563,563,563,86,549,102,686,133,246,605,86,448,86,86,207,307,131,131,131,641,86,177,611,445,373,194,584,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,308,307,171,86,86,86,86,86,86,86,717,86,86,86,86,86,460,131,131,650,86,86,86,694,708,86,86,694,86,458,131,131,131,131,131,131,667,694,289,650,667,131,131,86,640,131,131,664,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,171,131,131,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,460,86,86,86,86,86,86,86,86,86,86,86,86,86,458,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,86,640,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,466,203,149,429,94,432,160,687,539,63,237,283,192,248,348,259,427,526,396,676,254,468,487,212,327,623,49,633,322,493,434,688,357,361,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131,131]); var mappingStr = "صلى الله عليه وسلمجل جلالهキロメートルrad∕s2エスクードキログラムキロワットグラムトンクルゼイロサンチームパーセントピアストルファラッドブッシェルヘクタールマンションミリバールレントゲン′′′′1⁄10viii(10)(11)(12)(13)(14)(15)(16)(17)(18)(19)(20)∫∫∫∫(오전)(오후)アパートアルファアンペアイニングエーカーカラットカロリーキュリーギルダークローネサイクルシリングバーレルフィートポイントマイクロミクロンメガトンリットルルーブル株式会社kcalm∕s2c∕kgاكبرمحمدصلعمرسولریال1⁄41⁄23⁄4 ̈́ྲཱྀླཱྀ ̈͂ ̓̀ ̓́ ̓͂ ̔̀ ̔́ ̔͂ ̈̀‵‵‵a/ca/sc/oc/utelfax1⁄71⁄91⁄32⁄31⁄52⁄53⁄54⁄51⁄65⁄61⁄83⁄85⁄87⁄8xii0⁄3∮∮∮(1)(2)(3)(4)(5)(6)(7)(8)(9)(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)(q)(r)(s)(t)(u)(v)(w)(x)(y)(z)::====(ᄀ)(ᄂ)(ᄃ)(ᄅ)(ᄆ)(ᄇ)(ᄉ)(ᄋ)(ᄌ)(ᄎ)(ᄏ)(ᄐ)(ᄑ)(ᄒ)(가)(나)(다)(라)(마)(바)(사)(아)(자)(차)(카)(타)(파)(하)(주)(一)(二)(三)(四)(五)(六)(七)(八)(九)(十)(月)(火)(水)(木)(金)(土)(日)(株)(有)(社)(名)(特)(財)(祝)(労)(代)(呼)(学)(監)(企)(資)(協)(祭)(休)(自)(至)pte10月11月12月ergltdアールインチウォンオンスオームカイリガロンガンマギニーケースコルナコーポセンチダースノットハイツパーツピクルフランペニヒヘルツペンスページベータボルトポンドホールホーンマイルマッハマルクヤードヤールユアンルピー10点11点12点13点14点15点16点17点18点19点20点21点22点23点24点hpabardm2dm3khzmhzghzthzmm2cm2km2mm3cm3km3kpampagpalogmilmolppmv∕ma∕m10日11日12日13日14日15日16日17日18日19日20日21日22日23日24日25日26日27日28日29日30日31日galffifflשּׁשּׂ ٌّ ٍّ َّ ُّ ِّ ّٰـَّـُّـِّتجمتحجتحمتخمتمجتمحتمخجمححميحمىسحجسجحسجىسمحسمجسممصححصممشحمشجيشمخشممضحىضخمطمحطممطميعجمعممعمىغممغميغمىفخمقمحقمملحملحيلحىلججلخملمحمحجمحيمجحمجممخممجخهمجهممنحمنحىنجمنجىنمينمىيممبخيتجيتجىتخيتخىتميتمىجميجحىجمىسخىصحيشحيضحيلجيلمييحييجييميمميقمينحيعميكمينجحمخيلجمكممجحيحجيمجيفميبحيسخينجيصلےقلے𝅘𝅥𝅮𝅘𝅥𝅯𝅘𝅥𝅰𝅘𝅥𝅱𝅘𝅥𝅲𝆹𝅥𝅮𝆺𝅥𝅮𝆹𝅥𝅯𝆺𝅥𝅯〔s〕ppv〔本〕〔三〕〔二〕〔安〕〔点〕〔打〕〔盗〕〔勝〕〔敗〕 ̄ ́ ̧ssi̇ijl·ʼndžljnjdz ̆ ̇ ̊ ̨ ̃ ̋ ιեւاٴوٴۇٴيٴक़ख़ग़ज़ड़ढ़फ़य़ড়ঢ়য়ਲ਼ਸ਼ਖ਼ਗ਼ਜ਼ਫ਼ଡ଼ଢ଼ําໍາຫນຫມགྷཌྷདྷབྷཛྷཀྵཱཱིུྲྀླྀྒྷྜྷྡྷྦྷྫྷྐྵaʾἀιἁιἂιἃιἄιἅιἆιἇιἠιἡιἢιἣιἤιἥιἦιἧιὠιὡιὢιὣιὤιὥιὦιὧιὰιαιάιᾶι ͂ὴιηιήιῆιὼιωιώιῶι ̳!! ̅???!!?rs°c°fnosmtmivix⫝̸ ゙ ゚よりコト333435참고주의363738394042444546474849503月4月5月6月7月8月9月hgevギガデシドルナノピコビルペソホンリラレムdaauovpciu平成昭和大正明治naμakakbmbgbpfnfμfμgmgμlmldlklfmnmμmpsnsμsmsnvμvkvpwnwμwmwkwkωmωbqcccddbgyhainkkktlnlxphprsrsvwbstմնմեմիվնմխיִײַשׁשׂאַאָאּבּגּדּהּוּזּטּיּךּכּלּמּנּסּףּפּצּקּרּתּוֹבֿכֿפֿאלئائەئوئۇئۆئۈئېئىئجئحئمئيبجبمبىبيتىتيثجثمثىثيخحضجضمطحظمغجفجفحفىفيقحقىقيكاكجكحكخكلكىكينخنىنيهجهىهييىذٰرٰىٰئرئزئنبزبنترتزتنثرثزثنمانرنزننيريزئخئهبهتهصخنههٰثهسهشهطىطيعىعيغىغيسىسيشىشيصىصيضىضيشخشرسرصرضراً ًـًـّ ْـْلآلألإ𝅗𝅥0,1,2,3,4,5,6,7,8,9,wzhvsdwcmcmddjほかココàáâãäåæçèéêëìíîïðñòóôõöøùúûüýþāăąćĉċčďđēĕėęěĝğġģĥħĩīĭįĵķĺļľłńņňŋōŏőœŕŗřśŝşšţťŧũūŭůűųŵŷÿźżɓƃƅɔƈɖɗƌǝəɛƒɠɣɩɨƙɯɲɵơƣƥʀƨʃƭʈưʊʋƴƶʒƹƽǎǐǒǔǖǘǚǜǟǡǣǥǧǩǫǭǯǵƕƿǹǻǽǿȁȃȅȇȉȋȍȏȑȓȕȗșțȝȟƞȣȥȧȩȫȭȯȱȳⱥȼƚⱦɂƀʉʌɇɉɋɍɏɦɹɻʁʕͱͳʹͷ;ϳέίόύβγδεζθκλνξοπρστυφχψϊϋϗϙϛϝϟϡϣϥϧϩϫϭϯϸϻͻͼͽѐёђѓєѕіїјљњћќѝўџабвгдежзийклмнопрстуфхцчшщъыьэюяѡѣѥѧѩѫѭѯѱѳѵѷѹѻѽѿҁҋҍҏґғҕҗҙқҝҟҡңҥҧҩҫҭүұҳҵҷҹһҽҿӂӄӆӈӊӌӎӑӓӕӗәӛӝӟӡӣӥӧөӫӭӯӱӳӵӷӹӻӽӿԁԃԅԇԉԋԍԏԑԓԕԗԙԛԝԟԡԣԥԧԩԫԭԯաբգդզէըթժլծկհձղճյշոչպջռստրցփքօֆ་ⴧⴭნᏰᏱᏲᏳᏴᏵꙋɐɑᴂɜᴖᴗᴝᴥɒɕɟɡɥɪᵻʝɭᶅʟɱɰɳɴɸʂƫᴜʐʑḁḃḅḇḉḋḍḏḑḓḕḗḙḛḝḟḡḣḥḧḩḫḭḯḱḳḵḷḹḻḽḿṁṃṅṇṉṋṍṏṑṓṕṗṙṛṝṟṡṣṥṧṩṫṭṯṱṳṵṷṹṻṽṿẁẃẅẇẉẋẍẏẑẓẕạảấầẩẫậắằẳẵặẹẻẽếềểễệỉịọỏốồổỗộớờởỡợụủứừửữựỳỵỷỹỻỽỿἐἑἒἓἔἕἰἱἲἳἴἵἶἷὀὁὂὃὄὅὑὓὕὗᾰᾱὲΐῐῑὶΰῠῡὺῥ`ὸ‐+−∑〈〉ⰰⰱⰲⰳⰴⰵⰶⰷⰸⰹⰺⰻⰼⰽⰾⰿⱀⱁⱂⱃⱄⱅⱆⱇⱈⱉⱊⱋⱌⱍⱎⱏⱐⱑⱒⱓⱔⱕⱖⱗⱘⱙⱚⱛⱜⱝⱞⱡɫᵽɽⱨⱪⱬⱳⱶȿɀⲁⲃⲅⲇⲉⲋⲍⲏⲑⲓⲕⲗⲙⲛⲝⲟⲡⲣⲥⲧⲩⲫⲭⲯⲱⲳⲵⲷⲹⲻⲽⲿⳁⳃⳅⳇⳉⳋⳍⳏⳑⳓⳕⳗⳙⳛⳝⳟⳡⳣⳬⳮⳳⵡ母龟丨丶丿乙亅亠人儿入冂冖冫几凵刀力勹匕匚匸卜卩厂厶又口囗士夂夊夕女子宀寸小尢尸屮山巛工己巾干幺广廴廾弋弓彐彡彳心戈戶手支攴文斗斤方无曰欠止歹殳毋比毛氏气爪父爻爿片牙牛犬玄玉瓜瓦甘生用田疋疒癶白皮皿目矛矢石示禸禾穴立竹米糸缶网羊羽老而耒耳聿肉臣臼舌舛舟艮色艸虍虫血行衣襾見角言谷豆豕豸貝赤走足身車辛辰辵邑酉釆里長門阜隶隹雨靑非面革韋韭音頁風飛食首香馬骨高髟鬥鬯鬲鬼魚鳥鹵鹿麥麻黃黍黑黹黽鼎鼓鼠鼻齊齒龍龜龠.〒卄卅ᄁᆪᆬᆭᄄᆰᆱᆲᆳᆴᆵᄚᄈᄡᄊ짜ᅢᅣᅤᅥᅦᅧᅨᅩᅪᅫᅬᅭᅮᅯᅰᅱᅲᅳᅴᅵᄔᄕᇇᇈᇌᇎᇓᇗᇙᄜᇝᇟᄝᄞᄠᄢᄣᄧᄩᄫᄬᄭᄮᄯᄲᄶᅀᅇᅌᇱᇲᅗᅘᅙᆄᆅᆈᆑᆒᆔᆞᆡ上中下甲丙丁天地問幼箏우秘男適優印注項写左右医宗夜テヌモヨヰヱヲꙁꙃꙅꙇꙉꙍꙏꙑꙓꙕꙗꙙꙛꙝꙟꙡꙣꙥꙧꙩꙫꙭꚁꚃꚅꚇꚉꚋꚍꚏꚑꚓꚕꚗꚙꚛꜣꜥꜧꜩꜫꜭꜯꜳꜵꜷꜹꜻꜽꜿꝁꝃꝅꝇꝉꝋꝍꝏꝑꝓꝕꝗꝙꝛꝝꝟꝡꝣꝥꝧꝩꝫꝭꝯꝺꝼᵹꝿꞁꞃꞅꞇꞌꞑꞓꞗꞙꞛꞝꞟꞡꞣꞥꞧꞩɬʞʇꭓꞵꞷꬷꭒᎠᎡᎢᎣᎤᎥᎦᎧᎨᎩᎪᎫᎬᎭᎮᎯᎰᎱᎲᎳᎴᎵᎶᎷᎸᎹᎺᎻᎼᎽᎾᎿᏀᏁᏂᏃᏄᏅᏆᏇᏈᏉᏊᏋᏌᏍᏎᏏᏐᏑᏒᏓᏔᏕᏖᏗᏘᏙᏚᏛᏜᏝᏞᏟᏠᏡᏢᏣᏤᏥᏦᏧᏨᏩᏪᏫᏬᏭᏮᏯ豈更賈滑串句契喇奈懶癩羅蘿螺裸邏樂洛烙珞落酪駱亂卵欄爛蘭鸞嵐濫藍襤拉臘蠟廊朗浪狼郎來冷勞擄櫓爐盧蘆虜路露魯鷺碌祿綠菉錄論壟弄籠聾牢磊賂雷壘屢樓淚漏累縷陋勒肋凜凌稜綾菱陵讀拏諾丹寧怒率異北磻便復不泌數索參塞省葉說殺沈拾若掠略亮兩凉梁糧良諒量勵呂廬旅濾礪閭驪麗黎曆歷轢年憐戀撚漣煉璉秊練聯輦蓮連鍊列劣咽烈裂廉念捻殮簾獵令囹嶺怜玲瑩羚聆鈴零靈領例禮醴隸惡了僚寮尿料燎療蓼遼暈阮劉杻柳流溜琉留硫紐類戮陸倫崙淪輪律慄栗隆利吏履易李梨泥理痢罹裏裡離匿溺吝燐璘藺隣鱗麟林淋臨笠粒狀炙識什茶刺切度拓糖宅洞暴輻降廓兀嗀塚晴凞猪益礼神祥福靖精蘒諸逸都飯飼館鶴郞隷侮僧免勉勤卑喝嘆器塀墨層悔慨憎懲敏既暑梅海渚漢煮爫琢碑祉祈祐祖禍禎穀突節縉繁署者臭艹著褐視謁謹賓贈辶難響頻恵𤋮舘並况全侀充冀勇勺啕喙嗢墳奄奔婢嬨廒廙彩徭惘慎愈慠戴揄搜摒敖望杖滛滋瀞瞧爵犯瑱甆画瘝瘟盛直睊着磌窱类絛缾荒華蝹襁覆調請諭變輸遲醙鉶陼韛頋鬒𢡊𢡄𣏕㮝䀘䀹𥉉𥳐𧻓齃龎עםٱٻپڀٺٿٹڤڦڄڃچڇڍڌڎڈژڑکگڳڱںڻۀہھۓڭۋۅۉ、〖〗—–_{}【】《》「」『』[]#&*-<>\\$%@ءؤة\"'^|~⦅⦆・ゥャ¢£¬¦¥₩│←↑→↓■○𐐨𐐩𐐪𐐫𐐬𐐭𐐮𐐯𐐰𐐱𐐲𐐳𐐴𐐵𐐶𐐷𐐸𐐹𐐺𐐻𐐼𐐽𐐾𐐿𐑀𐑁𐑂𐑃𐑄𐑅𐑆𐑇𐑈𐑉𐑊𐑋𐑌𐑍𐑎𐑏𐓘𐓙𐓚𐓛𐓜𐓝𐓞𐓟𐓠𐓡𐓢𐓣𐓤𐓥𐓦𐓧𐓨𐓩𐓪𐓫𐓬𐓭𐓮𐓯𐓰𐓱𐓲𐓳𐓴𐓵𐓶𐓷𐓸𐓹𐓺𐓻𐳀𐳁𐳂𐳃𐳄𐳅𐳆𐳇𐳈𐳉𐳊𐳋𐳌𐳍𐳎𐳏𐳐𐳑𐳒𐳓𐳔𐳕𐳖𐳗𐳘𐳙𐳚𐳛𐳜𐳝𐳞𐳟𐳠𐳡𐳢𐳣𐳤𐳥𐳦𐳧𐳨𐳩𐳪𐳫𐳬𐳭𐳮𐳯𐳰𐳱𐳲𑣀𑣁𑣂𑣃𑣄𑣅𑣆𑣇𑣈𑣉𑣊𑣋𑣌𑣍𑣎𑣏𑣐𑣑𑣒𑣓𑣔𑣕𑣖𑣗𑣘𑣙𑣚𑣛𑣜𑣝𑣞𑣟ıȷ∇∂𞤢𞤣𞤤𞤥𞤦𞤧𞤨𞤩𞤪𞤫𞤬𞤭𞤮𞤯𞤰𞤱𞤲𞤳𞤴𞤵𞤶𞤷𞤸𞤹𞤺𞤻𞤼𞤽𞤾𞤿𞥀𞥁𞥂𞥃ٮڡٯ字双多解交映無前後再新初終販声吹演投捕遊指禁空合満申割営配得可丽丸乁𠄢你侻倂偺備像㒞𠘺兔兤具𠔜㒹內𠕋冗冤仌冬𩇟刃㓟刻剆剷㔕包匆卉博即卽卿𠨬灰及叟𠭣叫叱吆咞吸呈周咢哶唐啓啣善喫喳嗂圖圗噑噴壮城埴堍型堲報墬𡓤売壷夆夢奢𡚨𡛪姬娛娧姘婦㛮嬈嬾𡧈寃寘寳𡬘寿将㞁屠峀岍𡷤嵃𡷦嵮嵫嵼巡巢㠯巽帨帽幩㡢𢆃㡼庰庳庶𪎒𢌱舁弢㣇𣊸𦇚形彫㣣徚忍志忹悁㤺㤜𢛔惇慈慌慺憲憤憯懞戛扝抱拔捐𢬌挽拼捨掃揤𢯱搢揅掩㨮摩摾撝摷㩬敬𣀊旣書晉㬙㬈㫤冒冕最暜肭䏙朡杞杓𣏃㭉柺枅桒𣑭梎栟椔楂榣槪檨𣚣櫛㰘次𣢧歔㱎歲殟殻𣪍𡴋𣫺汎𣲼沿泍汧洖派浩浸涅𣴞洴港湮㴳滇𣻑淹潮𣽞𣾎濆瀹瀛㶖灊災灷炭𠔥煅𤉣熜爨牐𤘈犀犕𤜵𤠔獺王㺬玥㺸瑇瑜璅瓊㼛甤𤰶甾𤲒𢆟瘐𤾡𤾸𥁄㿼䀈𥃳𥃲𥄙𥄳眞真瞋䁆䂖𥐝硎䃣𥘦𥚚𥛅秫䄯穊穏𥥼𥪧䈂𥮫篆築䈧𥲀糒䊠糨糣紀𥾆絣䌁緇縂繅䌴𦈨𦉇䍙𦋙罺𦌾羕翺𦓚𦔣聠𦖨聰𣍟䏕育脃䐋脾媵𦞧𦞵𣎓𣎜舄辞䑫芑芋芝劳花芳芽苦𦬼茝荣莭茣莽菧荓菊菌菜𦰶𦵫𦳕䔫蓱蓳蔖𧏊蕤𦼬䕝䕡𦾱𧃒䕫虐虧虩蚩蚈蜎蛢蜨蝫螆蟡蠁䗹衠𧙧裗裞䘵裺㒻𧢮𧥦䚾䛇誠𧲨貫賁贛起𧼯𠠄跋趼跰𠣞軔𨗒𨗭邔郱鄑𨜮鄛鈸鋗鋘鉼鏹鐕𨯺開䦕閷𨵷䧦雃嶲霣𩅅𩈚䩮䩶韠𩐊䪲𩒖頩𩖶飢䬳餩馧駂駾䯎𩬰鱀鳽䳎䳭鵧𪃎䳸𪄅𪈎𪊑䵖黾鼅鼏鼖𪘀"; - + function mapChar(codePoint) { if (codePoint >= 0x30000) { // High planes are special cased. @@ -36221,13 +36221,13 @@ } return blocks[blockIdxes[codePoint >> 4]][codePoint & 15]; } - + return { mapStr: mappingStr, mapChar: mapChar }; })); - + },{}],177:[function(require,module,exports){ (function(root, factory) { /* istanbul ignore next */ @@ -36243,7 +36243,7 @@ root.uts46 = factory(root.punycode, root.idna_map); } }(this, function(punycode, idna_map) { - + function mapLabel(label, useStd3ASCII, transitional) { var mapped = []; var chars = punycode.ucs2.decode(label); @@ -36270,20 +36270,20 @@ mapped.push(ch); } } - + var newLabel = mapped.join("").normalize("NFC"); return newLabel; } - + function process(domain, transitional, useStd3ASCII) { /* istanbul ignore if */ if (useStd3ASCII === undefined) useStd3ASCII = false; var mappedIDNA = mapLabel(domain, useStd3ASCII, transitional); - + // Step 3. Break var labels = mappedIDNA.split("."); - + // Step 4. Convert/Validate labels = labels.map(function(label) { if (label.startsWith("xn--")) { @@ -36295,37 +36295,37 @@ } return label; }); - + return labels.join("."); } - + function validateLabel(label, useStd3ASCII, transitional) { // 2. The label must not contain a U+002D HYPHEN-MINUS character in both the // third position and fourth positions. if (label[2] === '-' && label[3] === '-') throw new Error("Failed to validate " + label); - + // 3. The label must neither begin nor end with a U+002D HYPHEN-MINUS // character. if (label.startsWith('-') || label.endsWith('-')) throw new Error("Failed to validate " + label); - + // 4. The label must not contain a U+002E ( . ) FULL STOP. // this should nerver happen as label is chunked internally by this character /* istanbul ignore if */ if (label.includes('.')) throw new Error("Failed to validate " + label); - + if (mapLabel(label, useStd3ASCII, transitional) !== label) throw new Error("Failed to validate " + label); - + // 5. The label must not begin with a combining mark, that is: // General_Category=Mark. var ch = label.codePointAt(0); if (idna_map.mapChar(ch) & (0x2 << 23)) throw new Error("Label contains illegal character: " + ch); } - + function toAscii(domain, options) { if (options === undefined) options = {}; @@ -36348,20 +36348,20 @@ } return asciiString; } - + function toUnicode(domain, options) { if (options === undefined) options = {}; var useStd3ASCII = 'useStd3ASCII' in options ? options.useStd3ASCII : false; return process(domain, false, useStd3ASCII); } - + return { toUnicode: toUnicode, toAscii: toAscii, }; })); - + },{"./idna-map":176,"punycode":265}],178:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m @@ -36372,19 +36372,19 @@ 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) { @@ -36395,7 +36395,7 @@ } 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 @@ -36405,9 +36405,9 @@ 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 @@ -36426,7 +36426,7 @@ e++ c /= 2 } - + if (e + eBias >= eMax) { m = 0 e = eMax @@ -36438,20 +36438,20 @@ 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 } - + },{}],179:[function(require,module,exports){ - + var indexOf = [].indexOf; - + module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { @@ -36483,7 +36483,7 @@ ctor.prototype.constructor = ctor } } - + },{}],181:[function(require,module,exports){ /*! * Determine if an object is a Buffer @@ -36491,27 +36491,27 @@ * @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)) } - + },{}],182:[function(require,module,exports){ 'use strict'; - + var fnToStr = Function.prototype.toString; - + var constructorRegex = /^\s*class\b/; var isES6ClassFn = function isES6ClassFunction(value) { try { @@ -36521,7 +36521,7 @@ return false; // not a function } }; - + var tryFunctionObject = function tryFunctionToStr(value) { try { if (isES6ClassFn(value)) { return false; } @@ -36535,7 +36535,7 @@ var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; - + module.exports = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } @@ -36545,20 +36545,20 @@ var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; - + },{}],183:[function(require,module,exports){ 'use strict'; var toString = Object.prototype.toString; - + module.exports = function (x) { return toString.call(x) === '[object Function]'; }; - + },{}],184:[function(require,module,exports){ module.exports = isFunction - + var toString = Object.prototype.toString - + function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || @@ -36570,7 +36570,7 @@ fn === window.confirm || fn === window.prompt)) }; - + },{}],185:[function(require,module,exports){ /** * Returns a `Boolean` on whether or not the a `String` starts with '0x' @@ -36582,26 +36582,26 @@ 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'; } - + },{}],186:[function(require,module,exports){ var toString = {}.toString; - + module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; - + },{}],187:[function(require,module,exports){ 'use strict'; - + function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } - + var promiseToCallback = require('promise-to-callback'); - + module.exports = createAsyncMiddleware; - + function createAsyncMiddleware(asyncMiddleware) { return function (req, res, next, end) { var getNextPromise = function () { @@ -36613,10 +36613,10 @@ nextDonePromise = getNextDoneCallback(); _context.next = 3; return nextDonePromise; - + case 3: return _context.abrupt('return', undefined); - + case 4: case 'end': return _context.stop(); @@ -36624,12 +36624,12 @@ } }, _callee, this); })); - + return function getNextPromise() { return _ref.apply(this, arguments); }; }(); - + var nextDonePromise = null; var finishedPromise = asyncMiddleware(req, res, getNextPromise); promiseToCallback(finishedPromise)(function (err) { @@ -36650,7 +36650,7 @@ end(err); } }); - + function getNextDoneCallback() { return new Promise(function (resolve) { next(function (cb) { @@ -36660,37 +36660,37 @@ } }; } - + },{"promise-to-callback":258}],188:[function(require,module,exports){ 'use strict'; - + var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - + function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - + function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } - + function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } - + var async = require('async'); var SafeEventEmitter = require('safe-event-emitter'); - + var RpcEngine = function (_SafeEventEmitter) { _inherits(RpcEngine, _SafeEventEmitter); - + function RpcEngine() { _classCallCheck(this, RpcEngine); - + var _this = _possibleConstructorReturn(this, (RpcEngine.__proto__ || Object.getPrototypeOf(RpcEngine)).call(this)); - + _this._middleware = []; return _this; } - + // // Public // - + _createClass(RpcEngine, [{ key: 'push', value: function push(middleware) { @@ -36706,11 +36706,11 @@ this._handle(req, cb); } } - + // // Private // - + }, { key: '_handle', value: function _handle(_req, cb) { @@ -36730,18 +36730,18 @@ key: '_runMiddleware', value: function _runMiddleware(req, res, onDone) { var _this2 = this; - + // flow async.waterfall([function (cb) { return _this2._runMiddlewareDown(req, res, cb); }, checkForCompletion, function (returnHandlers, cb) { return _this2._runReturnHandlersUp(returnHandlers, cb); }], onDone); - + function checkForCompletion(_ref, cb) { var isComplete = _ref.isComplete, returnHandlers = _ref.returnHandlers; - + // fail if not completed if (!('result' in res) && !('error' in res)) { var requestBody = JSON.stringify(req, null, 2); @@ -36756,16 +36756,16 @@ // continue return cb(null, returnHandlers); } - + function runReturnHandlers(returnHandlers, cb) { async.eachSeries(returnHandlers, function (handler, next) { return handler(next); }, onDone); } } - + // walks down stack of middleware - + }, { key: '_runMiddlewareDown', value: function _runMiddlewareDown(req, res, onDone) { @@ -36773,17 +36773,17 @@ var allReturnHandlers = []; // flag for stack return var isComplete = false; - + // down stack of middleware, call and collect optional allReturnHandlers async.mapSeries(this._middleware, eachMiddleware, completeRequest); - + // runs an individual middleware function eachMiddleware(middleware, cb) { // skip middleware if completed if (isComplete) return cb(); // run individual middleware middleware(req, res, next, end); - + function next(returnHandler) { // add return handler allReturnHandlers.push(returnHandler); @@ -36796,7 +36796,7 @@ cb(); } } - + // returns, indicating whether or not it ended function completeRequest(err) { if (err) { @@ -36811,9 +36811,9 @@ onDone(null, { isComplete: isComplete, returnHandlers: returnHandlers }); } } - + // climbs the stack calling return handlers - + }, { key: '_runReturnHandlersUp', value: function _runReturnHandlersUp(returnHandlers, cb) { @@ -36822,133 +36822,133 @@ }, cb); } }]); - + return RpcEngine; }(SafeEventEmitter); - + module.exports = RpcEngine; - + },{"async":21,"safe-event-emitter":291}],189:[function(require,module,exports){ module.exports = require('./lib/errors'); },{"./lib/errors":190}],190:[function(require,module,exports){ var inherits = require('inherits'); - + var JsonRpcError = function(message, code, data) { if (!(this instanceof JsonRpcError)) { return new JsonRpcError(message, code, data); } - + this.message = message; this.code = code; - + if (typeof data !== 'undefined') { this.data = data; } }; - + inherits(JsonRpcError, Error); - + var ParseError = function() { if (!(this instanceof ParseError)) { return new ParseError(); } - + JsonRpcError.call(this, 'Parse error', -32700); }; - + inherits(ParseError, JsonRpcError); - + var InvalidRequest = function() { if (!(this instanceof InvalidRequest)) { return new InvalidRequest(); } - + JsonRpcError.call(this, 'Invalid Request', -32600); }; - + inherits(InvalidRequest, JsonRpcError); - + var MethodNotFound = function() { if (!(this instanceof MethodNotFound)) { return new MethodNotFound(); } - + JsonRpcError.call(this, 'Method not found', -32601); }; - + inherits(MethodNotFound, JsonRpcError); - + var InvalidParams = function() { if (!(this instanceof InvalidParams)) { return new InvalidParams(); } - + JsonRpcError.call(this, 'Invalid params', -32602); }; - + inherits(InvalidParams, JsonRpcError); - + var InternalError = function(err) { var message; - + if (!(this instanceof InternalError)) { return new InternalError(err); } - + if (err && err.message) { message = err.message; } else { message = 'Internal error'; } - + JsonRpcError.call(this, message, -32603); }; - + inherits(InternalError, JsonRpcError); - + var ServerError = function(code) { if (code < -32099 || code > -32000) { throw new Error('Invalid error code'); } - + if (!(this instanceof ServerError)) { return new ServerError(code); } - + JsonRpcError.call(this, 'Server error', code); }; - + inherits(ServerError, JsonRpcError); - + JsonRpcError.ParseError = ParseError; JsonRpcError.InvalidRequest = InvalidRequest; JsonRpcError.MethodNotFound = MethodNotFound; JsonRpcError.InvalidParams = InvalidParams; JsonRpcError.InternalError = InternalError; JsonRpcError.ServerError = ServerError; - + module.exports = JsonRpcError; - - - + + + },{"inherits":180}],191:[function(require,module,exports){ module.exports = IdIterator - + function IdIterator(opts){ opts = opts || {} var max = opts.max || Number.MAX_SAFE_INTEGER var idCounter = typeof opts.start !== 'undefined' ? opts.start : Math.floor(Math.random() * max) - + return function createRandomId () { idCounter = idCounter % max return idCounter++ } - + } },{}],192:[function(require,module,exports){ exports.parse = require('./lib/parse'); exports.stringify = require('./lib/stringify'); - + },{"./lib/parse":193,"./lib/stringify":194}],193:[function(require,module,exports){ var at, // The index of the current character ch, // The current character @@ -36963,7 +36963,7 @@ t: '\t' }, text, - + error = function (m) { // Call error when something is wrong. throw { @@ -36973,26 +36973,26 @@ text: text }; }, - + next = function (c) { // If a c parameter is provided, verify that it matches the current character. if (c && c !== ch) { error("Expected '" + c + "' instead of '" + ch + "'"); } - + // Get the next character. When there are no more characters, // return the empty string. - + ch = text.charAt(at); at += 1; return ch; }, - + number = function () { // Parse a number value. var number, string = ''; - + if (ch === '-') { string = '-'; next('-'); @@ -37026,14 +37026,14 @@ return number; } }, - + string = function () { // Parse a string value. var hex, i, string = '', uffff; - + // When parsing for string values, we must look for " and \ characters. if (ch === '"') { while (next()) { @@ -37064,20 +37064,20 @@ } error("Bad string"); }, - + white = function () { - + // Skip whitespace. - + while (ch && ch <= ' ') { next(); } }, - + word = function () { - + // true, false, or null. - + switch (ch) { case 't': next('t'); @@ -37101,15 +37101,15 @@ } error("Unexpected '" + ch + "'"); }, - + value, // Place holder for the value function. - + array = function () { - + // Parse an array value. - + var array = []; - + if (ch === '[') { next('['); white(); @@ -37130,14 +37130,14 @@ } error("Bad array"); }, - + object = function () { - + // Parse an object value. - + var key, object = {}; - + if (ch === '{') { next('{'); white(); @@ -37164,12 +37164,12 @@ } error("Bad object"); }; - + value = function () { - + // Parse a JSON value. It could be an object, an array, a string, a number, // or a word. - + white(); switch (ch) { case '{': @@ -37184,13 +37184,13 @@ return ch >= '0' && ch <= '9' ? number() : word(); } }; - + // Return the json_parse function. It will have access to all of the above // functions and variables. - + module.exports = function (source, reviver) { var result; - + text = source; at = 0; ch = ' '; @@ -37199,13 +37199,13 @@ if (ch) { error("Syntax error"); } - + // If there is a reviver function, we recursively walk the new structure, // passing each name/value pair to the reviver function for possible // transformation, starting with a temporary root object that holds the result // in an empty key. If there is not a reviver function, we simply return the // result. - + return typeof reviver === 'function' ? (function walk(holder, key) { var k, v, value = holder[key]; if (value && typeof value === 'object') { @@ -37223,7 +37223,7 @@ return reviver.call(holder, key, value); }({'': result}, '')) : result; }; - + },{}],194:[function(require,module,exports){ var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, @@ -37239,13 +37239,13 @@ '\\': '\\\\' }, rep; - + function quote(string) { // If the string contains no control characters, no quote characters, and no // backslash characters, then we can safely slap some quotes around it. // Otherwise we must also replace the offending characters with safe escape // sequences. - + escapable.lastIndex = 0; return escapable.test(string) ? '"' + string.replace(escapable, function (a) { var c = meta[a]; @@ -37253,7 +37253,7 @@ '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); }) + '"' : '"' + string + '"'; } - + function str(key, holder) { // Produce a string from holder[key]. var i, // The loop counter. @@ -37263,47 +37263,47 @@ mind = gap, partial, value = holder[key]; - + // If the value has a toJSON method, call it to obtain a replacement value. if (value && typeof value === 'object' && typeof value.toJSON === 'function') { value = value.toJSON(key); } - + // If we were called with a replacer function, then call the replacer to // obtain a replacement value. if (typeof rep === 'function') { value = rep.call(holder, key, value); } - + // What happens next depends on the value's type. switch (typeof value) { case 'string': return quote(value); - + case 'number': // JSON numbers must be finite. Encode non-finite numbers as null. return isFinite(value) ? String(value) : 'null'; - + case 'boolean': case 'null': // If the value is a boolean or null, convert it to a string. Note: // typeof null does not produce 'null'. The case is included here in // the remote chance that this gets fixed someday. return String(value); - + case 'object': if (!value) return 'null'; gap += indent; partial = []; - + // Array.isArray if (Object.prototype.toString.apply(value) === '[object Array]') { length = value.length; for (i = 0; i < length; i += 1) { partial[i] = str(i, value) || 'null'; } - + // Join all of the elements together, separated with commas, and // wrap them in brackets. v = partial.length === 0 ? '[]' : gap ? @@ -37312,7 +37312,7 @@ gap = mind; return v; } - + // If the replacer is an array, use it to select the members to be // stringified. if (rep && typeof rep === 'object') { @@ -37338,10 +37338,10 @@ } } } - + // Join all of the member texts together, separated with commas, // and wrap them in braces. - + v = partial.length === 0 ? '{}' : gap ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' : '{' + partial.join(',') + '}'; @@ -37349,12 +37349,12 @@ return v; } } - + module.exports = function (value, replacer, space) { var i; gap = ''; indent = ''; - + // If the space parameter is a number, make an indent string containing that // many spaces. if (typeof space === 'number') { @@ -37366,7 +37366,7 @@ else if (typeof space === 'string') { indent = space; } - + // If there is a replacer, it must be a function or an array. // Otherwise, throw an error. rep = replacer; @@ -37374,25 +37374,25 @@ && (typeof replacer !== 'object' || typeof replacer.length !== 'number')) { throw new Error('JSON.stringify'); } - + // Make a fake root object containing our value under the key of ''. // Return the result of stringifying the value. return str('', {'': value}); }; - + },{}],195:[function(require,module,exports){ 'use strict' module.exports = require('./lib/api')(require('./lib/keccak')) - + },{"./lib/api":196,"./lib/keccak":200}],196:[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) { @@ -37400,43 +37400,43 @@ 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":197,"./shake":198}],197:[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 { @@ -37444,10 +37444,10 @@ } catch (err) { error = err } - + callback(error) } - + Keccak.prototype._flush = function (callback) { var error = null try { @@ -37455,73 +37455,73 @@ } 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":180,"safe-buffer":290,"stream":311}],198:[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 { @@ -37529,58 +37529,58 @@ } 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":180,"safe-buffer":290,"stream":311}],199:[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 @@ -37594,7 +37594,7 @@ 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 @@ -37655,7 +37655,7 @@ var t1shi19 = s[39] ^ hi var t1slo24 = s[48] ^ lo var t1shi24 = s[49] ^ hi - + // rho & pi var t2slo0 = t1slo0 var t2shi0 = t1shi0 @@ -37707,7 +37707,7 @@ 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) @@ -37759,18 +37759,18 @@ 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] } } - + },{}],200:[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 = [ @@ -37780,19 +37780,19 @@ 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)) @@ -37803,7 +37803,7 @@ } } } - + 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) @@ -37812,10 +37812,10 @@ 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 @@ -37825,27 +37825,27 @@ 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":199,"safe-buffer":290}],201:[function(require,module,exports){ var root = require('./_root'); - + /** Built-in value references. */ var Symbol = root.Symbol; - + module.exports = Symbol; - + },{"./_root":217}],202:[function(require,module,exports){ var baseTimes = require('./_baseTimes'), isArguments = require('./isArguments'), @@ -37853,13 +37853,13 @@ isBuffer = require('./isBuffer'), isIndex = require('./_isIndex'), isTypedArray = require('./isTypedArray'); - + /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - + /** * Creates an array of the enumerable property names of the array-like `value`. * @@ -37876,7 +37876,7 @@ skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; - + for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( @@ -37894,21 +37894,21 @@ } return result; } - + module.exports = arrayLikeKeys; - + },{"./_baseTimes":207,"./_isIndex":211,"./isArguments":219,"./isArray":220,"./isBuffer":222,"./isTypedArray":227}],203:[function(require,module,exports){ var Symbol = require('./_Symbol'), getRawTag = require('./_getRawTag'), objectToString = require('./_objectToString'); - + /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; - + /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - + /** * The base implementation of `getTag` without fallbacks for buggy environments. * @@ -37924,16 +37924,16 @@ ? getRawTag(value) : objectToString(value); } - + module.exports = baseGetTag; - + },{"./_Symbol":201,"./_getRawTag":210,"./_objectToString":215}],204:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObjectLike = require('./isObjectLike'); - + /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; - + /** * The base implementation of `_.isArguments`. * @@ -37944,14 +37944,14 @@ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } - + module.exports = baseIsArguments; - + },{"./_baseGetTag":203,"./isObjectLike":226}],205:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isLength = require('./isLength'), isObjectLike = require('./isObjectLike'); - + /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', @@ -37966,7 +37966,7 @@ setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; - + var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', @@ -37978,7 +37978,7 @@ uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; - + /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = @@ -37994,7 +37994,7 @@ typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - + /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * @@ -38006,19 +38006,19 @@ return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } - + module.exports = baseIsTypedArray; - + },{"./_baseGetTag":203,"./isLength":224,"./isObjectLike":226}],206:[function(require,module,exports){ var isPrototype = require('./_isPrototype'), nativeKeys = require('./_nativeKeys'); - + /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - + /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * @@ -38038,9 +38038,9 @@ } return result; } - + module.exports = baseKeys; - + },{"./_isPrototype":212,"./_nativeKeys":213}],207:[function(require,module,exports){ /** * The base implementation of `_.times` without support for iteratee shorthands @@ -38054,15 +38054,15 @@ function baseTimes(n, iteratee) { var index = -1, result = Array(n); - + while (++index < n) { result[index] = iteratee(index); } return result; } - + module.exports = baseTimes; - + },{}],208:[function(require,module,exports){ /** * The base implementation of `_.unary` without support for storing metadata. @@ -38076,36 +38076,36 @@ return func(value); }; } - + module.exports = baseUnary; - + },{}],209:[function(require,module,exports){ (function (global){ /** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - + module.exports = freeGlobal; - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],210:[function(require,module,exports){ var Symbol = require('./_Symbol'); - + /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - + /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; - + /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - + /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * @@ -38116,12 +38116,12 @@ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; - + try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} - + var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { @@ -38132,16 +38132,16 @@ } return result; } - + module.exports = getRawTag; - + },{"./_Symbol":201}],211:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; - + /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; - + /** * Checks if `value` is a valid array-like index. * @@ -38156,13 +38156,13 @@ (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } - + module.exports = isIndex; - + },{}],212:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** * Checks if `value` is likely a prototype object. * @@ -38173,55 +38173,55 @@ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - + return value === proto; } - + module.exports = isPrototype; - + },{}],213:[function(require,module,exports){ var overArg = require('./_overArg'); - + /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); - + module.exports = nativeKeys; - + },{"./_overArg":216}],214:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); - + /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - + /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - + /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; - + /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; - + /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); - + module.exports = nodeUtil; - + },{"./_freeGlobal":209}],215:[function(require,module,exports){ /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; - + /** * Converts `value` to a string using `Object.prototype.toString`. * @@ -38232,9 +38232,9 @@ function objectToString(value) { return nativeObjectToString.call(value); } - + module.exports = objectToString; - + },{}],216:[function(require,module,exports){ /** * Creates a unary function that invokes `func` with its argument transformed. @@ -38249,20 +38249,20 @@ return func(transform(arg)); }; } - + module.exports = overArg; - + },{}],217:[function(require,module,exports){ var freeGlobal = require('./_freeGlobal'); - + /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - + /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); - + module.exports = root; - + },{"./_freeGlobal":209}],218:[function(require,module,exports){ /** * Creates a function that returns `value`. @@ -38288,22 +38288,22 @@ return value; }; } - + module.exports = constant; - + },{}],219:[function(require,module,exports){ var baseIsArguments = require('./_baseIsArguments'), isObjectLike = require('./isObjectLike'); - + /** Used for built-in method references. */ var objectProto = Object.prototype; - + /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; - + /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; - + /** * Checks if `value` is likely an `arguments` object. * @@ -38326,9 +38326,9 @@ return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; - + module.exports = isArguments; - + },{"./_baseIsArguments":204,"./isObjectLike":226}],220:[function(require,module,exports){ /** * Checks if `value` is classified as an `Array` object. @@ -38354,13 +38354,13 @@ * // => false */ var isArray = Array.isArray; - + module.exports = isArray; - + },{}],221:[function(require,module,exports){ var isFunction = require('./isFunction'), isLength = require('./isLength'); - + /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or @@ -38389,28 +38389,28 @@ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } - + module.exports = isArrayLike; - + },{"./isFunction":223,"./isLength":224}],222:[function(require,module,exports){ var root = require('./_root'), stubFalse = require('./stubFalse'); - + /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - + /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - + /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; - + /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; - + /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - + /** * Checks if `value` is a buffer. * @@ -38429,19 +38429,19 @@ * // => false */ var isBuffer = nativeIsBuffer || stubFalse; - + module.exports = isBuffer; - + },{"./_root":217,"./stubFalse":230}],223:[function(require,module,exports){ var baseGetTag = require('./_baseGetTag'), isObject = require('./isObject'); - + /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; - + /** * Checks if `value` is classified as a `Function` object. * @@ -38468,13 +38468,13 @@ var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } - + module.exports = isFunction; - + },{"./_baseGetTag":203,"./isObject":225}],224:[function(require,module,exports){ /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; - + /** * Checks if `value` is a valid array-like length. * @@ -38505,9 +38505,9 @@ return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } - + module.exports = isLength; - + },{}],225:[function(require,module,exports){ /** * Checks if `value` is the @@ -38538,9 +38538,9 @@ var type = typeof value; return value != null && (type == 'object' || type == 'function'); } - + module.exports = isObject; - + },{}],226:[function(require,module,exports){ /** * Checks if `value` is object-like. A value is object-like if it's not `null` @@ -38569,17 +38569,17 @@ function isObjectLike(value) { return value != null && typeof value == 'object'; } - + module.exports = isObjectLike; - + },{}],227:[function(require,module,exports){ var baseIsTypedArray = require('./_baseIsTypedArray'), baseUnary = require('./_baseUnary'), nodeUtil = require('./_nodeUtil'); - + /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - + /** * Checks if `value` is classified as a typed array. * @@ -38598,14 +38598,14 @@ * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - + module.exports = isTypedArray; - + },{"./_baseIsTypedArray":205,"./_baseUnary":208,"./_nodeUtil":214}],228:[function(require,module,exports){ var arrayLikeKeys = require('./_arrayLikeKeys'), baseKeys = require('./_baseKeys'), isArrayLike = require('./isArrayLike'); - + /** * Creates an array of the own enumerable property names of `object`. * @@ -38637,9 +38637,9 @@ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } - + module.exports = keys; - + },{"./_arrayLikeKeys":202,"./_baseKeys":206,"./isArrayLike":221}],229:[function(require,module,exports){ /** * This method returns `undefined`. @@ -38656,9 +38656,9 @@ function noop() { // No operation performed. } - + module.exports = noop; - + },{}],230:[function(require,module,exports){ /** * This method returns `false`. @@ -38676,38 +38676,38 @@ function stubFalse() { return false; } - + module.exports = stubFalse; - + },{}],231:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') - + 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) @@ -38724,7 +38724,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) @@ -38741,7 +38741,7 @@ 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) @@ -38758,7 +38758,7 @@ 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) @@ -38775,13 +38775,13 @@ 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 @@ -38790,12 +38790,12 @@ 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 = new Buffer(16) buffer.writeInt32LE(this._a, 0) @@ -38804,55 +38804,55 @@ 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 - + }).call(this,require("buffer").Buffer) },{"buffer":84,"hash-base":232,"inherits":180}],232:[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 { @@ -38860,10 +38860,10 @@ } catch (err) { error = err } - + callback(error) } - + HashBase.prototype._flush = function (callback) { var error = null try { @@ -38871,15 +38871,15 @@ } 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 @@ -38889,177 +38889,177 @@ 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":180,"safe-buffer":290,"stream":311}],233:[function(require,module,exports){ var bn = require('bn.js'); var brorand = require('brorand'); - + function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } module.exports = MillerRabin; - + MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; - + MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); - + // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0); - + return a; }; - + MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; - + MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); - + if (!k) k = Math.max(1, (len / 48) | 0); - + // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); - + var rn1 = n1.toRed(red); - + var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); - + var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; - + for (var i = 1; i < s; i++) { x = x.redSqr(); - + if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } - + if (i === s) return false; } - + return prime; }; - + MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); - + if (!k) k = Math.max(1, (len / 48) | 0); - + // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); - + var rn1 = n1.toRed(red); - + for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); - + var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; - + var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; - + for (var i = 1; i < s; i++) { x = x.redSqr(); - + if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } - + if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } - + return false; }; - + },{"bn.js":53,"brorand":54}],234:[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)); }; - + },{}],235:[function(require,module,exports){ 'use strict'; - + var utils = exports; - + function toArray(msg, enc) { if (Array.isArray(msg)) return msg.slice(); @@ -39091,7 +39091,7 @@ return res; } utils.toArray = toArray; - + function zero2(word) { if (word.length === 1) return '0' + word; @@ -39099,7 +39099,7 @@ return word; } utils.zero2 = zero2; - + function toHex(msg) { var res = ''; for (var i = 0; i < msg.length; i++) @@ -39107,20 +39107,20 @@ return res; } utils.toHex = toHex; - + utils.encode = function encode(arr, enc) { if (enc === 'hex') return toHex(arr); else return arr; }; - + },{}],236:[function(require,module,exports){ arguments[4][154][0].apply(exports,arguments) },{"dup":154}],237:[function(require,module,exports){ var BN = require('bn.js'); var stripHexPrefix = require('strip-hex-prefix'); - + /** * Returns a BN object, converts a number value to a BN * @param {String|Number|Object} `arg` input a string number, hex string number, number, BigNumber or BN object @@ -39138,13 +39138,13 @@ multiplier = new BN(-1, 10); } stringArg = stringArg === '' ? '0' : stringArg; - + if ((!stringArg.match(/^-?[0-9]+$/) && stringArg.match(/^[0-9A-Fa-f]+$/)) || stringArg.match(/^[a-fA-F]+$/) || (isHexPrefixed === true && stringArg.match(/^[0-9A-Fa-f]+$/))) { return new BN(stringArg, 16).mul(multiplier); } - + if ((stringArg.match(/^-?[0-9]+$/) || stringArg === '') && isHexPrefixed === false) { return new BN(stringArg, 10).mul(multiplier); } @@ -39153,46 +39153,46 @@ return new BN(arg.toString(10), 10); } } - + throw new Error('[number-to-bn] while converting number ' + JSON.stringify(arg) + ' to BN.js instance, error: invalid number value. Value must be an integer, hex string, BN or BigNumber instance. Note, decimals are not supported.'); } - + },{"bn.js":236,"strip-hex-prefix":318}],238:[function(require,module,exports){ /* object-assign (c) Sindre Sorhus @license MIT */ - + 'use strict'; /* eslint-disable no-unused-vars */ var getOwnPropertySymbols = Object.getOwnPropertySymbols; var hasOwnProperty = Object.prototype.hasOwnProperty; var propIsEnumerable = Object.prototype.propertyIsEnumerable; - + function toObject(val) { if (val === null || val === undefined) { throw new TypeError('Object.assign cannot be called with null or undefined'); } - + return Object(val); } - + function shouldUseNative() { try { if (!Object.assign) { return false; } - + // Detect buggy property enumeration order in older V8 versions. - + // https://bugs.chromium.org/p/v8/issues/detail?id=4118 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers test1[5] = 'de'; if (Object.getOwnPropertyNames(test1)[0] === '5') { return false; } - + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test2 = {}; for (var i = 0; i < 10; i++) { @@ -39204,7 +39204,7 @@ if (order2.join('') !== '0123456789') { return false; } - + // https://bugs.chromium.org/p/v8/issues/detail?id=3056 var test3 = {}; 'abcdefghijklmnopqrst'.split('').forEach(function (letter) { @@ -39214,28 +39214,28 @@ 'abcdefghijklmnopqrst') { return false; } - + return true; } catch (err) { // We don't expect any of the above to throw, but better to be safe. return false; } } - + module.exports = shouldUseNative() ? Object.assign : function (target, source) { var from; var to = toObject(target); var symbols; - + for (var s = 1; s < arguments.length; s++) { from = Object(arguments[s]); - + for (var key in from) { if (hasOwnProperty.call(from, key)) { to[key] = from[key]; } } - + if (getOwnPropertySymbols) { symbols = getOwnPropertySymbols(from); for (var i = 0; i < symbols.length; i++) { @@ -39245,36 +39245,36 @@ } } } - + return to; }; - + },{}],239:[function(require,module,exports){ // This file is the concatenation of many js files. // See http://github.com/jimhigson/oboe.js for the raw source - + // having a local undefined, window, Object etc allows slightly better minification: (function (window, Object, Array, Error, JSON, undefined ) { - + // v2.1.3 - + /* - + Copyright (c) 2013, Jim Higson - + 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 COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A @@ -39286,66 +39286,66 @@ 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. - + */ - - /** + + /** * Partially complete a function. - * + * * var add3 = partialComplete( function add(a,b){return a+b}, 3 ); - * + * * add3(4) // gives 7 - * + * * function wrap(left, right, cen){return left + " " + cen + " " + right;} - * + * * var pirateGreeting = partialComplete( wrap , "I'm", ", a mighty pirate!" ); - * - * pirateGreeting("Guybrush Threepwood"); + * + * pirateGreeting("Guybrush Threepwood"); * // gives "I'm Guybrush Threepwood, a mighty pirate!" */ var partialComplete = varArgs(function( fn, args ) { - + // this isn't the shortest way to write this but it does // avoid creating a new array each time to pass to fn.apply, - // otherwise could just call boundArgs.concat(callArgs) - + // otherwise could just call boundArgs.concat(callArgs) + var numBoundArgs = args.length; - + return varArgs(function( callArgs ) { - + for (var i = 0; i < callArgs.length; i++) { args[numBoundArgs + i] = callArgs[i]; } - - args.length = numBoundArgs + callArgs.length; - + + args.length = numBoundArgs + callArgs.length; + return fn.apply(this, args); - }); + }); }), - + /** * Compose zero or more functions: - * + * * compose(f1, f2, f3)(x) = f1(f2(f3(x)))) - * + * * The last (inner-most) function may take more than one parameter: - * + * * compose(f1, f2, f3)(x,y) = f1(f2(f3(x,y)))) */ compose = varArgs(function(fns) { - + var fnsList = arrayAsList(fns); - - function next(params, curFn) { - return [apply(params, curFn)]; + + function next(params, curFn) { + return [apply(params, curFn)]; } - + return varArgs(function(startParams){ - + return foldR(next, startParams, fnsList)[0]; }); }); - + /** * A more optimised version of compose that takes exactly two functions * @param f1 @@ -39356,141 +39356,141 @@ return f1.call(this,f2.apply(this,arguments)); } } - + /** * Generic form for a function to get a property from an object - * + * * var o = { * foo:'bar' * } - * + * * var getFoo = attr('foo') - * + * * fetFoo(o) // returns 'bar' - * + * * @param {String} key the property name */ function attr(key) { return function(o) { return o[key]; }; } - + /** - * Call a list of functions with the same args until one returns a + * Call a list of functions with the same args until one returns a * truthy result. Similar to the || operator. - * + * * So: * lazyUnion([f1,f2,f3 ... fn])( p1, p2 ... pn ) - * - * Is equivalent to: - * apply([p1, p2 ... pn], f1) || - * apply([p1, p2 ... pn], f2) || - * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn]) - * + * + * Is equivalent to: + * apply([p1, p2 ... pn], f1) || + * apply([p1, p2 ... pn], f2) || + * apply([p1, p2 ... pn], f3) ... apply(fn, [p1, p2 ... pn]) + * * @returns the first return value that is given that is truthy. */ var lazyUnion = varArgs(function(fns) { - + return varArgs(function(params){ - + var maybeValue; - + for (var i = 0; i < len(fns); i++) { - + maybeValue = apply(params, fns[i]); - + if( maybeValue ) { return maybeValue; } } }); - }); - + }); + /** * This file declares various pieces of functional programming. - * + * * This isn't a general purpose functional library, to keep things small it * has just the parts useful for Oboe.js. */ - - + + /** * Call a single function with the given arguments array. - * Basically, a functional-style version of the OO-style Function#apply for + * Basically, a functional-style version of the OO-style Function#apply for * when we don't care about the context ('this') of the call. - * + * * The order of arguments allows partial completion of the arguments array */ function apply(args, fn) { return fn.apply(undefined, args); } - + /** - * Define variable argument functions but cut out all that tedious messing about + * Define variable argument functions but cut out all that tedious messing about * with the arguments object. Delivers the variable-length part of the arguments * list as an array. - * + * * Eg: - * + * * var myFunction = varArgs( * function( fixedArgument, otherFixedArgument, variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * } * ) - * + * * myFunction('a', 'b', 1, 2, 3); // logs [1,2,3] - * + * * var myOtherFunction = varArgs(function( variableNumberOfArguments ){ * console.log( variableNumberOfArguments ); * }) - * + * * myFunction(1, 2, 3); // logs [1,2,3] - * + * */ function varArgs(fn){ - + var numberOfFixedArguments = fn.length -1, - slice = Array.prototype.slice; - - + slice = Array.prototype.slice; + + if( numberOfFixedArguments == 0 ) { - // an optimised case for when there are no fixed args: - + // an optimised case for when there are no fixed args: + return function(){ return fn.call(this, slice.call(arguments)); } - + } else if( numberOfFixedArguments == 1 ) { // an optimised case for when there are is one fixed args: - + return function(){ return fn.call(this, arguments[0], slice.call(arguments, 1)); } } - - // general case - + + // general case + // we know how many arguments fn will always take. Create a // fixed-size array to hold that many, to be re-used on // every call to the returned function - var argsHolder = Array(fn.length); - + var argsHolder = Array(fn.length); + return function(){ - + for (var i = 0; i < numberOfFixedArguments; i++) { - argsHolder[i] = arguments[i]; + argsHolder[i] = arguments[i]; } - - argsHolder[numberOfFixedArguments] = + + argsHolder[numberOfFixedArguments] = slice.call(arguments, numberOfFixedArguments); - - return fn.apply( this, argsHolder); - } + + return fn.apply( this, argsHolder); + } } - - + + /** * Swap the order of parameters to a binary function - * + * * A bit like this flip: http://zvon.org/other/haskell/Outputprelude/flip_f.html */ function flip(fn){ @@ -39498,38 +39498,38 @@ return fn(b,a); } } - - + + /** * Create a function which is the intersection of two other functions. - * + * * Like the && operator, if the first is truthy, the second is never called, * otherwise the return value from the second is returned. */ function lazyIntersection(fn1, fn2) { - + return function (param) { - + return fn1(param) && fn2(param); - }; + }; } - + /** * A function which does nothing */ function noop(){} - + /** * A function which is always happy */ function always(){return true} - + /** * Create a function which always returns the same * value - * + * * var return3 = functor(3); - * + * * return3() // gives 3 * return3() // still gives 3 * return3() // will always give 3 @@ -39539,58 +39539,58 @@ return val; } } - + /** - * This file defines some loosely associated syntactic sugar for - * Javascript programming + * This file defines some loosely associated syntactic sugar for + * Javascript programming */ - - + + /** * Returns true if the given candidate is of type T */ function isOfType(T, maybeSomething){ return maybeSomething && maybeSomething.constructor === T; } - - var len = attr('length'), + + var len = attr('length'), isString = partialComplete(isOfType, String); - - /** + + /** * I don't like saying this: - * + * * foo !=== undefined - * + * * because of the double-negative. I find this: - * + * * defined(foo) - * + * * easier to read. - */ + */ function defined( value ) { return value !== undefined; } - + /** - * Returns true if object o has a key named like every property in - * the properties array. Will give false if any are missing, or if o + * Returns true if object o has a key named like every property in + * the properties array. Will give false if any are missing, or if o * is not an object. */ function hasAllProperties(fieldList, o) { - - return (o instanceof Object) + + return (o instanceof Object) && - all(function (field) { - return (field in o); + all(function (field) { + return (field in o); }, fieldList); } /** * Like cons in Lisp */ function cons(x, xs) { - + /* Internally lists are linked 2-element Javascript arrays. - + Ideally the return here would be Object.freeze([x,xs]) so that bugs related to mutation are found fast. However, cons is right on the critical path for @@ -39600,218 +39600,218 @@ run faster) this should be considered for restoration. */ - + return [x,xs]; } - + /** * The empty list */ var emptyList = null, - + /** * Get the head of a list. - * + * * Ie, head(cons(a,b)) = a */ head = attr(0), - + /** * Get the tail of a list. - * + * * Ie, tail(cons(a,b)) = b */ tail = attr(1); - - - /** - * Converts an array to a list - * + + + /** + * Converts an array to a list + * * asList([a,b,c]) - * + * * is equivalent to: - * - * cons(a, cons(b, cons(c, emptyList))) + * + * cons(a, cons(b, cons(c, emptyList))) **/ function arrayAsList(inputArray){ - - return reverseList( + + return reverseList( inputArray.reduce( flip(cons), - emptyList + emptyList ) ); } - + /** * A varargs version of arrayAsList. Works a bit like list * in LISP. - * - * list(a,b,c) - * + * + * list(a,b,c) + * * is equivalent to: - * + * * cons(a, cons(b, cons(c, emptyList))) */ var list = varArgs(arrayAsList); - + /** * Convert a list back to a js native array */ function listAsArray(list){ - + return foldR( function(arraySoFar, listItem){ - + arraySoFar.unshift(listItem); return arraySoFar; - + }, [], list ); - + } - + /** - * Map a function over a list + * Map a function over a list */ function map(fn, list) { - + return list ? cons(fn(head(list)), map(fn,tail(list))) : emptyList ; } - + /** * foldR implementation. Reduce a list down to a single value. - * - * @pram {Function} fn (rightEval, curVal) -> result + * + * @pram {Function} fn (rightEval, curVal) -> result */ function foldR(fn, startValue, list) { - - return list + + return list ? fn(foldR(fn, startValue, tail(list)), head(list)) : startValue ; } - + /** * foldR implementation. Reduce a list down to a single value. - * - * @pram {Function} fn (rightEval, curVal) -> result + * + * @pram {Function} fn (rightEval, curVal) -> result */ function foldR1(fn, list) { - - return tail(list) + + return tail(list) ? fn(foldR1(fn, tail(list)), head(list)) : head(list) ; } - - + + /** - * Return a list like the one given but with the first instance equal - * to item removed + * Return a list like the one given but with the first instance equal + * to item removed */ function without(list, test, removedFn) { - + return withoutInner(list, removedFn || noop); - + function withoutInner(subList, removedFn) { - return subList - ? ( test(head(subList)) - ? (removedFn(head(subList)), tail(subList)) + return subList + ? ( test(head(subList)) + ? (removedFn(head(subList)), tail(subList)) : cons(head(subList), withoutInner(tail(subList), removedFn)) ) : emptyList ; - } + } } - - /** - * Returns true if the given function holds for every item in - * the list, false otherwise + + /** + * Returns true if the given function holds for every item in + * the list, false otherwise */ function all(fn, list) { - - return !list || + + return !list || ( fn(head(list)) && all(fn, tail(list)) ); } - + /** * Call every function in a list of functions with the same arguments - * - * This doesn't make any sense if we're doing pure functional because + * + * This doesn't make any sense if we're doing pure functional because * it doesn't return anything. Hence, this is only really useful if the - * functions being called have side-effects. + * functions being called have side-effects. */ function applyEach(fnList, args) { - - if( fnList ) { + + if( fnList ) { head(fnList).apply(null, args); - + applyEach(tail(fnList), args); } } - + /** * Reverse the order of a list */ - function reverseList(list){ - + function reverseList(list){ + // js re-implementation of 3rd solution from: // http://www.haskell.org/haskellwiki/99_questions/Solutions/5 function reverseInner( list, reversedAlready ) { if( !list ) { return reversedAlready; } - + return reverseInner(tail(list), cons(head(list), reversedAlready)) } - + return reverseInner(list, emptyList); } - + function first(test, list) { return list && - (test(head(list)) - ? head(list) - : first(test,tail(list))); - } - - /* - This is a slightly hacked-up browser only version of clarinet - - * some features removed to help keep browser Oboe under + (test(head(list)) + ? head(list) + : first(test,tail(list))); + } + + /* + This is a slightly hacked-up browser only version of clarinet + + * some features removed to help keep browser Oboe under the 5k micro-library limit * plug directly into event bus - + For the original go here: https://github.com/dscape/clarinet - + We receive the events: STREAM_DATA STREAM_END - + We emit the events: SAX_KEY SAX_VALUE_OPEN - SAX_VALUE_CLOSE - FAIL_EVENT + SAX_VALUE_CLOSE + FAIL_EVENT */ - + function clarinet(eventBus) { "use strict"; - - var + + var // shortcut some events on the bus emitSaxKey = eventBus(SAX_KEY).emit, emitValueOpen = eventBus(SAX_VALUE_OPEN).emit, emitValueClose = eventBus(SAX_VALUE_CLOSE).emit, emitFail = eventBus(FAIL_EVENT).emit, - + MAX_BUFFER_LENGTH = 64 * 1024 , stringTokenPattern = /[\\"\n]/g , _n = 0 - + // states , BEGIN = _n++ , VALUE = _n++ // general stuff @@ -39834,14 +39834,14 @@ , NULL3 = _n++ // l , NUMBER_DECIMAL_POINT = _n++ // . , NUMBER_DIGIT = _n // [0-9] - + // setup initial parser values , bufferCheckPosition = MAX_BUFFER_LENGTH - , latestError - , c - , p + , latestError + , c + , p , textNode = undefined - , numberNode = "" + , numberNode = "" , slashed = false , closed = false , state = BEGIN @@ -39853,11 +39853,11 @@ , column = 0 //mostly for error reporting , line = 1 ; - + function checkBufferLength () { - + var maxActual = 0; - + if (textNode !== undefined && textNode.length > MAX_BUFFER_LENGTH) { emitError("Max buffer length exceeded: textNode"); maxActual = Math.max(maxActual, textNode.length); @@ -39866,104 +39866,104 @@ emitError("Max buffer length exceeded: numberNode"); maxActual = Math.max(maxActual, numberNode.length); } - + bufferCheckPosition = (MAX_BUFFER_LENGTH - maxActual) + position; } - + eventBus(STREAM_DATA).on(handleData); - - /* At the end of the http content close the clarinet - This will provide an error if the total content provided was not + + /* At the end of the http content close the clarinet + This will provide an error if the total content provided was not valid json, ie if not all arrays, objects and Strings closed properly */ - eventBus(STREAM_END).on(handleStreamEnd); - + eventBus(STREAM_END).on(handleStreamEnd); + function emitError (errorString) { if (textNode !== undefined) { emitValueOpen(textNode); emitValueClose(); textNode = undefined; } - + latestError = Error(errorString + "\nLn: "+line+ "\nCol: "+column+ "\nChr: "+c); - + emitFail(errorReport(undefined, undefined, latestError)); } - + function handleStreamEnd() { if( state == BEGIN ) { // Handle the case where the stream closes without ever receiving // any input. This isn't an error - response bodies can be blank, // particularly for 204 http responses - + // Because of how Oboe is currently implemented, we parse a // completely empty stream as containing an empty object. // This is because Oboe's done event is only fired when the // root object of the JSON stream closes. - + // This should be decoupled and attached instead to the input stream // from the http (or whatever) resource ending. // If this decoupling could happen the SAX parser could simply emit // zero events on a completely empty input. emitValueOpen({}); emitValueClose(); - + closed = true; return; } - + if (state !== VALUE || depth !== 0) emitError("Unexpected end"); - + if (textNode !== undefined) { emitValueOpen(textNode); emitValueClose(); textNode = undefined; } - + closed = true; } - + function whitespace(c){ return c == '\r' || c == '\n' || c == ' ' || c == '\t'; } - + function handleData (chunk) { - + // this used to throw the error but inside Oboe we will have already // gotten the error when it was emitted. The important thing is to // not continue with the parse. if (latestError) return; - + if (closed) { return emitError("Cannot write after close"); } - + var i = 0; - c = chunk[0]; - + c = chunk[0]; + while (c) { p = c; c = chunk[i++]; if(!c) break; - + position ++; if (c == "\n") { line ++; column = 0; } else column ++; switch (state) { - + case BEGIN: if (c === "{") state = OPEN_OBJECT; else if (c === "[") state = OPEN_ARRAY; else if (!whitespace(c)) return emitError("Non-whitespace before {[."); continue; - + case OPEN_KEY: case OPEN_OBJECT: if (whitespace(c)) continue; @@ -39981,15 +39981,15 @@ else return emitError("Malformed object key should start with \" "); continue; - + case CLOSE_KEY: case CLOSE_OBJECT: if (whitespace(c)) continue; - + if(c===':') { if(state === CLOSE_OBJECT) { stack.push(CLOSE_OBJECT); - + if (textNode !== undefined) { // was previously (in upstream Clarinet) one event // - object open came with the text of the first @@ -40023,16 +40023,16 @@ textNode = undefined; } state = OPEN_KEY; - } else + } else return emitError('Bad object'); continue; - + case OPEN_ARRAY: // after an array there always a value case VALUE: if (whitespace(c)) continue; if(state===OPEN_ARRAY) { emitValueOpen([]); - depth++; + depth++; state = VALUE; if(c === ']') { emitValueClose(); @@ -40057,10 +40057,10 @@ } else if('123456789'.indexOf(c) !== -1) { numberNode += c; state = NUMBER_DIGIT; - } else + } else return emitError("Bad value"); continue; - + case CLOSE_ARRAY: if(c===',') { stack.push(CLOSE_ARRAY); @@ -40081,20 +40081,20 @@ state = stack.pop() || VALUE; } else if (whitespace(c)) continue; - else + else return emitError('Bad array'); continue; - + case STRING: if (textNode === undefined) { textNode = ""; } - + // thanks thejh, this is an about 50% performance improvement. var starti = i-1; - + STRING_BIGLOOP: while (true) { - + // zero means "no unicode active". 1-4 mean "parse some more". end after 4. while (unicodeI > 0) { unicodeS += c; @@ -40140,7 +40140,7 @@ if (!c) break; else continue; } - + stringTokenPattern.lastIndex = i; var reResult = stringTokenPattern.exec(chunk); if (!reResult) { @@ -40156,21 +40156,21 @@ } } continue; - + case TRUE: if (!c) continue; // strange buffers if (c==='r') state = TRUE2; else return emitError( 'Invalid true started with t'+ c); continue; - + case TRUE2: if (!c) continue; if (c==='u') state = TRUE3; else return emitError('Invalid true started with tr'+ c); continue; - + case TRUE3: if (!c) continue; if(c==='e') { @@ -40180,28 +40180,28 @@ } else return emitError('Invalid true started with tru'+ c); continue; - + case FALSE: if (!c) continue; if (c==='a') state = FALSE2; else return emitError('Invalid false started with f'+ c); continue; - + case FALSE2: if (!c) continue; if (c==='l') state = FALSE3; else return emitError('Invalid false started with fa'+ c); continue; - + case FALSE3: if (!c) continue; if (c==='s') state = FALSE4; else return emitError('Invalid false started with fal'+ c); continue; - + case FALSE4: if (!c) continue; if (c==='e') { @@ -40211,39 +40211,39 @@ } else return emitError('Invalid false started with fals'+ c); continue; - + case NULL: if (!c) continue; if (c==='u') state = NULL2; else return emitError('Invalid null started with n'+ c); continue; - + case NULL2: if (!c) continue; if (c==='l') state = NULL3; else return emitError('Invalid null started with nu'+ c); continue; - + case NULL3: if (!c) continue; if(c==='l') { emitValueOpen(null); emitValueClose(); state = stack.pop() || VALUE; - } else + } else return emitError('Invalid null started with nul'+ c); continue; - + case NUMBER_DECIMAL_POINT: if(c==='.') { numberNode += c; state = NUMBER_DIGIT; - } else + } else return emitError('Leading zero not followed by .'); continue; - + case NUMBER_DIGIT: if('0123456789'.indexOf(c) !== -1) numberNode += c; else if (c==='.') { @@ -40269,7 +40269,7 @@ state = stack.pop() || VALUE; } continue; - + default: return emitError("Unknown state: " + state); } @@ -40278,72 +40278,72 @@ checkBufferLength(); } } - - - /** + + + /** * A bridge used to assign stateless functions to listen to clarinet. - * + * * As well as the parameter from clarinet, each callback will also be passed * the result of the last callback. - * + * * This may also be used to clear all listeners by assigning zero handlers: - * + * * ascentManager( clarinet, {} ) */ function ascentManager(oboeBus, handlers){ "use strict"; - + var listenerId = {}, ascent; - + function stateAfter(handler) { return function(param){ ascent = handler( ascent, param); } } - + for( var eventName in handlers ) { - + oboeBus(eventName).on(stateAfter(handlers[eventName]), listenerId); } - + oboeBus(NODE_SWAP).on(function(newNode) { - + var oldHead = head(ascent), key = keyOf(oldHead), ancestors = tail(ascent), parentNode; - + if( ancestors ) { parentNode = nodeOf(head(ancestors)); parentNode[key] = newNode; } }); - + oboeBus(NODE_DROP).on(function() { - + var oldHead = head(ascent), key = keyOf(oldHead), ancestors = tail(ascent), parentNode; - + if( ancestors ) { parentNode = nodeOf(head(ancestors)); - + delete parentNode[key]; } }); - + oboeBus(ABORTING).on(function(){ - + for( var eventName in handlers ) { oboeBus(eventName).un(listenerId); } - }); + }); } - + // based on gist https://gist.github.com/monsur/706839 - + /** * XmlHttpRequest's getAllResponseHeaders() method returns a string of response * headers according to the format described here: @@ -40352,33 +40352,33 @@ */ function parseResponseHeaders(headerStr) { var headers = {}; - + headerStr && headerStr.split('\u000d\u000a') .forEach(function(headerPair){ - + // Can't use split() here because it does the wrong thing // if the header value has the string ": " in it. var index = headerPair.indexOf('\u003a\u0020'); - - headers[headerPair.substring(0, index)] + + headers[headerPair.substring(0, index)] = headerPair.substring(index + 2); }); - + return headers; } - + /** * Detect if a given URL is cross-origin in the scope of the * current page. - * + * * Browser only (since cross-origin has no meaning in Node.js) * * @param {Object} pageLocation - as in window.location - * @param {Object} ajaxHost - an object like window.location describing the + * @param {Object} ajaxHost - an object like window.location describing the * origin of the url that we want to ajax in */ function isCrossOrigin(pageLocation, ajaxHost) { - + /* * NB: defaultPort only knows http and https. * Returns undefined otherwise. @@ -40386,65 +40386,65 @@ function defaultPort(protocol) { return {'http:':80, 'https:':443}[protocol]; } - + function portOf(location) { // pageLocation should always have a protocol. ajaxHost if no port or // protocol is specified, should use the port of the containing page - + return location.port || defaultPort(location.protocol||pageLocation.protocol); } - + // if ajaxHost doesn't give a domain, port is the same as pageLocation // it can't give a protocol but not a domain // it can't give a port but not a domain - + return !!( (ajaxHost.protocol && (ajaxHost.protocol != pageLocation.protocol)) || (ajaxHost.host && (ajaxHost.host != pageLocation.host)) || (ajaxHost.host && (portOf(ajaxHost) != portOf(pageLocation))) ); } - + /* turn any url into an object like window.location */ function parseUrlOrigin(url) { // url could be domain-relative // url could give a domain - + // cross origin means: // same domain // same port // some protocol - // so, same everything up to the first (single) slash + // so, same everything up to the first (single) slash // if such is given // - // can ignore everything after that - + // can ignore everything after that + var URL_HOST_PATTERN = /(\w+:)?(?:\/\/)([\w.-]+)?(?::(\d+))?\/?/, - + // if no match, use an empty array so that // subexpressions 1,2,3 are all undefined // and will ultimately return all empty // strings as the parse result: urlHostMatch = URL_HOST_PATTERN.exec(url) || []; - + return { protocol: urlHostMatch[1] || '', host: urlHostMatch[2] || '', port: urlHostMatch[3] || '' }; } - + function httpTransport(){ return new XMLHttpRequest(); } - + /** - * A wrapper around the browser XmlHttpRequest object that raises an + * A wrapper around the browser XmlHttpRequest object that raises an * event whenever a new part of the response is available. - * - * In older browsers progressive reading is impossible so all the + * + * In older browsers progressive reading is impossible so all the * content is given in a single call. For newer ones several events * should be raised, allowing progressive interpretation of the response. - * + * * @param {Function} oboeBus an event bus local to this Oboe instance * @param {XMLHttpRequest} xhr the xhr to use as the transport. Under normal * operation, will have been created using httpTransport() above @@ -40456,61 +40456,61 @@ * @param {Object} [headers] the http request headers to send * @param {boolean} withCredentials the XHR withCredentials property will be * set to this value - */ + */ function streamingHttp(oboeBus, xhr, method, url, data, headers, withCredentials) { - + "use strict"; - + var emitStreamData = oboeBus(STREAM_DATA).emit, emitFail = oboeBus(FAIL_EVENT).emit, numberOfCharsAlreadyGivenToCallback = 0, stillToSendStartEvent = true; - - // When an ABORTING message is put on the event bus abort - // the ajax request + + // When an ABORTING message is put on the event bus abort + // the ajax request oboeBus( ABORTING ).on( function(){ - - // if we keep the onreadystatechange while aborting the XHR gives + + // if we keep the onreadystatechange while aborting the XHR gives // a callback like a successful call so first remove this listener // by assigning null: xhr.onreadystatechange = null; - + xhr.abort(); }); - - /** + + /** * Handle input from the underlying xhr: either a state change, * the progress event or the request being complete. */ function handleProgress() { - + var textSoFar = xhr.responseText, newText = textSoFar.substr(numberOfCharsAlreadyGivenToCallback); - - + + /* Raise the event for new text. - - On older browsers, the new text is the whole response. - On newer/better ones, the fragment part that we got since + + On older browsers, the new text is the whole response. + On newer/better ones, the fragment part that we got since last progress. */ - + if( newText ) { emitStreamData( newText ); - } - + } + numberOfCharsAlreadyGivenToCallback = len(textSoFar); } - - + + if('onprogress' in xhr){ // detect browser support for progressive delivery xhr.onprogress = handleProgress; } - + xhr.onreadystatechange = function() { - + function sendStartIfNotAlready() { // Internet Explorer is very unreliable as to when xhr.status etc can - // be read so has to be protected with try/catch and tried again on + // be read so has to be protected with try/catch and tried again on // the next readyState if it fails try{ stillToSendStartEvent && oboeBus( HTTP_START ).emit( @@ -40519,111 +40519,111 @@ stillToSendStartEvent = false; } catch(e){/* do nothing, will try again on next readyState*/} } - + switch( xhr.readyState ) { - + case 2: // HEADERS_RECEIVED case 3: // LOADING return sendStartIfNotAlready(); - + case 4: // DONE sendStartIfNotAlready(); // if xhr.status hasn't been available yet, it must be NOW, huh IE? - + // is this a 2xx http code? var successful = String(xhr.status)[0] == 2; - + if( successful ) { // In Chrome 29 (not 28) no onprogress is emitted when a response // is complete before the onload. We need to always do handleInput // in case we get the load but have not had a final progress event. // This looks like a bug and may change in future but let's take - // the safest approach and assume we might not have received a + // the safest approach and assume we might not have received a // progress event for each part of the response handleProgress(); - + oboeBus(STREAM_END).emit(); } else { - + emitFail( errorReport( - xhr.status, + xhr.status, xhr.responseText )); } } }; - + try{ - + xhr.open(method, url, true); - + for( var headerName in headers ){ xhr.setRequestHeader(headerName, headers[headerName]); } - + if( !isCrossOrigin(window.location, parseUrlOrigin(url)) ) { xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); } - + xhr.withCredentials = withCredentials; - + xhr.send(data); - + } catch( e ) { - + // To keep a consistent interface with Node, we can't emit an event here. // Node's streaming http adaptor receives the error as an asynchronous // event rather than as an exception. If we emitted now, the Oboe user // has had no chance to add a .fail listener so there is no way // the event could be useful. For both these reasons defer the - // firing to the next JS frame. + // firing to the next JS frame. window.setTimeout( partialComplete(emitFail, errorReport(undefined, undefined, e)) , 0 ); - } + } } - + var jsonPathSyntax = (function() { - + var - - /** - * Export a regular expression as a simple function by exposing just - * the Regex#exec. This allows regex tests to be used under the same + + /** + * Export a regular expression as a simple function by exposing just + * the Regex#exec. This allows regex tests to be used under the same * interface as differently implemented tests, or for a user of the * tests to not concern themselves with their implementation as regular * expressions. - * + * * This could also be expressed point-free as: * Function.prototype.bind.bind(RegExp.prototype.exec), - * - * But that's far too confusing! (and not even smaller once minified + * + * But that's far too confusing! (and not even smaller once minified * and gzipped) */ regexDescriptor = function regexDescriptor(regex) { return regex.exec.bind(regex); } - + /** * Join several regular expressions and express as a function. * This allows the token patterns to reuse component regular expressions * instead of being expressed in full using huge and confusing regular * expressions. - */ + */ , jsonPathClause = varArgs(function( componentRegexes ) { - - // The regular expressions all start with ^ because we - // only want to find matches at the start of the - // JSONPath fragment we are inspecting + + // The regular expressions all start with ^ because we + // only want to find matches at the start of the + // JSONPath fragment we are inspecting componentRegexes.unshift(/^/); - + return regexDescriptor( RegExp( componentRegexes.map(attr('source')).join('') ) ); }) - + , possiblyCapturing = /(\$?)/ , namedNode = /([\w-_]+|\*)/ , namePlaceholder = /()/ @@ -40631,388 +40631,388 @@ , numberedNodeInArrayNotation = /\[(\d+|\*)\]/ , fieldList = /{([\w ]*?)}/ , optionalFieldList = /(?:{([\w ]*?)})?/ - - - // foo or * - , jsonPathNamedNodeInObjectNotation = jsonPathClause( - possiblyCapturing, - namedNode, + + + // foo or * + , jsonPathNamedNodeInObjectNotation = jsonPathClause( + possiblyCapturing, + namedNode, optionalFieldList ) - - // ["foo"] - , jsonPathNamedNodeInArrayNotation = jsonPathClause( - possiblyCapturing, - nodeInArrayNotation, + + // ["foo"] + , jsonPathNamedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + nodeInArrayNotation, optionalFieldList - ) - - // [2] or [*] - , jsonPathNumberedNodeInArrayNotation = jsonPathClause( - possiblyCapturing, - numberedNodeInArrayNotation, + ) + + // [2] or [*] + , jsonPathNumberedNodeInArrayNotation = jsonPathClause( + possiblyCapturing, + numberedNodeInArrayNotation, optionalFieldList ) - - // {a b c} - , jsonPathPureDuckTyping = jsonPathClause( - possiblyCapturing, - namePlaceholder, + + // {a b c} + , jsonPathPureDuckTyping = jsonPathClause( + possiblyCapturing, + namePlaceholder, fieldList ) - + // .. - , jsonPathDoubleDot = jsonPathClause(/\.\./) - + , jsonPathDoubleDot = jsonPathClause(/\.\./) + // . - , jsonPathDot = jsonPathClause(/\./) - + , jsonPathDot = jsonPathClause(/\./) + // ! , jsonPathBang = jsonPathClause( - possiblyCapturing, + possiblyCapturing, /!/ - ) - + ) + // nada! - , emptyString = jsonPathClause(/$/) - + , emptyString = jsonPathClause(/$/) + ; - - - /* We export only a single function. When called, this function injects - into another function the descriptors from above. + + + /* We export only a single function. When called, this function injects + into another function the descriptors from above. */ - return function (fn){ - return fn( + return function (fn){ + return fn( lazyUnion( jsonPathNamedNodeInObjectNotation , jsonPathNamedNodeInArrayNotation , jsonPathNumberedNodeInArrayNotation - , jsonPathPureDuckTyping + , jsonPathPureDuckTyping ) , jsonPathDoubleDot , jsonPathDot , jsonPathBang - , emptyString + , emptyString ); - }; - + }; + }()); /** * Get a new key->node mapping - * + * * @param {String|Number} key * @param {Object|Array|String|Number|null} node a value found in the json */ function namedNode(key, node) { return {key:key, node:node}; } - + /** get the key of a namedNode */ var keyOf = attr('key'); - + /** get the node from a namedNode */ var nodeOf = attr('node'); - /** + /** * This file provides various listeners which can be used to build up * a changing ascent based on the callbacks provided by Clarinet. It listens * to the low-level events from Clarinet and emits higher-level ones. - * + * * The building up is stateless so to track a JSON file * ascentManager.js is required to store the ascent state * between calls. */ - - - - /** - * A special value to use in the path list to represent the path 'to' a root - * object (which doesn't really have any path). This prevents the need for - * special-casing detection of the root object and allows it to be treated - * like any other object. We might think of this as being similar to the - * 'unnamed root' domain ".", eg if I go to - * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates + + + + /** + * A special value to use in the path list to represent the path 'to' a root + * object (which doesn't really have any path). This prevents the need for + * special-casing detection of the root object and allows it to be treated + * like any other object. We might think of this as being similar to the + * 'unnamed root' domain ".", eg if I go to + * http://en.wikipedia.org./wiki/En/Main_page the dot after 'org' deliminates * the unnamed root of the DNS. - * - * This is kept as an object to take advantage that in Javascript's OO objects - * are guaranteed to be distinct, therefore no other object can possibly clash - * with this one. Strings, numbers etc provide no such guarantee. + * + * This is kept as an object to take advantage that in Javascript's OO objects + * are guaranteed to be distinct, therefore no other object can possibly clash + * with this one. Strings, numbers etc provide no such guarantee. **/ var ROOT_PATH = {}; - - + + /** - * Create a new set of handlers for clarinet's events, bound to the emit - * function given. - */ + * Create a new set of handlers for clarinet's events, bound to the emit + * function given. + */ function incrementalContentBuilder( oboeBus ) { - + var emitNodeOpened = oboeBus(NODE_OPENED).emit, emitNodeClosed = oboeBus(NODE_CLOSED).emit, emitRootOpened = oboeBus(ROOT_PATH_FOUND).emit, emitRootClosed = oboeBus(ROOT_NODE_FOUND).emit; - + function arrayIndicesAreKeys( possiblyInconsistentAscent, newDeepestNode) { - - /* for values in arrays we aren't pre-warned of the coming paths - (Clarinet gives no call to onkey like it does for values in objects) - so if we are in an array we need to create this path ourselves. The - key will be len(parentNode) because array keys are always sequential + + /* for values in arrays we aren't pre-warned of the coming paths + (Clarinet gives no call to onkey like it does for values in objects) + so if we are in an array we need to create this path ourselves. The + key will be len(parentNode) because array keys are always sequential numbers. */ - + var parentNode = nodeOf( head( possiblyInconsistentAscent)); - + return isOfType( Array, parentNode) ? - keyFound( possiblyInconsistentAscent, - len(parentNode), + keyFound( possiblyInconsistentAscent, + len(parentNode), newDeepestNode ) - : + : // nothing needed, return unchanged - possiblyInconsistentAscent + possiblyInconsistentAscent ; } - + function nodeOpened( ascent, newDeepestNode ) { - + if( !ascent ) { - // we discovered the root node, + // we discovered the root node, emitRootOpened( newDeepestNode); - - return keyFound( ascent, ROOT_PATH, newDeepestNode); + + return keyFound( ascent, ROOT_PATH, newDeepestNode); } - + // we discovered a non-root node - - var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), + + var arrayConsistentAscent = arrayIndicesAreKeys( ascent, newDeepestNode), ancestorBranches = tail( arrayConsistentAscent), previouslyUnmappedName = keyOf( head( arrayConsistentAscent)); - - appendBuiltContent( - ancestorBranches, - previouslyUnmappedName, - newDeepestNode + + appendBuiltContent( + ancestorBranches, + previouslyUnmappedName, + newDeepestNode ); - - return cons( - namedNode( previouslyUnmappedName, newDeepestNode ), + + return cons( + namedNode( previouslyUnmappedName, newDeepestNode ), ancestorBranches - ); + ); } - - + + /** * Add a new value to the object we are building up to represent the * parsed JSON */ function appendBuiltContent( ancestorBranches, key, node ){ - + nodeOf( head( ancestorBranches))[key] = node; } - - + + /** * For when we find a new key in the json. - * - * @param {String|Number|Object} newDeepestName the key. If we are in an - * array will be a number, otherwise a string. May take the special + * + * @param {String|Number|Object} newDeepestName the key. If we are in an + * array will be a number, otherwise a string. May take the special * value ROOT_PATH if the root node has just been found - * - * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode] - * usually this won't be known so can be undefined. Can't use null + * + * @param {String|Number|Object|Array|Null|undefined} [maybeNewDeepestNode] + * usually this won't be known so can be undefined. Can't use null * to represent unknown because null is a valid value in JSON - **/ + **/ function keyFound(ascent, newDeepestName, maybeNewDeepestNode) { - + if( ascent ) { // if not root - + // If we have the key but (unless adding to an array) no known value - // yet. Put that key in the output but against no defined value: + // yet. Put that key in the output but against no defined value: appendBuiltContent( ascent, newDeepestName, maybeNewDeepestNode ); } - - var ascentWithNewPath = cons( - namedNode( newDeepestName, - maybeNewDeepestNode), + + var ascentWithNewPath = cons( + namedNode( newDeepestName, + maybeNewDeepestNode), ascent ); - + emitNodeOpened( ascentWithNewPath); - + return ascentWithNewPath; } - - + + /** * For when the current node ends. */ function nodeClosed( ascent ) { - + emitNodeClosed( ascent); - + return tail( ascent) || // If there are no nodes left in the ascent the root node - // just closed. Emit a special event for this: + // just closed. Emit a special event for this: emitRootClosed(nodeOf(head(ascent))); - } - + } + var contentBuilderHandlers = {}; contentBuilderHandlers[SAX_VALUE_OPEN] = nodeOpened; contentBuilderHandlers[SAX_VALUE_CLOSE] = nodeClosed; contentBuilderHandlers[SAX_KEY] = keyFound; return contentBuilderHandlers; } - + /** - * The jsonPath evaluator compiler used for Oboe.js. - * - * One function is exposed. This function takes a String JSONPath spec and + * The jsonPath evaluator compiler used for Oboe.js. + * + * One function is exposed. This function takes a String JSONPath spec and * returns a function to test candidate ascents for matches. - * + * * String jsonPath -> (List ascent) -> Boolean|Object * - * This file is coded in a pure functional style. That is, no function has - * side effects, every function evaluates to the same value for the same + * This file is coded in a pure functional style. That is, no function has + * side effects, every function evaluates to the same value for the same * arguments and no variables are reassigned. - */ - // the call to jsonPathSyntax injects the token syntaxes that are needed + */ + // the call to jsonPathSyntax injects the token syntaxes that are needed // inside the compiler - var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax, - doubleDotSyntax, + var jsonPathCompiler = jsonPathSyntax(function (pathNodeSyntax, + doubleDotSyntax, dotSyntax, bangSyntax, emptySyntax ) { - + var CAPTURING_INDEX = 1; var NAME_INDEX = 2; var FIELD_LIST_INDEX = 3; - + var headKey = compose2(keyOf, head), headNode = compose2(nodeOf, head); - + /** * Create an evaluator function for a named path node, expressed in the * JSONPath like: * foo * ["bar"] - * [2] + * [2] */ function nameClause(previousExpr, detection ) { - + var name = detection[NAME_INDEX], - - matchesName = ( !name || name == '*' ) + + matchesName = ( !name || name == '*' ) ? always : function(ascent){return headKey(ascent) == name}; - - + + return lazyIntersection(matchesName, previousExpr); } - + /** * Create an evaluator function for a a duck-typed node, expressed like: - * + * * {spin, taste, colour} * .particle{spin, taste, colour} * *{spin, taste, colour} */ function duckTypeClause(previousExpr, detection) { - + var fieldListStr = detection[FIELD_LIST_INDEX]; - - if (!fieldListStr) - return previousExpr; // don't wrap at all, return given expr as-is - + + if (!fieldListStr) + return previousExpr; // don't wrap at all, return given expr as-is + var hasAllrequiredFields = partialComplete( - hasAllProperties, + hasAllProperties, arrayAsList(fieldListStr.split(/\W+/)) ), - - isMatch = compose2( - hasAllrequiredFields, + + isMatch = compose2( + hasAllrequiredFields, headNode ); - + return lazyIntersection(isMatch, previousExpr); } - + /** * Expression for $, returns the evaluator function */ function capture( previousExpr, detection ) { - - // extract meaning from the detection + + // extract meaning from the detection var capturing = !!detection[CAPTURING_INDEX]; - - if (!capturing) - return previousExpr; // don't wrap at all, return given expr as-is - + + if (!capturing) + return previousExpr; // don't wrap at all, return given expr as-is + return lazyIntersection(previousExpr, head); - - } - + + } + /** - * Create an evaluator function that moves onto the next item on the - * lists. This function is the place where the logic to move up a - * level in the ascent exists. - * + * Create an evaluator function that moves onto the next item on the + * lists. This function is the place where the logic to move up a + * level in the ascent exists. + * * Eg, for JSONPath ".foo" we need skip1(nameClause(always, [,'foo'])) */ function skip1(previousExpr) { - - + + if( previousExpr == always ) { - /* If there is no previous expression this consume command + /* If there is no previous expression this consume command is at the start of the jsonPath. - Since JSONPath specifies what we'd like to find but not + Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running out of JSONPath to check against we default to true */ return always; } - + /** return true if the ascent we have contains only the JSON root, * false otherwise */ function notAtRoot(ascent){ return headKey(ascent) != ROOT_PATH; } - + return lazyIntersection( - /* If we're already at the root but there are more + /* If we're already at the root but there are more expressions to satisfy, can't consume any more. No match. - - This check is why none of the other exprs have to be able - to handle empty lists; skip1 is the only evaluator that - moves onto the next token and it refuses to do so once it + + This check is why none of the other exprs have to be able + to handle empty lists; skip1 is the only evaluator that + moves onto the next token and it refuses to do so once it reaches the last item in the list. */ notAtRoot, - + /* We are not at the root of the ascent yet. - Move to the next level of the ascent by handing only - the tail to the previous expression */ - compose2(previousExpr, tail) + Move to the next level of the ascent by handing only + the tail to the previous expression */ + compose2(previousExpr, tail) ); - - } - + + } + /** * Create an evaluator function for the .. (double dot) token. Consumes * zero or more levels of the ascent, the fewest that are required to find * a match when given to previousExpr. - */ + */ function skipMany(previousExpr) { - + if( previousExpr == always ) { - /* If there is no previous expression this consume command + /* If there is no previous expression this consume command is at the start of the jsonPath. - Since JSONPath specifies what we'd like to find but not + Since JSONPath specifies what we'd like to find but not necessarily everything leading down to it, when running - out of JSONPath to check against we default to true */ + out of JSONPath to check against we default to true */ return always; } - - var + + var // In JSONPath .. is equivalent to !.. so if .. reaches the root // the match has succeeded. Ie, we might write ..foo or !..foo // and both should match identically. @@ -41021,303 +41021,303 @@ recursiveCase = skip1(function(ascent) { return cases(ascent); }), - + cases = lazyUnion( terminalCaseWhenArrivingAtRoot , terminalCaseWhenPreviousExpressionIsSatisfied - , recursiveCase + , recursiveCase ); - + return cases; - } - + } + /** * Generate an evaluator for ! - matches only the root element of the json - * and ignores any previous expressions since nothing may precede !. - */ + * and ignores any previous expressions since nothing may precede !. + */ function rootExpr() { - + return function(ascent){ return headKey(ascent) == ROOT_PATH; }; - } - + } + /** - * Generate a statement wrapper to sit around the outermost + * Generate a statement wrapper to sit around the outermost * clause evaluator. - * + * * Handles the case where the capturing is implicit because the JSONPath * did not contain a '$' by returning the last node. - */ + */ function statementExpr(lastClause) { - + return function(ascent) { - + // kick off the evaluation by passing through to the last clause var exprMatch = lastClause(ascent); - + return exprMatch === true ? head(ascent) : exprMatch; }; - } - + } + /** * For when a token has been found in the JSONPath input. * Compiles the parser for that token and returns in combination with the * parser already generated. - * + * * @param {Function} exprs a list of the clause evaluator generators for * the token that was found * @param {Function} parserGeneratedSoFar the parser already found - * @param {Array} detection the match given by the regex engine when + * @param {Array} detection the match given by the regex engine when * the feature was found */ function expressionsReader( exprs, parserGeneratedSoFar, detection ) { - - // if exprs is zero-length foldR will pass back the - // parserGeneratedSoFar as-is so we don't need to treat + + // if exprs is zero-length foldR will pass back the + // parserGeneratedSoFar as-is so we don't need to treat // this as a special case - - return foldR( + + return foldR( function( parserGeneratedSoFar, expr ){ - + return expr(parserGeneratedSoFar, detection); - }, - parserGeneratedSoFar, + }, + parserGeneratedSoFar, exprs - ); - + ); + } - - /** + + /** * If jsonPath matches the given detector function, creates a function which * evaluates against every clause in the clauseEvaluatorGenerators. The * created function is propagated to the onSuccess function, along with * the remaining unparsed JSONPath substring. - * + * * The intended use is to create a clauseMatcher by filling in * the first two arguments, thus providing a function that knows * some syntax to match and what kind of generator to create if it * finds it. The parameter list once completed is: - * + * * (jsonPath, parserGeneratedSoFar, onSuccess) - * - * onSuccess may be compileJsonPathToFunction, to recursively continue + * + * onSuccess may be compileJsonPathToFunction, to recursively continue * parsing after finding a match or returnFoundParser to stop here. */ function generateClauseReaderIfTokenFound ( - + tokenDetector, clauseEvaluatorGenerators, - + jsonPath, parserGeneratedSoFar, onSuccess) { - + var detected = tokenDetector(jsonPath); - + if(detected) { var compiledParser = expressionsReader( - clauseEvaluatorGenerators, - parserGeneratedSoFar, + clauseEvaluatorGenerators, + parserGeneratedSoFar, detected ), - - remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); - + + remainingUnparsedJsonPath = jsonPath.substr(len(detected[0])); + return onSuccess(remainingUnparsedJsonPath, compiledParser); - } + } } - + /** - * Partially completes generateClauseReaderIfTokenFound above. + * Partially completes generateClauseReaderIfTokenFound above. */ function clauseMatcher(tokenDetector, exprs) { - - return partialComplete( - generateClauseReaderIfTokenFound, - tokenDetector, - exprs + + return partialComplete( + generateClauseReaderIfTokenFound, + tokenDetector, + exprs ); } - + /** - * clauseForJsonPath is a function which attempts to match against + * clauseForJsonPath is a function which attempts to match against * several clause matchers in order until one matches. If non match the * jsonPath expression is invalid and an error is thrown. - * + * * The parameter list is the same as a single clauseMatcher: - * + * * (jsonPath, parserGeneratedSoFar, onSuccess) - */ + */ var clauseForJsonPath = lazyUnion( - - clauseMatcher(pathNodeSyntax , list( capture, - duckTypeClause, - nameClause, + + clauseMatcher(pathNodeSyntax , list( capture, + duckTypeClause, + nameClause, skip1 )) - + , clauseMatcher(doubleDotSyntax , list( skipMany)) - - // dot is a separator only (like whitespace in other languages) but - // rather than make it a special case, use an empty list of + + // dot is a separator only (like whitespace in other languages) but + // rather than make it a special case, use an empty list of // expressions when this token is found - , clauseMatcher(dotSyntax , list() ) - + , clauseMatcher(dotSyntax , list() ) + , clauseMatcher(bangSyntax , list( capture, rootExpr)) - + , clauseMatcher(emptySyntax , list( statementExpr)) - + , function (jsonPath) { - throw Error('"' + jsonPath + '" could not be tokenised') + throw Error('"' + jsonPath + '" could not be tokenised') } ); - - + + /** - * One of two possible values for the onSuccess argument of + * One of two possible values for the onSuccess argument of * generateClauseReaderIfTokenFound. - * - * When this function is used, generateClauseReaderIfTokenFound simply - * returns the compiledParser that it made, regardless of if there is + * + * When this function is used, generateClauseReaderIfTokenFound simply + * returns the compiledParser that it made, regardless of if there is * any remaining jsonPath to be compiled. */ - function returnFoundParser(_remainingJsonPath, compiledParser){ - return compiledParser - } - + function returnFoundParser(_remainingJsonPath, compiledParser){ + return compiledParser + } + /** * Recursively compile a JSONPath expression. - * - * This function serves as one of two possible values for the onSuccess + * + * This function serves as one of two possible values for the onSuccess * argument of generateClauseReaderIfTokenFound, meaning continue to * recursively compile. Otherwise, returnFoundParser is given and * compilation terminates. */ - function compileJsonPathToFunction( uncompiledJsonPath, + function compileJsonPathToFunction( uncompiledJsonPath, parserGeneratedSoFar ) { - + /** * On finding a match, if there is remaining text to be compiled - * we want to either continue parsing using a recursive call to - * compileJsonPathToFunction. Otherwise, we want to stop and return + * we want to either continue parsing using a recursive call to + * compileJsonPathToFunction. Otherwise, we want to stop and return * the parser that we have found so far. */ var onFind = uncompiledJsonPath - ? compileJsonPathToFunction + ? compileJsonPathToFunction : returnFoundParser; - - return clauseForJsonPath( - uncompiledJsonPath, - parserGeneratedSoFar, + + return clauseForJsonPath( + uncompiledJsonPath, + parserGeneratedSoFar, onFind - ); + ); } - + /** * This is the function that we expose to the rest of the library. */ return function(jsonPath){ - + try { - // Kick off the recursive parsing of the jsonPath + // Kick off the recursive parsing of the jsonPath return compileJsonPathToFunction(jsonPath, always); - + } catch( e ) { - throw Error( 'Could not compile "' + jsonPath + + throw Error( 'Could not compile "' + jsonPath + '" because ' + e.message ); } } - + }); - - /** - * A pub/sub which is responsible for a single event type. A + + /** + * A pub/sub which is responsible for a single event type. A * multi-event type event bus is created by pubSub by collecting * several of these. - * - * @param {String} eventType + * + * @param {String} eventType * the name of the events managed by this singleEventPubSub - * @param {singleEventPubSub} [newListener] + * @param {singleEventPubSub} [newListener] * place to notify of new listeners - * @param {singleEventPubSub} [removeListener] + * @param {singleEventPubSub} [removeListener] * place to notify of when listeners are removed */ function singleEventPubSub(eventType, newListener, removeListener){ - + /** we are optimised for emitting events over firing them. * As well as the tuple list which stores event ids and - * listeners there is a list with just the listeners which + * listeners there is a list with just the listeners which * can be iterated more quickly when we are emitting */ var listenerTupleList, listenerList; - + function hasId(id){ return function(tuple) { - return tuple.id == id; - }; + return tuple.id == id; + }; } - + return { - + /** * @param {Function} listener - * @param {*} listenerId - * an id that this listener can later by removed by. + * @param {*} listenerId + * an id that this listener can later by removed by. * Can be of any type, to be compared to other ids using == */ on:function( listener, listenerId ) { - + var tuple = { listener: listener , id: listenerId || listener // when no id is given use the // listener function as the id }; - + if( newListener ) { newListener.emit(eventType, listener, tuple.id); } - + listenerTupleList = cons( tuple, listenerTupleList ); listenerList = cons( listener, listenerList ); - + return this; // chaining }, - - emit:function () { + + emit:function () { applyEach( listenerList, arguments ); }, - + un: function( listenerId ) { - - var removed; - + + var removed; + listenerTupleList = without( listenerTupleList, hasId(listenerId), function(tuple){ removed = tuple; } - ); - + ); + if( removed ) { listenerList = without( listenerList, function(listener){ return listener == removed.listener; }); - + if( removeListener ) { removeListener.emit(eventType, removed.listener, removed.id); } } }, - + listeners: function(){ // differs from Node EventEmitter: returns list, not array return listenerList; }, - + hasListener: function(listenerId){ var test = listenerId? hasId(listenerId) : always; - + return defined(first( test, listenerTupleList)); } }; @@ -41325,227 +41325,227 @@ /** * pubSub is a curried interface for listening to and emitting * events. - * + * * If we get a bus: - * + * * var bus = pubSub(); - * + * * We can listen to event 'foo' like: - * + * * bus('foo').on(myCallback) - * + * * And emit event foo like: - * + * * bus('foo').emit() - * + * * or, with a parameter: - * + * * bus('foo').emit('bar') - * - * All functions can be cached and don't need to be + * + * All functions can be cached and don't need to be * bound. Ie: - * + * * var fooEmitter = bus('foo').emit * fooEmitter('bar'); // emit an event * fooEmitter('baz'); // emit another - * + * * There's also an uncurried[1] shortcut for .emit and .on: - * + * * bus.on('foo', callback) * bus.emit('foo', 'bar') - * + * * [1]: http://zvon.org/other/haskell/Outputprelude/uncurry_f.html */ function pubSub(){ - + var singles = {}, newListener = newSingle('newListener'), - removeListener = newSingle('removeListener'); - + removeListener = newSingle('removeListener'); + function newSingle(eventName) { return singles[eventName] = singleEventPubSub( - eventName, - newListener, + eventName, + newListener, removeListener - ); - } - + ); + } + /** pubSub instances are functions */ - function pubSubInstance( eventName ){ - - return singles[eventName] || newSingle( eventName ); + function pubSubInstance( eventName ){ + + return singles[eventName] || newSingle( eventName ); } - + // add convenience EventEmitter-style uncurried form of 'emit' and 'on' ['emit', 'on', 'un'].forEach(function(methodName){ - + pubSubInstance[methodName] = varArgs(function(eventName, parameters){ apply( parameters, pubSubInstance( eventName )[methodName]); - }); + }); }); - + return pubSubInstance; } - + /** * This file declares some constants to use as names for event types. */ - - var // the events which are never exported are kept as + + var // the events which are never exported are kept as // the smallest possible representation, in numbers: _S = 1, - + // fired whenever a new node starts in the JSON stream: NODE_OPENED = _S++, - + // fired whenever a node closes in the JSON stream: NODE_CLOSED = _S++, - - // called if a .node callback returns a value - + + // called if a .node callback returns a value - NODE_SWAP = _S++, NODE_DROP = _S++, - + FAIL_EVENT = 'fail', - + ROOT_NODE_FOUND = _S++, ROOT_PATH_FOUND = _S++, - + HTTP_START = 'start', STREAM_DATA = 'data', STREAM_END = 'end', ABORTING = _S++, - + // SAX events butchered from Clarinet SAX_KEY = _S++, SAX_VALUE_OPEN = _S++, SAX_VALUE_CLOSE = _S++; - + function errorReport(statusCode, body, error) { try{ var jsonBody = JSON.parse(body); }catch(e){} - + return { statusCode:statusCode, body:body, jsonBody:jsonBody, thrown:error }; - } - - /** + } + + /** * The pattern adaptor listens for newListener and removeListener * events. When patterns are added or removed it compiles the JSONPath * and wires them up. - * - * When nodes and paths are found it emits the fully-qualified match + * + * When nodes and paths are found it emits the fully-qualified match * events with parameters ready to ship to the outside world */ - + function patternAdapter(oboeBus, jsonPathCompiler) { - + var predicateEventMap = { node:oboeBus(NODE_CLOSED) , path:oboeBus(NODE_OPENED) }; - + function emitMatchingNode(emitMatch, node, ascent) { - - /* - We're now calling to the outside world where Lisp-style - lists will not be familiar. Convert to standard arrays. - - Also, reverse the order because it is more common to + + /* + We're now calling to the outside world where Lisp-style + lists will not be familiar. Convert to standard arrays. + + Also, reverse the order because it is more common to list paths "root to leaf" than "leaf to root" */ var descent = reverseList(ascent); - + emitMatch( node, - + // To make a path, strip off the last item which is the special - // ROOT_PATH token for the 'path' to the root node + // ROOT_PATH token for the 'path' to the root node listAsArray(tail(map(keyOf,descent))), // path - listAsArray(map(nodeOf, descent)) // ancestors - ); + listAsArray(map(nodeOf, descent)) // ancestors + ); } - - /* - * Set up the catching of events such as NODE_CLOSED and NODE_OPENED and, if - * matching the specified pattern, propagate to pattern-match events such as + + /* + * Set up the catching of events such as NODE_CLOSED and NODE_OPENED and, if + * matching the specified pattern, propagate to pattern-match events such as * oboeBus('node:!') - * - * - * - * @param {Function} predicateEvent + * + * + * + * @param {Function} predicateEvent * either oboeBus(NODE_CLOSED) or oboeBus(NODE_OPENED). - * @param {Function} compiledJsonPath + * @param {Function} compiledJsonPath */ function addUnderlyingListener( fullEventName, predicateEvent, compiledJsonPath ){ - + var emitMatch = oboeBus(fullEventName).emit; - + predicateEvent.on( function (ascent) { - + var maybeMatchingMapping = compiledJsonPath(ascent); - + /* Possible values for maybeMatchingMapping are now: - - false: - we did not match - - an object/array/string/number/null: + + false: + we did not match + + an object/array/string/number/null: we matched and have the node that matched. Because nulls are valid json values this can be null. - + undefined: we matched but don't have the matching node yet. - ie, we know there is an upcoming node that matches but we - can't say anything else about it. + ie, we know there is an upcoming node that matches but we + can't say anything else about it. */ if (maybeMatchingMapping !== false) { - + emitMatchingNode( - emitMatch, - nodeOf(maybeMatchingMapping), + emitMatch, + nodeOf(maybeMatchingMapping), ascent ); } }, fullEventName); - + oboeBus('removeListener').on( function(removedEventName){ - - // if the fully qualified match event listener is later removed, clean up + + // if the fully qualified match event listener is later removed, clean up // by removing the underlying listener if it was the last using that pattern: - + if( removedEventName == fullEventName ) { - + if( !oboeBus(removedEventName).listeners( )) { predicateEvent.un( fullEventName ); } } - }); + }); } - + oboeBus('newListener').on( function(fullEventName){ - + var match = /(node|path):(.*)/.exec(fullEventName); - + if( match ) { var predicateEvent = predicateEventMap[match[1]]; - - if( !predicateEvent.hasListener( fullEventName) ) { - + + if( !predicateEvent.hasListener( fullEventName) ) { + addUnderlyingListener( fullEventName, - predicateEvent, + predicateEvent, jsonPathCompiler( match[2] ) ); } - } + } }) - + } - + /** * The instance API is the thing that is returned when oboe() is called. * it allows: @@ -41554,74 +41554,74 @@ * - the http response header/headers to be read */ function instanceApi(oboeBus, contentSource){ - + var oboeApi, fullyQualifiedNamePattern = /^(node|path):./, rootNodeFinishedEvent = oboeBus(ROOT_NODE_FOUND), emitNodeDrop = oboeBus(NODE_DROP).emit, emitNodeSwap = oboeBus(NODE_SWAP).emit, - + /** * Add any kind of listener that the instance api exposes */ addListener = varArgs(function( eventId, parameters ){ - + if( oboeApi[eventId] ) { - + // for events added as .on(event, callback), if there is a // .event() equivalent with special behaviour , pass through // to that: apply(parameters, oboeApi[eventId]); } else { - + // we have a standard Node.js EventEmitter 2-argument call. // The first parameter is the listener. var event = oboeBus(eventId), listener = parameters[0]; - + if( fullyQualifiedNamePattern.test(eventId) ) { - + // allow fully-qualified node/path listeners // to be added addForgettableCallback(event, listener); } else { - + // the event has no special handling, pass through // directly onto the event bus: event.on( listener); } } - + return oboeApi; // chaining }), - + /** * Remove any kind of listener that the instance api exposes */ removeListener = function( eventId, p2, p3 ){ - + if( eventId == 'done' ) { - + rootNodeFinishedEvent.un(p2); - + } else if( eventId == 'node' || eventId == 'path' ) { - + // allow removal of node and path oboeBus.un(eventId + ':' + p2, p3); } else { - + // we have a standard Node.js EventEmitter 2-argument call. // The second parameter is the listener. This may be a call // to remove a fully-qualified node/path listener but requires // no special handling var listener = p2; - + oboeBus(eventId).un(listener); } - + return oboeApi; // chaining }; - + /** * Add a callback, wrapped in a try/catch so as to not break the * execution of Oboe if an exception is thrown (fail events are @@ -41634,39 +41634,39 @@ oboeBus(eventName).on(protectedCallback(callback), callback); return oboeApi; // chaining } - + /** * Add a callback where, if .forget() is called during the callback's * execution, the callback will be de-registered */ function addForgettableCallback(event, callback, listenerId) { - + // listenerId is optional and if not given, the original // callback will be used listenerId = listenerId || callback; - + var safeCallback = protectedCallback(callback); - + event.on( function() { - + var discard = false; - + oboeApi.forget = function(){ discard = true; }; - + apply( arguments, safeCallback ); - + delete oboeApi.forget; - + if( discard ) { event.un(listenerId); } }, listenerId); - + return oboeApi; // chaining } - + /** * wrap a callback so that if it throws, Oboe.js doesn't crash but instead * throw the error in another event loop @@ -41682,7 +41682,7 @@ } } } - + /** * Return the fully qualified event for when a pattern matches * either a node or a path @@ -41692,13 +41692,13 @@ function fullyQualifiedPatternMatchEvent(type, pattern) { return oboeBus(type + ':' + pattern); } - + function wrapCallbackToSwapNodeIfSomethingReturned( callback ) { return function() { var returnValueFromCallback = callback.apply(this, arguments); - + if( defined(returnValueFromCallback) ) { - + if( returnValueFromCallback == oboe.drop ) { emitNodeDrop(); } else { @@ -41707,69 +41707,69 @@ } } } - + function addSingleNodeOrPathListener(eventId, pattern, callback) { - + var effectiveCallback; - + if( eventId == 'node' ) { effectiveCallback = wrapCallbackToSwapNodeIfSomethingReturned(callback); } else { effectiveCallback = callback; } - + addForgettableCallback( fullyQualifiedPatternMatchEvent(eventId, pattern), effectiveCallback, callback ); } - + /** * Add several listeners at a time, from a map */ function addMultipleNodeOrPathListeners(eventId, listenerMap) { - + for( var pattern in listenerMap ) { addSingleNodeOrPathListener(eventId, pattern, listenerMap[pattern]); } } - + /** * implementation behind .onPath() and .onNode() */ function addNodeOrPathListenerApi( eventId, jsonPathOrListenerMap, callback ){ - + if( isString(jsonPathOrListenerMap) ) { addSingleNodeOrPathListener(eventId, jsonPathOrListenerMap, callback); - + } else { addMultipleNodeOrPathListeners(eventId, jsonPathOrListenerMap); } - + return oboeApi; // chaining } - - + + // some interface methods are only filled in after we receive // values and are noops before that: oboeBus(ROOT_PATH_FOUND).on( function(rootNode) { oboeApi.root = functor(rootNode); }); - + /** * When content starts make the headers readable through the * instance API */ oboeBus(HTTP_START).on( function(_statusCode, headers) { - + oboeApi.header = function(name) { return name ? headers[name] : headers ; } }); - + /** * Construct and return the public API of the Oboe instance to be * returned to the calling application @@ -41779,46 +41779,46 @@ addListener : addListener, removeListener : removeListener, emit : oboeBus.emit, - + node : partialComplete(addNodeOrPathListenerApi, 'node'), path : partialComplete(addNodeOrPathListenerApi, 'path'), - + done : partialComplete(addForgettableCallback, rootNodeFinishedEvent), start : partialComplete(addProtectedCallback, HTTP_START ), - + // fail doesn't use protectedCallback because // could lead to non-terminating loops fail : oboeBus(FAIL_EVENT).on, - + // public api calling abort fires the ABORTING event abort : oboeBus(ABORTING).emit, - + // initially return nothing for header and root header : noop, root : noop, - + source : contentSource }; } - + /** * This file sits just behind the API which is used to attain a new * Oboe instance. It creates the new components that are required * and introduces them to each other. */ - + function wire (httpMethodName, contentSource, body, headers, withCredentials){ - + var oboeBus = pubSub(); - + // Wire the input stream in if we are given a content source. // This will usually be the case. If not, the instance created // will have to be passed content from an external source. - + if( contentSource ) { - + streamingHttp( oboeBus, - httpTransport(), + httpTransport(), httpMethodName, contentSource, body, @@ -41826,76 +41826,76 @@ withCredentials ); } - + clarinet(oboeBus); - + ascentManager(oboeBus, incrementalContentBuilder(oboeBus)); - - patternAdapter(oboeBus, jsonPathCompiler); - + + patternAdapter(oboeBus, jsonPathCompiler); + return instanceApi(oboeBus, contentSource); } - + function applyDefaults( passthrough, url, httpMethodName, body, headers, withCredentials, cached ){ - + headers = headers ? // Shallow-clone the headers array. This allows it to be // modified without side effects to the caller. We don't // want to change objects that the user passes in. JSON.parse(JSON.stringify(headers)) : {}; - + if( body ) { if( !isString(body) ) { - + // If the body is not a string, stringify it. This allows objects to // be given which will be sent as JSON. body = JSON.stringify(body); - + // Default Content-Type to JSON unless given otherwise. headers['Content-Type'] = headers['Content-Type'] || 'application/json'; } } else { body = null; } - + // support cache busting like jQuery.ajax({cache:false}) function modifiedUrl(baseUrl, cached) { - + if( cached === false ) { - + if( baseUrl.indexOf('?') == -1 ) { baseUrl += '?'; } else { baseUrl += '&'; } - + baseUrl += '_=' + new Date().getTime(); } return baseUrl; } - + return passthrough( httpMethodName || 'GET', modifiedUrl(url, cached), body, headers, withCredentials || false ); } - + // export public API function oboe(arg1) { - + // We use duck-typing to detect if the parameter given is a stream, with the // below list of parameters. // Unpipe and unshift would normally be present on a stream but this breaks // compatibility with Request streams. // See https://github.com/jimhigson/oboe.js/issues/65 - + var nodeStreamMethodNames = list('resume', 'pause', 'pipe'), isStream = partialComplete( hasAllProperties , nodeStreamMethodNames ); - + if( arg1 ) { if (isStream(arg1) || isString(arg1)) { - + // simple version for GETs. Signature is: // oboe( url ) // or, under node: @@ -41904,12 +41904,12 @@ wire, arg1 // url ); - + } else { - + // method signature is: // oboe({method:m, url:u, body:b, headers:{...}}) - + return applyDefaults( wire, arg1.url, @@ -41919,23 +41919,23 @@ arg1.withCredentials, arg1.cached ); - + } } else { - // wire up a no-AJAX, no-stream Oboe. Will have to have content + // wire up a no-AJAX, no-stream Oboe. Will have to have content // fed in externally and using .emit. return wire(); } } - + /* oboe.drop is a special value. If a node callback returns this value the parsed node is deleted from the JSON */ oboe.drop = function() { return oboe.drop; }; - - + + if ( typeof define === "function" && define.amd ) { define( "oboe", [], function () { return oboe; } ); } else if (typeof exports === 'object') { @@ -41952,58 +41952,58 @@ return self; } }()), Object, Array, Error, JSON); - + },{}],240:[function(require,module,exports){ exports.endianness = function () { return 'LE' }; - + exports.hostname = function () { if (typeof location !== 'undefined') { return location.hostname } else return ''; }; - + exports.loadavg = function () { return [] }; - + exports.uptime = function () { return 0 }; - + exports.freemem = function () { return Number.MAX_VALUE; }; - + exports.totalmem = function () { return Number.MAX_VALUE; }; - + exports.cpus = function () { return [] }; - + exports.type = function () { return 'Browser' }; - + exports.release = function () { if (typeof navigator !== 'undefined') { return navigator.appVersion; } return ''; }; - + exports.networkInterfaces = exports.getNetworkInterfaces = function () { return {} }; - + exports.arch = function () { return 'javascript' }; - + exports.platform = function () { return 'browser' }; - + exports.tmpdir = exports.tmpDir = function () { return '/tmp'; }; - + exports.EOL = '\n'; - + exports.homedir = function () { return '/' }; - + },{}],241:[function(require,module,exports){ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", @@ -42022,11 +42022,11 @@ // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js // Fedor, you are amazing. 'use strict' - + var asn1 = require('asn1.js') - + exports.certificate = require('./certificate') - + var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { this.seq().obj( this.key('version').int(), @@ -42041,7 +42041,7 @@ ) }) exports.RSAPrivateKey = RSAPrivateKey - + var RSAPublicKey = asn1.define('RSAPublicKey', function () { this.seq().obj( this.key('modulus').int(), @@ -42049,7 +42049,7 @@ ) }) exports.RSAPublicKey = RSAPublicKey - + var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), @@ -42057,7 +42057,7 @@ ) }) exports.PublicKey = PublicKey - + var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), @@ -42070,7 +42070,7 @@ ).optional() ) }) - + var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { this.seq().obj( this.key('version').int(), @@ -42100,9 +42100,9 @@ this.key('subjectPrivateKey').octstr() ) }) - + exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo - + var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { this.seq().obj( this.key('version').int(), @@ -42114,11 +42114,11 @@ ) }) exports.DSAPrivateKey = DSAPrivateKey - + exports.DSAparam = asn1.define('DSAparam', function () { this.int() }) - + var ECPrivateKey = asn1.define('ECPrivateKey', function () { this.seq().obj( this.key('version').int(), @@ -42128,77 +42128,77 @@ ) }) exports.ECPrivateKey = ECPrivateKey - + var ECParameters = asn1.define('ECParameters', function () { this.choice({ namedCurve: this.objid() }) }) - + exports.signature = asn1.define('signature', function () { this.seq().obj( this.key('r').int(), this.key('s').int() ) }) - + },{"./certificate":243,"asn1.js":5}],243:[function(require,module,exports){ // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen - + 'use strict' - + var asn = require('asn1.js') - + var Time = asn.define('Time', function () { this.choice({ utcTime: this.utctime(), generalTime: this.gentime() }) }) - + var AttributeTypeValue = asn.define('AttributeTypeValue', function () { this.seq().obj( this.key('type').objid(), this.key('value').any() ) }) - + var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), this.key('parameters').optional() ) }) - + var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr() ) }) - + var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { this.setof(AttributeTypeValue) }) - + var RDNSequence = asn.define('RDNSequence', function () { this.seqof(RelativeDistinguishedName) }) - + var Name = asn.define('Name', function () { this.choice({ rdnSequence: this.use(RDNSequence) }) }) - + var Validity = asn.define('Validity', function () { this.seq().obj( this.key('notBefore').use(Time), this.key('notAfter').use(Time) ) }) - + var Extension = asn.define('Extension', function () { this.seq().obj( this.key('extnID').objid(), @@ -42206,7 +42206,7 @@ this.key('extnValue').octstr() ) }) - + var TBSCertificate = asn.define('TBSCertificate', function () { this.seq().obj( this.key('version').explicit(0).int(), @@ -42221,7 +42221,7 @@ this.key('extensions').explicit(3).seqof(Extension).optional() ) }) - + var X509Certificate = asn.define('X509Certificate', function () { this.seq().obj( this.key('tbsCertificate').use(TBSCertificate), @@ -42229,9 +42229,9 @@ this.key('signatureValue').bitstr() ) }) - + module.exports = X509Certificate - + },{"asn1.js":5}],244:[function(require,module,exports){ (function (Buffer){ // adapted from https://github.com/apatil/pemstrip @@ -42264,7 +42264,7 @@ data: decrypted } } - + }).call(this,require("buffer").Buffer) },{"browserify-aes":58,"buffer":84,"evp_bytestokey":158}],245:[function(require,module,exports){ (function (Buffer){ @@ -42274,7 +42274,7 @@ var ciphers = require('browserify-aes') var compat = require('pbkdf2') module.exports = parseKeys - + function parseKeys (buffer) { var password if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { @@ -42284,9 +42284,9 @@ if (typeof buffer === 'string') { buffer = new Buffer(buffer) } - + var stripped = fixProc(buffer, password) - + var type = stripped.tag var data = stripped.data var subtype, ndata @@ -42374,7 +42374,7 @@ out.push(cipher.final()) return Buffer.concat(out) } - + }).call(this,require("buffer").Buffer) },{"./aesid.json":241,"./asn1":242,"./fixProc":244,"browserify-aes":58,"buffer":84,"pbkdf2":247}],246:[function(require,module,exports){ var trim = require('trim') @@ -42382,20 +42382,20 @@ , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } - + module.exports = function (headers) { if (!headers) return {} - + var result = {} - + forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) - + if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { @@ -42405,22 +42405,22 @@ } } ) - + return result } },{"for-each":159,"trim":324}],247:[function(require,module,exports){ - + exports.pbkdf2 = require('./lib/async') - + exports.pbkdf2Sync = require('./lib/sync') - + },{"./lib/async":248,"./lib/sync":251}],248:[function(require,module,exports){ (function (process,global){ var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var sync = require('./sync') var Buffer = require('safe-buffer').Buffer - + var ZERO_BUF var subtle = global.crypto && global.crypto.subtle var toBrowser = { @@ -42485,14 +42485,14 @@ module.exports = function (password, salt, iterations, keylen, digest, callback) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) - + checkParameters(iterations, keylen) if (typeof digest === 'function') { callback = digest digest = undefined } if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') - + digest = digest || 'sha1' var algo = toBrowser[digest.toLowerCase()] if (!algo || typeof global.Promise !== 'function') { @@ -42514,7 +42514,7 @@ } }), callback) } - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./default-encoding":249,"./precondition":250,"./sync":251,"_process":257,"safe-buffer":290}],249:[function(require,module,exports){ (function (process){ @@ -42524,11 +42524,11 @@ defaultEncoding = 'utf-8' } else { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) - + defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' } module.exports = defaultEncoding - + }).call(this,require('_process')) },{"_process":257}],250:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs @@ -42536,25 +42536,25 @@ if (typeof iterations !== 'number') { throw new TypeError('Iterations not a number') } - + if (iterations < 0) { throw new TypeError('Bad iterations') } - + if (typeof keylen !== 'number') { throw new TypeError('Key length not a number') } - + if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ throw new TypeError('Bad key length') } } - + },{}],251:[function(require,module,exports){ var md5 = require('create-hash/md5') var rmd160 = require('ripemd160') var sha = require('sha.js') - + var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var Buffer = require('safe-buffer').Buffer @@ -42569,24 +42569,24 @@ rmd160: 20, ripemd160: 20 } - + function Hmac (alg, key, saltLen) { var hash = getDigest(alg) var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - + if (key.length > blocksize) { key = hash(key) } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } - + var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } - + var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) ipad.copy(ipad1, 0, 0, blocksize) this.ipad1 = ipad1 @@ -42597,149 +42597,149 @@ this.hash = hash this.size = sizes[alg] } - + Hmac.prototype.run = function (data, ipad) { data.copy(ipad, this.blocksize) var h = this.hash(ipad) h.copy(this.opad, this.blocksize) return this.hash(this.opad) } - + function getDigest (alg) { function shaFunc (data) { return sha(alg).update(data).digest() } - + if (alg === 'rmd160' || alg === 'ripemd160') return rmd160 if (alg === 'md5') return md5 return shaFunc } - + function pbkdf2 (password, salt, iterations, keylen, digest) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) - + checkParameters(iterations, keylen) - + digest = digest || 'sha1' - + var hmac = new Hmac(digest, password, salt.length) - + var DK = Buffer.allocUnsafe(keylen) var block1 = Buffer.allocUnsafe(salt.length + 4) salt.copy(block1, 0, 0, salt.length) - + var destPos = 0 var hLen = sizes[digest] var l = Math.ceil(keylen / hLen) - + for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length) - + var T = hmac.run(block1, hmac.ipad1) var U = T - + for (var j = 1; j < iterations; j++) { U = hmac.run(U, hmac.ipad2) for (var k = 0; k < hLen; k++) T[k] ^= U[k] } - + T.copy(DK, destPos) destPos += hLen } - + return DK } - + module.exports = pbkdf2 - + },{"./default-encoding":249,"./precondition":250,"create-hash/md5":93,"ripemd160":288,"safe-buffer":290,"sha.js":304}],252:[function(require,module,exports){ 'use strict'; - + var processFn = function (fn, P, opts) { return function () { var that = this; var args = new Array(arguments.length); - + for (var i = 0; i < arguments.length; i++) { args[i] = arguments[i]; } - + return new P(function (resolve, reject) { args.push(function (err, result) { if (err) { reject(err); } else if (opts.multiArgs) { var results = new Array(arguments.length - 1); - + for (var i = 1; i < arguments.length; i++) { results[i - 1] = arguments[i]; } - + resolve(results); } else { resolve(result); } }); - + fn.apply(that, args); }); }; }; - + var pify = module.exports = function (obj, P, opts) { if (typeof P !== 'function') { opts = P; P = Promise; } - + opts = opts || {}; opts.exclude = opts.exclude || [/.+Sync$/]; - + var filter = function (key) { var match = function (pattern) { return typeof pattern === 'string' ? key === pattern : pattern.test(key); }; - + return opts.include ? opts.include.some(match) : !opts.exclude.some(match); }; - + var ret = typeof obj === 'function' ? function () { if (opts.excludeMain) { return obj.apply(this, arguments); } - + return processFn(obj, P, opts).apply(this, arguments); } : {}; - + return Object.keys(obj).reduce(function (ret, key) { var x = obj[key]; - + ret[key] = typeof x === 'function' && filter(key) ? processFn(x, P, opts) : x; - + return ret; }, ret); }; - + pify.all = pify; - + },{}],253:[function(require,module,exports){ /* * Copyright (c) 2012 Mathieu Turcotte * Licensed under the MIT license. */ - + module.exports = require('./lib/checks'); },{"./lib/checks":254}],254:[function(require,module,exports){ /* * Copyright (c) 2012 Mathieu Turcotte * Licensed under the MIT license. */ - + var util = require('util'); - + var errors = module.exports = require('./errors'); - + function failCheck(ExceptionConstructor, callee, messageFormat, formatArgs) { messageFormat = messageFormat || ''; var message = util.format.apply(this, [messageFormat].concat(formatArgs)); @@ -42747,50 +42747,50 @@ Error.captureStackTrace(error, callee); throw error; } - + function failArgumentCheck(callee, message, formatArgs) { failCheck(errors.IllegalArgumentError, callee, message, formatArgs); } - + function failStateCheck(callee, message, formatArgs) { failCheck(errors.IllegalStateError, callee, message, formatArgs); } - + module.exports.checkArgument = function(value, message) { if (!value) { failArgumentCheck(arguments.callee, message, Array.prototype.slice.call(arguments, 2)); } }; - + module.exports.checkState = function(value, message) { if (!value) { failStateCheck(arguments.callee, message, Array.prototype.slice.call(arguments, 2)); } }; - + module.exports.checkIsDef = function(value, message) { if (value !== undefined) { return value; } - + failArgumentCheck(arguments.callee, message || 'Expected value to be defined but was undefined.', Array.prototype.slice.call(arguments, 2)); }; - + module.exports.checkIsDefAndNotNull = function(value, message) { // Note that undefined == null. if (value != null) { return value; } - + failArgumentCheck(arguments.callee, message || 'Expected value to be defined and not null but got "' + typeOf(value) + '".', Array.prototype.slice.call(arguments, 2)); }; - + // Fixed version of the typeOf operator which returns 'null' for null values // and 'array' for arrays. function typeOf(value) { @@ -42804,58 +42804,58 @@ } return s; } - + function typeCheck(expect) { return function(value, message) { var type = typeOf(value); - + if (type == expect) { return value; } - + failArgumentCheck(arguments.callee, message || 'Expected "' + expect + '" but got "' + type + '".', Array.prototype.slice.call(arguments, 2)); }; } - + module.exports.checkIsString = typeCheck('string'); module.exports.checkIsArray = typeCheck('array'); module.exports.checkIsNumber = typeCheck('number'); module.exports.checkIsBoolean = typeCheck('boolean'); module.exports.checkIsFunction = typeCheck('function'); module.exports.checkIsObject = typeCheck('object'); - + },{"./errors":255,"util":333}],255:[function(require,module,exports){ /* * Copyright (c) 2012 Mathieu Turcotte * Licensed under the MIT license. */ - + var util = require('util'); - + function IllegalArgumentError(message) { Error.call(this, message); this.message = message; } util.inherits(IllegalArgumentError, Error); - + IllegalArgumentError.prototype.name = 'IllegalArgumentError'; - + function IllegalStateError(message) { Error.call(this, message); this.message = message; } util.inherits(IllegalStateError, Error); - + IllegalStateError.prototype.name = 'IllegalStateError'; - + module.exports.IllegalStateError = IllegalStateError; module.exports.IllegalArgumentError = IllegalArgumentError; },{"util":333}],256:[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) { @@ -42863,7 +42863,7 @@ } else { module.exports = process } - + function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); @@ -42897,21 +42897,21 @@ }); } } - - + + }).call(this,require('_process')) },{"_process":257}],257:[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'); } @@ -42960,8 +42960,8 @@ return cachedSetTimeout.call(this, fun, 0); } } - - + + } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { @@ -42986,15 +42986,15 @@ return cachedClearTimeout.call(this, marker); } } - - - + + + } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; - + function cleanUpNextTick() { if (!draining || !currentQueue) { return; @@ -43009,14 +43009,14 @@ drainQueue(); } } - + function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; - + var len = queue.length; while(len) { currentQueue = queue; @@ -43033,7 +43033,7 @@ draining = false; runClearTimeout(timeout); } - + process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { @@ -43046,7 +43046,7 @@ runTimeout(drainQueue); } }; - + // v8 likes predictible objects function Item(fun, array) { this.fun = fun; @@ -43061,9 +43061,9 @@ process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; - + function noop() {} - + process.on = noop; process.addListener = noop; process.once = noop; @@ -43073,29 +43073,29 @@ 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; }; - + },{}],258:[function(require,module,exports){ 'use strict'; var isFn = require('is-fn'); var setImmediate = require('set-immediate-shim'); - + module.exports = function (promise) { if (!isFn(promise.then)) { throw new TypeError('Expected a promise'); } - + return function (cb) { promise.then(function (data) { setImmediate(cb, null, data); @@ -43104,15 +43104,15 @@ }); }; }; - + },{"is-fn":183,"set-immediate-shim":302}],259:[function(require,module,exports){ exports.publicEncrypt = require('./publicEncrypt'); exports.privateDecrypt = require('./privateDecrypt'); - + exports.privateEncrypt = function privateEncrypt(key, buf) { return exports.publicEncrypt(key, buf, true); }; - + exports.publicDecrypt = function publicDecrypt(key, buf) { return exports.privateDecrypt(key, buf, true); }; @@ -43128,7 +43128,7 @@ } return t.slice(0, len); }; - + function i2ops(c) { var out = new Buffer(4); out.writeUInt32BE(c,0); @@ -43153,7 +43153,7 @@ } else { padding = 4; } - + var key = parseKeys(private_key); var k = key.modulus.byteLength(); if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { @@ -43178,7 +43178,7 @@ throw new Error('unknown padding'); } }; - + function oaep(key, msg){ var n = key.modulus; var k = key.modulus.byteLength(); @@ -43205,7 +43205,7 @@ } return db.slice(i); } - + function pkcs1(key, msg, reverse){ var p1 = msg.slice(0, 2); var i = 2; @@ -43218,7 +43218,7 @@ } var ps = msg.slice(2, i - 1); var p2 = msg.slice(i - 1, i); - + if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){ status++; } @@ -43256,13 +43256,13 @@ var bn = require('bn.js'); var withPublic = require('./withPublic'); var crt = require('browserify-rsa'); - + var constants = { RSA_PKCS1_OAEP_PADDING: 4, RSA_PKCS1_PADDIN: 1, RSA_NO_PADDING: 3 }; - + module.exports = function publicEncrypt(public_key, msg, reverse) { var padding; if (public_key.padding) { @@ -43292,7 +43292,7 @@ return withPublic(paddedMsg, key); } }; - + function oaep(key, msg){ var k = key.modulus.byteLength(); var mLen = msg.length; @@ -43354,7 +43354,7 @@ .fromRed() .toArray()); } - + module.exports = withPublic; }).call(this,require("buffer").Buffer) },{"bn.js":53,"buffer":84}],264:[function(require,module,exports){ @@ -43370,7 +43370,7 @@ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { - + /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; @@ -43384,17 +43384,17 @@ ) { root = freeGlobal; } - + /** * The `punycode` object. * @name punycode * @type Object */ var punycode, - + /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 - + /** Bootstring parameters */ base = 36, tMin = 1, @@ -43404,29 +43404,29 @@ initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' - + /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators - + /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, - + /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, - + /** Temporary variable */ key; - + /*--------------------------------------------------------------------------*/ - + /** * A generic error utility function. * @private @@ -43436,7 +43436,7 @@ function error(type) { throw new RangeError(errors[type]); } - + /** * A generic `Array#map` utility function. * @private @@ -43453,7 +43453,7 @@ } return result; } - + /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. @@ -43479,7 +43479,7 @@ var encoded = map(labels, fn).join('.'); return result + encoded; } - + /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, @@ -43518,7 +43518,7 @@ } return output; } - + /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` @@ -43539,7 +43539,7 @@ return output; }).join(''); } - + /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` @@ -43561,7 +43561,7 @@ } return base; } - + /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` @@ -43578,7 +43578,7 @@ // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } - + /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 @@ -43593,7 +43593,7 @@ } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } - + /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. @@ -43619,16 +43619,16 @@ t, /** Cached calculation results */ baseMinusT; - + // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. - + basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } - + for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { @@ -43636,65 +43636,65 @@ } output.push(input.charCodeAt(j)); } - + // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. - + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { - + // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { - + if (index >= inputLength) { error('invalid-input'); } - + digit = basicToDigit(input.charCodeAt(index++)); - + if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } - + i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); - + if (digit < t) { break; } - + baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } - + w *= baseMinusT; - + } - + out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); - + // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } - + n += floor(i / out); i %= out; - + // Insert `n` at position `i` of the output output.splice(i++, 0, n); - + } - + return ucs2encode(output); } - + /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. @@ -43721,18 +43721,18 @@ handledCPCountPlusOne, baseMinusT, qMinusT; - + // Convert the input in UCS-2 to Unicode input = ucs2decode(input); - + // Cache the length inputLength = input.length; - + // Initialize the state n = initialN; delta = 0; bias = initialBias; - + // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; @@ -43740,20 +43740,20 @@ output.push(stringFromCharCode(currentValue)); } } - + handledCPCount = basicLength = output.length; - + // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. - + // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } - + // Main encoding loop: while (handledCPCount < inputLength) { - + // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { @@ -43762,24 +43762,24 @@ m = currentValue; } } - + // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } - + delta += (m - n) * handledCPCountPlusOne; n = m; - + for (j = 0; j < inputLength; ++j) { currentValue = input[j]; - + if (currentValue < n && ++delta > maxInt) { error('overflow'); } - + if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { @@ -43794,21 +43794,21 @@ ); q = floor(qMinusT / baseMinusT); } - + output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } - + ++delta; ++n; - + } return output.join(''); } - + /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. @@ -43827,7 +43827,7 @@ : string; }); } - + /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, @@ -43846,9 +43846,9 @@ : string; }); } - + /*--------------------------------------------------------------------------*/ - + /** Define the public API */ punycode = { /** @@ -43873,7 +43873,7 @@ 'toASCII': toASCII, 'toUnicode': toUnicode }; - + /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: @@ -43899,16 +43899,16 @@ // in Rhino or a web browser root.punycode = punycode; } - + }(this)); - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],266:[function(require,module,exports){ 'use strict'; var strictUriEncode = require('strict-uri-encode'); var objectAssign = require('object-assign'); var decodeComponent = require('decode-uri-component'); - + function encoderForArrayFormat(opts) { switch (opts.arrayFormat) { case 'index': @@ -43926,7 +43926,7 @@ encode(value, opts) ].join(''); }; - + case 'bracket': return function (key, value) { return value === null ? encode(key, opts) : [ @@ -43935,7 +43935,7 @@ encode(value, opts) ].join(''); }; - + default: return function (key, value) { return value === null ? encode(key, opts) : [ @@ -43946,34 +43946,34 @@ }; } } - + function parserForArrayFormat(opts) { var result; - + switch (opts.arrayFormat) { case 'index': return function (key, value, accumulator) { result = /\[(\d*)\]$/.exec(key); - + key = key.replace(/\[\d*\]$/, ''); - + if (!result) { accumulator[key] = value; return; } - + if (accumulator[key] === undefined) { accumulator[key] = {}; } - + accumulator[key][result[1]] = value; }; - + case 'bracket': return function (key, value, accumulator) { result = /(\[\])$/.exec(key); key = key.replace(/\[\]$/, ''); - + if (!result) { accumulator[key] = value; return; @@ -43981,30 +43981,30 @@ accumulator[key] = [value]; return; } - + accumulator[key] = [].concat(accumulator[key], value); }; - + default: return function (key, value, accumulator) { if (accumulator[key] === undefined) { accumulator[key] = value; return; } - + accumulator[key] = [].concat(accumulator[key], value); }; } } - + function encode(value, opts) { if (opts.encode) { return opts.strict ? strictUriEncode(value) : encodeURIComponent(value); } - + return value; } - + function keysSorter(input) { if (Array.isArray(input)) { return input.sort(); @@ -44015,10 +44015,10 @@ return input[key]; }); } - + return input; } - + function extract(str) { var queryStart = str.indexOf('?'); if (queryStart === -1) { @@ -44026,40 +44026,40 @@ } return str.slice(queryStart + 1); } - + function parse(str, opts) { opts = objectAssign({arrayFormat: 'none'}, opts); - + var formatter = parserForArrayFormat(opts); - + // Create an object with no prototype // https://github.com/sindresorhus/query-string/issues/47 var ret = Object.create(null); - + if (typeof str !== 'string') { return ret; } - + str = str.trim().replace(/^[?#&]/, ''); - + if (!str) { return ret; } - + str.split('&').forEach(function (param) { var parts = param.replace(/\+/g, ' ').split('='); // Firefox (pre 40) decodes `%3D` to `=` // https://github.com/sindresorhus/query-string/pull/37 var key = parts.shift(); var val = parts.length > 0 ? parts.join('=') : undefined; - + // missing `=` should be `null`: // http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters val = val === undefined ? null : decodeComponent(val); - + formatter(decodeComponent(key), val, ret); }); - + return Object.keys(ret).sort().reduce(function (result, key) { var val = ret[key]; if (Boolean(val) && typeof val === 'object' && !Array.isArray(val)) { @@ -44068,67 +44068,67 @@ } else { result[key] = val; } - + return result; }, Object.create(null)); } - + exports.extract = extract; exports.parse = parse; - + exports.stringify = function (obj, opts) { var defaults = { encode: true, strict: true, arrayFormat: 'none' }; - + opts = objectAssign(defaults, opts); - + if (opts.sort === false) { opts.sort = function () {}; } - + var formatter = encoderForArrayFormat(opts); - + return obj ? Object.keys(obj).sort(opts.sort).map(function (key) { var val = obj[key]; - + if (val === undefined) { return ''; } - + if (val === null) { return encode(key, opts); } - + if (Array.isArray(val)) { var result = []; - + val.slice().forEach(function (val2) { if (val2 === undefined) { return; } - + result.push(formatter(key, val2, result.length)); }); - + return result.join('&'); } - + return encode(key, opts) + '=' + encode(val, opts); }).filter(function (x) { return x.length > 0; }).join('&') : ''; }; - + exports.parseUrl = function (str, opts) { return { url: str.split('?')[0] || '', query: parse(extract(str), opts) }; }; - + },{"decode-uri-component":98,"object-assign":238,"strict-uri-encode":316}],267:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -44150,44 +44150,44 @@ // 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'; - + // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } - + module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; - + if (typeof qs !== 'string' || qs.length === 0) { return obj; } - + var regexp = /\+/g; qs = qs.split(sep); - + var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } - + var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } - + for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; - + if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); @@ -44195,10 +44195,10 @@ kstr = x; vstr = ''; } - + k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); - + if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { @@ -44207,14 +44207,14 @@ obj[k] = [obj[k], v]; } } - + return obj; }; - + var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; - + },{}],268:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -44236,32 +44236,32 @@ // 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 stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; - + case 'boolean': return v ? 'true' : 'false'; - + case 'number': return isFinite(v) ? v : ''; - + default: return ''; } }; - + module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } - + if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; @@ -44273,18 +44273,18 @@ return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); - + } - + if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; - + var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; - + function map (xs, f) { if (xs.map) return xs.map(f); var res = []; @@ -44293,7 +44293,7 @@ } return res; } - + var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { @@ -44301,59 +44301,59 @@ } return res; }; - + },{}],269:[function(require,module,exports){ 'use strict'; - + exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); - + },{"./decode":267,"./encode":268}],270:[function(require,module,exports){ (function (process,global){ 'use strict' - + 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 > 65536) throw new Error('requested too many random bytes') // in case browserify isn't using the Uint8Array version var rawBytes = new global.Uint8Array(size) - + // This will not work in older browsers. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues if (size > 0) { // getRandomValues fails on IE if size == 0 crypto.getRandomValues(rawBytes) } - + // XXX: phantomjs doesn't like a buffer being passed here var bytes = Buffer.from(rawBytes.buffer) - + 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":257,"safe-buffer":290}],271:[function(require,module,exports){ (function (process,global){ 'use strict' - + function oldBrowser () { throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') } @@ -44367,25 +44367,25 @@ if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare throw new TypeError('offset must be a number') } - + if (offset > kMaxUint32 || offset < 0) { throw new TypeError('offset must be a uint32') } - + if (offset > kBufferMaxLength || offset > length) { throw new RangeError('offset out of range') } } - + function assertSize (size, offset, length) { if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare throw new TypeError('size must be a number') } - + if (size > kMaxUint32 || size < 0) { throw new TypeError('size must be a uint32') } - + if (size + offset > length || size > kBufferMaxLength) { throw new RangeError('buffer too small') } @@ -44401,7 +44401,7 @@ if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array') } - + if (typeof offset === 'function') { cb = offset offset = 0 @@ -44416,7 +44416,7 @@ assertSize(size, offset, buf.length) return actualFill(buf, offset, size, cb) } - + function actualFill (buf, offset, size, cb) { if (process.browser) { var ourBuf = buf.buffer @@ -44451,16 +44451,16 @@ if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { throw new TypeError('"buf" argument must be a Buffer or Uint8Array') } - + assertOffset(offset, buf.length) - + if (size === undefined) size = buf.length - offset - + assertSize(size, offset, buf.length) - + return actualFill(buf, offset, size) } - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":257,"randombytes":270,"safe-buffer":290}],272:[function(require,module,exports){ module.exports = window.crypto; @@ -44470,8 +44470,8 @@ var randomHex = function(size, callback) { var crypto = require('./crypto.js'); var isCallback = (typeof callback === 'function'); - - + + if (size > 65536) { if(isCallback) { callback(new Error('Requested too many random bytes.')); @@ -44479,11 +44479,11 @@ throw new Error('Requested too many random bytes.'); } }; - - + + // is node if (typeof crypto !== 'undefined' && crypto.randomBytes) { - + if(isCallback) { crypto.randomBytes(size, function(err, result){ if(!err) { @@ -44495,31 +44495,31 @@ } else { return '0x'+ crypto.randomBytes(size).toString('hex'); } - + // is browser } else { var cryptoLib; - + if (typeof crypto !== 'undefined') { cryptoLib = crypto; } else if(typeof msCrypto !== 'undefined') { cryptoLib = msCrypto; } - + if (cryptoLib && cryptoLib.getRandomValues) { var randomBytes = cryptoLib.getRandomValues(new Uint8Array(size)); var returnValue = '0x'+ Array.from(randomBytes).map(function(arr){ return arr.toString(16); }).join(''); - + if(isCallback) { callback(null, returnValue); } else { return returnValue; } - + // not crypto object } else { var error = new Error('No "crypto" object available. This Browser doesn\'t support generating secure random bytes.'); - + if(isCallback) { callback(error); } else { @@ -44528,13 +44528,13 @@ } } }; - - + + module.exports = randomHex; - + },{"./crypto.js":273}],275:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); - + },{"./lib/_stream_duplex.js":276}],276:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -44556,19 +44556,19 @@ // 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 processNextTick = require('process-nextick-args').nextTick; /**/ - + /**/ var objectKeys = Object.keys || function (obj) { var keys = []; @@ -44577,56 +44577,56 @@ }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); - + 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); } - + // 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. processNextTick(onEndNT, this); } - + function onEndNT(self) { self.end(); } - + Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { @@ -44640,21 +44640,21 @@ 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(); - + processNextTick(cb, err); }; - + function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); @@ -44681,30 +44681,30 @@ // 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); }; @@ -44730,40 +44730,40 @@ // 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 processNextTick = require('process-nextick-args').nextTick; /**/ - + 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) { @@ -44772,14 +44772,14 @@ 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; @@ -44789,56 +44789,56 @@ 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() @@ -44850,34 +44850,34 @@ 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) { @@ -44886,26 +44886,26 @@ 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) { @@ -44919,20 +44919,20 @@ 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 @@ -44940,7 +44940,7 @@ Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; - + if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; @@ -44953,15 +44953,15 @@ } 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) { @@ -44976,7 +44976,7 @@ 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) { @@ -44994,10 +44994,10 @@ state.reading = false; } } - + return needMoreData(state); } - + function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); @@ -45006,12 +45006,12 @@ // 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) { @@ -45019,7 +45019,7 @@ } 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, @@ -45030,11 +45030,11 @@ 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; @@ -45042,7 +45042,7 @@ this._readableState.encoding = enc; return this; }; - + // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { @@ -45061,7 +45061,7 @@ } return n; } - + // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { @@ -45081,16 +45081,16 @@ } 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. @@ -45099,15 +45099,15 @@ 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 @@ -45129,17 +45129,17 @@ // '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) { @@ -45158,31 +45158,31 @@ // 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) { @@ -45193,11 +45193,11 @@ } } 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. @@ -45210,13 +45210,13 @@ if (state.sync) processNextTick(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 @@ -45229,7 +45229,7 @@ processNextTick(maybeReadMore_, stream, state); } } - + function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { @@ -45241,7 +45241,7 @@ } 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 @@ -45249,11 +45249,11 @@ 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; @@ -45267,12 +45267,12 @@ } 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) processNextTick(endFn);else src.once('end', endFn); - + dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); @@ -45283,19 +45283,19 @@ } } } - + 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'); @@ -45308,9 +45308,9 @@ 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. @@ -45318,7 +45318,7 @@ // 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. @@ -45342,7 +45342,7 @@ 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) { @@ -45351,10 +45351,10 @@ 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); @@ -45367,24 +45367,24 @@ 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; @@ -45396,21 +45396,21 @@ } }; } - + 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; @@ -45418,9 +45418,9 @@ if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } - + // slow case. multiple pipe destinations. - + if (!dest) { // remove all. var dests = state.pipes; @@ -45428,30 +45428,30 @@ 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(); @@ -45467,16 +45467,16 @@ } } } - + 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 () { @@ -45488,27 +45488,27 @@ } return this; }; - + function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; processNextTick(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) { @@ -45518,46 +45518,46 @@ } 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) { @@ -45569,12 +45569,12 @@ }(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) { @@ -45584,13 +45584,13 @@ stream.resume(); } }; - + return this; }; - + // 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 @@ -45598,7 +45598,7 @@ 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 @@ -45608,10 +45608,10 @@ // 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. @@ -45630,7 +45630,7 @@ } 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 @@ -45660,7 +45660,7 @@ 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. @@ -45690,20 +45690,20 @@ 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; processNextTick(endReadableNT, state, stream); } } - + function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { @@ -45712,13 +45712,13 @@ stream.emit('end'); } } - + function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } - + function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; @@ -45747,7 +45747,7 @@ // 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 @@ -45789,50 +45789,50 @@ // 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, @@ -45841,28 +45841,28 @@ 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); @@ -45871,12 +45871,12 @@ 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. @@ -45890,7 +45890,7 @@ 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; @@ -45901,13 +45901,13 @@ 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); @@ -45917,28 +45917,28 @@ 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":276,"core-util-is":89,"inherits":180}],280:[function(require,module,exports){ @@ -45963,20 +45963,20 @@ // 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 processNextTick = require('process-nextick-args').nextTick; /**/ - + module.exports = Writable; - + /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; @@ -45984,12 +45984,12 @@ 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 () { @@ -45997,34 +45997,34 @@ }; } /* */ - + /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /**/ - + /**/ 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) { @@ -46033,48 +46033,48 @@ 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() @@ -46083,76 +46083,76 @@ 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 = []; @@ -46162,7 +46162,7 @@ } return out; }; - + (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { @@ -46172,7 +46172,7 @@ }); } catch (_) {} })(); - + // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; @@ -46182,7 +46182,7 @@ value: function (object) { if (realHasInstance.call(this, object)) return true; if (this !== Writable) return false; - + return object && object._writableState instanceof WritableState; } }); @@ -46191,58 +46191,58 @@ 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); processNextTick(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) { @@ -46255,49 +46255,49 @@ } 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(); @@ -46305,14 +46305,14 @@ 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; } - + // 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. @@ -46326,13 +46326,13 @@ } } 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 = { @@ -46351,10 +46351,10 @@ } 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; @@ -46363,10 +46363,10 @@ 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 @@ -46387,29 +46387,29 @@ 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); @@ -46419,14 +46419,14 @@ } } } - + 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. @@ -46436,19 +46436,19 @@ 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) { @@ -46458,9 +46458,9 @@ 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++; @@ -46479,7 +46479,7 @@ 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--; @@ -46491,23 +46491,23 @@ 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; @@ -46516,19 +46516,19 @@ 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; } @@ -46555,7 +46555,7 @@ } } } - + function finishMaybe(stream, state) { var need = needFinish(state); if (need) { @@ -46567,7 +46567,7 @@ } return need; } - + function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); @@ -46577,7 +46577,7 @@ state.ended = true; stream.writable = false; } - + function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; @@ -46593,7 +46593,7 @@ state.corkedRequestsFree = corkReq; } } - + Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { @@ -46607,13 +46607,13 @@ 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) { @@ -46623,39 +46623,39 @@ }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":276,"./internal/streams/destroy":282,"./internal/streams/stream":283,"_process":257,"core-util-is":89,"inherits":180,"process-nextick-args":256,"safe-buffer":290,"util-deprecate":330}],281:[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; @@ -46663,12 +46663,12 @@ --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; @@ -46677,7 +46677,7 @@ 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; @@ -46691,10 +46691,10 @@ } 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 }); @@ -46703,19 +46703,19 @@ } },{"safe-buffer":290,"util":55}],282:[function(require,module,exports){ 'use strict'; - + /**/ - + var processNextTick = require('process-nextick-args').nextTick; /**/ - + // 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); @@ -46724,19 +46724,19 @@ } 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) { processNextTick(emitErrorNT, _this, err); @@ -46747,10 +46747,10 @@ cb(err); } }); - + return this; } - + function undestroy() { if (this._readableState) { this._readableState.destroyed = false; @@ -46758,7 +46758,7 @@ this._readableState.ended = false; this._readableState.endEmitted = false; } - + if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; @@ -46767,21 +46767,21 @@ this._writableState.errorEmitted = false; } } - + function emitErrorNT(self, err) { self.emit('error', err); } - + module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":256}],283:[function(require,module,exports){ module.exports = require('events').EventEmitter; - + },{"events":157}],284:[function(require,module,exports){ module.exports = require('./readable').PassThrough - + },{"./readable":285}],285:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; @@ -46790,22 +46790,22 @@ 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":276,"./lib/_stream_passthrough.js":277,"./lib/_stream_readable.js":278,"./lib/_stream_transform.js":279,"./lib/_stream_writable.js":280}],286:[function(require,module,exports){ module.exports = require('./readable').Transform - + },{"./readable":285}],287:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); - + },{"./lib/_stream_writable.js":280}],288:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') - + function RIPEMD160 () { HashBase.call(this, 64) - + // state this._a = 0x67452301 this._b = 0xefcdab89 @@ -46813,19 +46813,19 @@ this._d = 0x10325476 this._e = 0xc3d2e1f0 } - + inherits(RIPEMD160, HashBase) - + RIPEMD160.prototype._update = function () { var m = new Array(16) for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4) - + var al = this._a var bl = this._b var cl = this._c var dl = this._d var el = this._e - + // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 // K = 0x00000000 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 @@ -46845,7 +46845,7 @@ cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10) - + // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 // K = 0x5a827999 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 @@ -46865,7 +46865,7 @@ bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10) - + // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 // K = 0x6ed9eba1 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 @@ -46885,7 +46885,7 @@ al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10) - + // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 // K = 0x8f1bbcdc // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 @@ -46905,7 +46905,7 @@ el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10) - + // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 // K = 0xa953fd4e // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 @@ -46925,13 +46925,13 @@ dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10) - + var ar = this._a var br = this._b var cr = this._c var dr = this._d var er = this._e - + // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 // K' = 0x50a28be6 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 @@ -46951,7 +46951,7 @@ cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10) - + // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 // K' = 0x5c4dd124 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 @@ -46971,7 +46971,7 @@ br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10) - + // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 // K' = 0x6d703ef3 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 @@ -46991,7 +46991,7 @@ ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10) - + // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 // K' = 0x7a6d76e9 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 @@ -47011,7 +47011,7 @@ er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10) - + // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 // K' = 0x00000000 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 @@ -47031,7 +47031,7 @@ dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10) - + // change state var t = (this._b + cl + dr) | 0 this._b = (this._c + dl + er) | 0 @@ -47040,7 +47040,7 @@ this._e = (this._a + bl + cr) | 0 this._a = t } - + RIPEMD160.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80 @@ -47049,12 +47049,12 @@ 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 = new Buffer(20) buffer.writeInt32LE(this._a, 0) @@ -47064,33 +47064,33 @@ 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 - + }).call(this,require("buffer").Buffer) },{"buffer":84,"hash-base":161,"inherits":180}],289:[function(require,module,exports){ const assert = require('assert') @@ -47119,15 +47119,15 @@ } } } - + 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]) @@ -47138,7 +47138,7 @@ return Buffer.from(firstByte + hexLength, 'hex') } } - + /** * RLP Decoding based on: {@link https://github.com/ethereum/wiki/wiki/%5BEnglish%5D-RLP|RLP} * @param {Buffer,String,Integer,Array} data - will be converted to buffer @@ -47148,23 +47148,23 @@ if (!input || input.length === 0) { return Buffer.from([]) } - + input = toBuffer(input) var decoded = _decode(input) - + if (stream) { return decoded } - + assert.equal(decoded.remainder.length, 0, 'invalid remainder') return decoded.data } - + exports.getLength = function (input) { if (!input || input.length === 0) { return Buffer.from([]) } - + input = toBuffer(input) var firstByte = input[0] if (firstByte <= 0x7f) { @@ -47183,12 +47183,12 @@ return llength + length } } - + 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 { @@ -47199,18 +47199,18 @@ // 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) @@ -47222,7 +47222,7 @@ if (data.length < length) { throw (new Error('invalid RLP')) } - + return { data: data, remainder: input.slice(length + llength) @@ -47236,7 +47236,7 @@ decoded.push(d.data) innerRemainder = d.remainder } - + return { data: decoded, remainder: input.slice(length) @@ -47249,12 +47249,12 @@ 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) @@ -47266,11 +47266,11 @@ } } } - + function isHexPrefixed (str) { return str.slice(0, 2) === '0x' } - + // Removes 0x from a given String function stripHexPrefix (str) { if (typeof str !== 'string') { @@ -47278,26 +47278,26 @@ } return isHexPrefixed(str) ? str.slice(2) : str } - + function intToHex (i) { var hex = i.toString(16) if (hex.length % 2) { hex = '0' + hex } - + return hex } - + function padToEven (a) { if (a.length % 2) a = '0' + a return a } - + function intToBuffer (i) { var hex = intToHex(i) return Buffer.from(hex, 'hex') } - + function toBuffer (v) { if (!Buffer.isBuffer(v)) { if (typeof v === 'string') { @@ -47323,12 +47323,12 @@ } return v } - + },{"assert":19,"safe-buffer":290}],290:[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) { @@ -47342,21 +47342,21 @@ 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') @@ -47373,54 +47373,54 @@ } 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":84}],291:[function(require,module,exports){ const util = require('util') const EventEmitter = require('events/') - + var R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } - + module.exports = SafeEventEmitter - - + + function SafeEventEmitter() { EventEmitter.call(this) } - + util.inherits(SafeEventEmitter, EventEmitter) - + SafeEventEmitter.prototype.emit = function (type) { // copied from https://github.com/Gozala/events/blob/master/events.js // modified lines are commented with "edited:" var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); - + var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; - + // If there is no 'error' event listener then throw. if (doError) { var er; @@ -47436,12 +47436,12 @@ err.context = er; throw err; // Unhandled 'error' event } - + var handler = events[type]; - + if (handler === undefined) return false; - + if (typeof handler === 'function') { // edited: using safeApply safeApply(handler, this, args); @@ -47452,10 +47452,10 @@ // edited: using safeApply safeApply(listeners[i], this, args); } - + return true; } - + function safeApply(handler, context, args) { try { ReflectApply(handler, context, args) @@ -47466,14 +47466,14 @@ }) } } - + function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } - + },{"events/":292,"util":333}],292:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -47495,16 +47495,16 @@ // 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 R = typeof Reflect === 'object' ? Reflect : null var ReflectApply = R && typeof R.apply === 'function' ? R.apply : function ReflectApply(target, receiver, args) { return Function.prototype.apply.call(target, receiver, args); } - + var ReflectOwnKeys if (R && typeof R.ownKeys === 'function') { ReflectOwnKeys = R.ownKeys @@ -47518,31 +47518,31 @@ return Object.getOwnPropertyNames(target); }; } - + function ProcessEmitWarning(warning) { if (console && console.warn) console.warn(warning); } - + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { return value !== value; } - + function EventEmitter() { EventEmitter.init.call(this); } module.exports = EventEmitter; - + // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; - + EventEmitter.prototype._events = undefined; EventEmitter.prototype._eventsCount = 0; 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; - + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { enumerable: true, get: function() { @@ -47555,18 +47555,18 @@ defaultMaxListeners = arg; } }); - + EventEmitter.init = function() { - + if (this._events === undefined || this._events === Object.getPrototypeOf(this)._events) { this._events = Object.create(null); this._eventsCount = 0; } - + this._maxListeners = this._maxListeners || undefined; }; - + // 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) { @@ -47576,28 +47576,28 @@ 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); }; - + EventEmitter.prototype.emit = function emit(type) { var args = []; for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); var doError = (type === 'error'); - + var events = this._events; if (events !== undefined) doError = (doError && events.error === undefined); else if (!doError) return false; - + // If there is no 'error' event listener then throw. if (doError) { var er; @@ -47613,12 +47613,12 @@ err.context = er; throw err; // Unhandled 'error' event } - + var handler = events[type]; - + if (handler === undefined) return false; - + if (typeof handler === 'function') { ReflectApply(handler, this, args); } else { @@ -47627,19 +47627,19 @@ for (var i = 0; i < len; ++i) ReflectApply(listeners[i], this, args); } - + return true; }; - + function _addListener(target, type, listener, prepend) { var m; var events; var existing; - + if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); } - + events = target._events; if (events === undefined) { events = target._events = Object.create(null); @@ -47650,14 +47650,14 @@ if (events.newListener !== undefined) { 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 === undefined) { // Optimize the case of one listener. Don't need the extra array object. existing = events[type] = listener; @@ -47673,7 +47673,7 @@ } else { existing.push(listener); } - + // Check for listener leak m = $getMaxListeners(target); if (m > 0 && existing.length > m && !existing.warned) { @@ -47691,21 +47691,21 @@ ProcessEmitWarning(w); } } - + 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() { var args = []; for (var i = 0; i < arguments.length; i++) args.push(arguments[i]); @@ -47715,7 +47715,7 @@ ReflectApply(this.listener, this.target, args); } } - + function _onceWrap(target, type, listener) { var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; var wrapped = onceWrapper.bind(state); @@ -47723,7 +47723,7 @@ state.wrapFn = wrapped; return wrapped; } - + EventEmitter.prototype.once = function once(type, listener) { if (typeof listener !== 'function') { throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); @@ -47731,7 +47731,7 @@ this.on(type, _onceWrap(this, type, listener)); return this; }; - + EventEmitter.prototype.prependOnceListener = function prependOnceListener(type, listener) { if (typeof listener !== 'function') { @@ -47740,24 +47740,24 @@ 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('The "listener" argument must be of type Function. Received type ' + typeof listener); } - + events = this._events; if (events === undefined) return this; - + list = events[type]; if (list === undefined) return this; - + if (list === listener || list.listener === listener) { if (--this._eventsCount === 0) this._events = Object.create(null); @@ -47768,7 +47768,7 @@ } } 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; @@ -47776,36 +47776,36 @@ 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 !== undefined) this.emit('removeListener', type, originalListener || listener); } - + return this; }; - + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; - + EventEmitter.prototype.removeAllListeners = function removeAllListeners(type) { var listeners, events, i; - + events = this._events; if (events === undefined) return this; - + // not listening for removeListener, no need to emit if (events.removeListener === undefined) { if (arguments.length === 0) { @@ -47819,7 +47819,7 @@ } return this; } - + // emit removeListener for all listeners on all events if (arguments.length === 0) { var keys = Object.keys(events); @@ -47834,9 +47834,9 @@ this._eventsCount = 0; return this; } - + listeners = events[type]; - + if (typeof listeners === 'function') { this.removeListener(type, listeners); } else if (listeners !== undefined) { @@ -47845,35 +47845,35 @@ this.removeListener(type, listeners[i]); } } - + return this; }; - + function _listeners(target, type, unwrap) { var events = target._events; - + if (events === undefined) return []; - + var evlistener = events[type]; if (evlistener === undefined) 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); @@ -47881,41 +47881,41 @@ return listenerCount.call(emitter, type); } }; - + EventEmitter.prototype.listenerCount = listenerCount; function listenerCount(type) { var events = this._events; - + if (events !== undefined) { var evlistener = events[type]; - + if (typeof evlistener === 'function') { return 1; } else if (evlistener !== undefined) { return evlistener.length; } } - + return 0; } - + EventEmitter.prototype.eventNames = function eventNames() { return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; }; - + function arrayClone(arr, n) { var copy = new Array(n); for (var i = 0; i < n; ++i) copy[i] = arr[i]; return copy; } - + function spliceOne(list, index) { for (; index + 1 < list.length; index++) list[index] = list[index + 1]; list.pop(); } - + function unwrapListeners(arr) { var ret = new Array(arr.length); for (var i = 0; i < ret.length; ++i) { @@ -47923,42 +47923,42 @@ } return ret; } - + },{}],293:[function(require,module,exports){ module.exports = require('scryptsy') - + },{"scryptsy":294}],294:[function(require,module,exports){ (function (Buffer){ var pbkdf2Sync = require('pbkdf2').pbkdf2Sync - + var MAX_VALUE = 0x7fffffff - + // N = Cpu cost, r = Memory cost, p = parallelization cost function scrypt (key, salt, N, r, p, dkLen, progressCallback) { if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2') - + if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large') if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large') - + var XY = new Buffer(256 * r) var V = new Buffer(128 * r * N) - + // pseudo global var B32 = new Int32Array(16) // salsa20_8 var x = new Int32Array(16) // salsa20_8 var _X = new Buffer(64) // blockmix_salsa8 - + // pseudo global var B = pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256') - + var tickCallback if (progressCallback) { var totalOps = p * N * 2 var currentOp = 0 - + tickCallback = function () { ++currentOp - + // send progress notifications once every 1,000 ops if (currentOp % 1000 === 0) { progressCallback({ @@ -47969,69 +47969,69 @@ } } } - + for (var i = 0; i < p; i++) { smix(B, i * 128 * r, r, N, V, XY) } - + return pbkdf2Sync(key, B, 1, dkLen, 'sha256') - + // all of these functions are actually moved to the top // due to function hoisting - + function smix (B, Bi, r, N, V, XY) { var Xi = 0 var Yi = 128 * r var i - + B.copy(XY, Xi, Bi, Bi + Yi) - + for (i = 0; i < N; i++) { XY.copy(V, i * Yi, Xi, Xi + Yi) blockmix_salsa8(XY, Xi, Yi, r) - + if (tickCallback) tickCallback() } - + for (i = 0; i < N; i++) { var offset = Xi + (2 * r - 1) * 64 var j = XY.readUInt32LE(offset) & (N - 1) blockxor(V, j * Yi, XY, Xi, Yi) blockmix_salsa8(XY, Xi, Yi, r) - + if (tickCallback) tickCallback() } - + XY.copy(B, Bi, Xi, Xi + Yi) } - + function blockmix_salsa8 (BY, Bi, Yi, r) { var i - + arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64) - + for (i = 0; i < 2 * r; i++) { blockxor(BY, i * 64, _X, 0, 64) salsa20_8(_X) arraycopy(_X, 0, BY, Yi + (i * 64), 64) } - + for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64) } - + for (i = 0; i < r; i++) { arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64) } } - + function R (a, b) { return (a << b) | (a >>> (32 - b)) } - + function salsa20_8 (B) { var i - + for (i = 0; i < 16; i++) { B32[i] = (B[i * 4 + 0] & 0xff) << 0 B32[i] |= (B[i * 4 + 1] & 0xff) << 8 @@ -48039,9 +48039,9 @@ B32[i] |= (B[i * 4 + 3] & 0xff) << 24 // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js } - + arraycopy(B32, 0, x, 0, 16) - + for (i = 8; i > 0; i -= 2) { x[ 4] ^= R(x[ 0] + x[12], 7) x[ 8] ^= R(x[ 4] + x[ 0], 9) @@ -48076,9 +48076,9 @@ x[14] ^= R(x[13] + x[12], 13) x[15] ^= R(x[14] + x[13], 18) } - + for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i] - + for (i = 0; i < 16; i++) { var bi = i * 4 B[bi + 0] = (B32[i] >> 0 & 0xff) @@ -48088,7 +48088,7 @@ // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js } } - + // naive approach... going back to loop unrolling may yield additional performance function blockxor (S, Si, D, Di, len) { for (var i = 0; i < len; i++) { @@ -48096,7 +48096,7 @@ } } } - + function arraycopy (src, srcPos, dest, destPos, length) { if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { src.copy(dest, destPos, srcPos, srcPos + length) @@ -48106,67 +48106,67 @@ } } } - + module.exports = scrypt - + }).call(this,require("buffer").Buffer) },{"buffer":84,"pbkdf2":247}],295:[function(require,module,exports){ 'use strict' module.exports = require('./lib')(require('./lib/elliptic')) - + },{"./lib":299,"./lib/elliptic":298}],296:[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("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":181}],297:[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, @@ -48188,7 +48188,7 @@ 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, @@ -48214,35 +48214,35 @@ 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 || @@ -48251,7 +48251,7 @@ return } index += 3 - + // sequence element 1: octet string, up to 32 bytes if (length < index + 2 || privateKey[index] !== 0x04 || @@ -48259,24 +48259,24 @@ 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) @@ -48286,33 +48286,33 @@ } 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) { @@ -48324,10 +48324,10 @@ 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) { @@ -48339,70 +48339,70 @@ 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":52,"safe-buffer":290}],298:[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) { @@ -48419,150 +48419,150 @@ 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) - + return Buffer.from(ecparams.g.mul(tweak).add(pair.pub).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([ @@ -48572,173 +48572,173 @@ 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":300,"bn.js":53,"create-hash":91,"elliptic":109,"safe-buffer":290}],299:[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) @@ -48746,126 +48746,126 @@ 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":296,"./der":297,"./messages.json":300}],300:[function(require,module,exports){ module.exports={ "COMPRESSED_TYPE_INVALID": "compressed should be a boolean", @@ -48904,26 +48904,26 @@ "TWEAK_TYPE_INVALID": "tweak should be a Buffer", "TWEAK_LENGTH_INVALID": "tweak length is invalid" } - + },{}],301:[function(require,module,exports){ (function (process){ ;(function(global) { - + 'use strict'; - + var nextTick = function (fn) { setTimeout(fn, 0); } if (typeof process != 'undefined' && process && typeof process.nextTick == 'function') { // node.js and the like nextTick = process.nextTick; } - + function semaphore(capacity) { var semaphore = { capacity: capacity || 1, current: 0, queue: [], firstHere: false, - + take: function() { if (semaphore.firstHere === false) { semaphore.current++; @@ -48933,21 +48933,21 @@ var isFirst = 0; } var item = { n: 1 }; - + if (typeof arguments[0] == 'function') { item.task = arguments[0]; } else { item.n = arguments[0]; } - + if (arguments.length >= 2) { if (typeof arguments[1] == 'function') item.task = arguments[1]; else item.n = arguments[1]; } - + var task = item.task; item.task = function() { task(semaphore.leave); }; - + if (semaphore.current + item.n - isFirst > semaphore.capacity) { if (isFirst === 1) { semaphore.current--; @@ -48955,46 +48955,46 @@ } return semaphore.queue.push(item); } - + semaphore.current += item.n - isFirst; item.task(semaphore.leave); if (isFirst === 1) semaphore.firstHere = false; }, - + leave: function(n) { n = n || 1; - + semaphore.current -= n; - + if (!semaphore.queue.length) { if (semaphore.current < 0) { throw new Error('leave called too many times.'); } - + return; } - + var item = semaphore.queue[0]; - + if (item.n + semaphore.current > semaphore.capacity) { return; } - + semaphore.queue.shift(); semaphore.current += item.n; - + nextTick(item.task); }, - + available: function(n) { n = n || 1; return(semaphore.current + n <= semaphore.capacity); } }; - + return semaphore; }; - + if (typeof exports === 'object') { // node export module.exports = semaphore; @@ -49008,7 +49008,7 @@ global.semaphore = semaphore; } }(this)); - + }).call(this,require('_process')) },{"_process":257}],302:[function(require,module,exports){ 'use strict'; @@ -49018,10 +49018,10 @@ args.splice(1, 0, 0); setTimeout.apply(null, args); }; - + },{}],303:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer - + // prototype class for hash functions function Hash (blockSize, finalSize) { this._block = Buffer.alloc(blockSize) @@ -49029,96 +49029,96 @@ 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":290}],304:[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":305,"./sha1":306,"./sha224":307,"./sha256":308,"./sha384":309,"./sha512":310}],305:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined @@ -49127,94 +49127,94 @@ * 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":303,"inherits":180,"safe-buffer":290}],306:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined @@ -49224,98 +49224,98 @@ * 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":303,"inherits":180,"safe-buffer":290}],307:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -49324,24 +49324,24 @@ * 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 @@ -49351,13 +49351,13 @@ 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) @@ -49365,12 +49365,12 @@ H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) - + return H } - + module.exports = Sha224 - + },{"./hash":303,"./sha256":308,"inherits":180,"safe-buffer":290}],308:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined @@ -49379,11 +49379,11 @@ * 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, @@ -49402,19 +49402,19 @@ 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 @@ -49424,37 +49424,37 @@ 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 @@ -49463,14 +49463,14 @@ 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 @@ -49480,7 +49480,7 @@ b = a a = (T1 + T2) | 0 } - + this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 @@ -49490,10 +49490,10 @@ 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) @@ -49502,29 +49502,29 @@ H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) H.writeInt32BE(this._h, 28) - + return H } - + module.exports = Sha256 - + },{"./hash":303,"inherits":180,"safe-buffer":290}],309:[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 @@ -49534,7 +49534,7 @@ this._fh = 0x8eb44a87 this._gh = 0xdb0c2e0d this._hh = 0x47b5481d - + this._al = 0xc1059ed8 this._bl = 0x367cd507 this._cl = 0x3070dd17 @@ -49543,35 +49543,35 @@ 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":303,"./sha512":310,"inherits":180,"safe-buffer":290}],310:[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, @@ -49614,18 +49614,18 @@ 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 @@ -49635,7 +49635,7 @@ this._fh = 0x9b05688c this._gh = 0x1f83d9ab this._hh = 0x5be0cd19 - + this._al = 0xf3bcc908 this._bl = 0x84caa73b this._cl = 0xfe94f82b @@ -49644,49 +49644,49 @@ 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 @@ -49695,7 +49695,7 @@ 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 @@ -49704,7 +49704,7 @@ 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) @@ -49714,49 +49714,49 @@ 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 @@ -49765,11 +49765,11 @@ 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 @@ -49787,7 +49787,7 @@ 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 @@ -49796,7 +49796,7 @@ 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 @@ -49806,15 +49806,15 @@ 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) @@ -49823,12 +49823,12 @@ writeInt64BE(this._fh, this._fl, 40) writeInt64BE(this._gh, this._gl, 48) writeInt64BE(this._hh, this._hl, 56) - + return H } - + module.exports = Sha512 - + },{"./hash":303,"inherits":180,"safe-buffer":290}],311:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -49850,34 +49850,34 @@ // 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) { @@ -49885,40 +49885,40 @@ } } } - + 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(); @@ -49926,38 +49926,38 @@ 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":157,"inherits":180,"readable-stream/duplex.js":275,"readable-stream/passthrough.js":284,"readable-stream/readable.js":285,"readable-stream/transform.js":286,"readable-stream/writable.js":287}],312:[function(require,module,exports){ (function (global){ var ClientRequest = require('./lib/request') @@ -49965,56 +49965,56 @@ var extend = require('xtend') var statusCodes = require('builtin-status-codes') var url = require('url') - + var http = exports - + http.request = function (opts, cb) { if (typeof opts === 'string') opts = url.parse(opts) else opts = extend(opts) - + // Normally, the page is loaded from http or https, so not specifying a protocol // will result in a (valid) protocol-relative url. However, this won't work if // the protocol is something else, like 'file:' var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : '' - + var protocol = opts.protocol || defaultProtocol var host = opts.hostname || opts.host var port = opts.port var path = opts.path || '/' - + // Necessary for IPv6 addresses if (host && host.indexOf(':') !== -1) host = '[' + host + ']' - + // This may be a relative url. The browser should always be able to interpret it correctly. opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path opts.method = (opts.method || 'GET').toUpperCase() opts.headers = opts.headers || {} - + // Also valid opts.auth, opts.mode - + var req = new ClientRequest(opts) if (cb) req.on('response', cb) return req } - + http.get = function get (opts, cb) { var req = http.request(opts, cb) req.end() return req } - + http.ClientRequest = ClientRequest http.IncomingMessage = IncomingMessage - + http.Agent = function () {} http.Agent.defaultMaxSockets = 4 - + http.STATUS_CODES = statusCodes - + http.METHODS = [ 'CHECKOUT', 'CONNECT', @@ -50047,17 +50047,17 @@ },{"./lib/request":314,"./lib/response":315,"builtin-status-codes":85,"url":327,"xtend":423}],313:[function(require,module,exports){ (function (global){ exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream) - + exports.writableStream = isFunction(global.WritableStream) - + exports.abortController = isFunction(global.AbortController) - + exports.blobConstructor = false try { new Blob([new ArrayBuffer(1)]) exports.blobConstructor = true } catch (e) {} - + // The xhr request to example.com may violate some restrictive CSP configurations, // so if we're running in a browser that supports `fetch`, avoid calling getXHR() // and assume support for certain features below. @@ -50065,7 +50065,7 @@ function getXHR () { // Cache the xhr value if (xhr !== undefined) return xhr - + if (global.XMLHttpRequest) { xhr = new global.XMLHttpRequest() // If XDomainRequest is available (ie only, where xhr might not work @@ -50082,7 +50082,7 @@ } return xhr } - + function checkTypeSupport (type) { var xhr = getXHR() if (!xhr) return false @@ -50092,34 +50092,34 @@ } catch (e) {} return false } - + // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. // Safari 7.1 appears to have fixed this bug. var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined' var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice) - + // If fetch is supported, then arraybuffer will be supported too. Skip calling // checkTypeSupport(), since that calls getXHR(). exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer')) - + // These next two tests unavoidably show warnings in Chrome. Since fetch will always // be used if it's available, just return false for these to avoid the warnings. exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream') exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer && checkTypeSupport('moz-chunked-arraybuffer') - + // If fetch is supported, then overrideMimeType will be supported too. Skip calling // getXHR(). exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false) - + exports.vbArray = isFunction(global.VBArray) - + function isFunction (value) { return typeof value === 'function' } - + xhr = null // Help gc - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],314:[function(require,module,exports){ (function (process,global,Buffer){ @@ -50128,10 +50128,10 @@ var response = require('./response') var stream = require('readable-stream') var toArrayBuffer = require('to-arraybuffer') - + var IncomingMessage = response.IncomingMessage var rStates = response.readyStates - + function decideMode (preferBinary, useFetch) { if (capability.fetch && useFetch) { return 'fetch' @@ -50147,11 +50147,11 @@ return 'text' } } - + var ClientRequest = module.exports = function (opts) { var self = this stream.Writable.call(self) - + self._opts = opts self._body = [] self._headers = {} @@ -50160,7 +50160,7 @@ Object.keys(opts.headers).forEach(function (name) { self.setHeader(name, opts.headers[name]) }) - + var preferBinary var useFetch = true if (opts.mode === 'disable-fetch' || ('requestTimeout' in opts && !capability.abortController)) { @@ -50181,14 +50181,14 @@ throw new Error('Invalid value for opts.mode') } self._mode = decideMode(preferBinary, useFetch) - + self.on('finish', function () { self._onFinish() }) } - + inherits(ClientRequest, stream.Writable) - + ClientRequest.prototype.setHeader = function (name, value) { var self = this var lowerName = name.toLowerCase() @@ -50197,32 +50197,32 @@ // http-browserify did it, so I will too. if (unsafeHeaders.indexOf(lowerName) !== -1) return - + self._headers[lowerName] = { name: name, value: value } } - + ClientRequest.prototype.getHeader = function (name) { var header = this._headers[name.toLowerCase()] if (header) return header.value return null } - + ClientRequest.prototype.removeHeader = function (name) { var self = this delete self._headers[name.toLowerCase()] } - + ClientRequest.prototype._onFinish = function () { var self = this - + if (self._destroyed) return var opts = self._opts - + var headersObj = self._headers var body = null if (opts.method !== 'GET' && opts.method !== 'HEAD') { @@ -50239,7 +50239,7 @@ body = Buffer.concat(self._body).toString() } } - + // create flattened list of headers var headersList = [] Object.keys(headersObj).forEach(function (keyName) { @@ -50253,14 +50253,14 @@ headersList.push([name, value]) } }) - + if (self._mode === 'fetch') { var signal = null if (capability.abortController) { var controller = new AbortController() signal = controller.signal self._fetchAbortController = controller - + if ('requestTimeout' in opts && opts.requestTimeout !== 0) { global.setTimeout(function () { self.emit('requestTimeout') @@ -50269,7 +50269,7 @@ }, opts.requestTimeout) } } - + global.fetch(self._opts.url, { method: self._opts.method, headers: headersList, @@ -50293,28 +50293,28 @@ }) return } - + // Can't set responseType on really old browsers if ('responseType' in xhr) xhr.responseType = self._mode.split(':')[0] - + if ('withCredentials' in xhr) xhr.withCredentials = !!opts.withCredentials - + if (self._mode === 'text' && 'overrideMimeType' in xhr) xhr.overrideMimeType('text/plain; charset=x-user-defined') - + if ('requestTimeout' in opts) { xhr.timeout = opts.requestTimeout xhr.ontimeout = function () { self.emit('requestTimeout') } } - + headersList.forEach(function (header) { xhr.setRequestHeader(header[0], header[1]) }) - + self._response = null xhr.onreadystatechange = function () { switch (xhr.readyState) { @@ -50331,13 +50331,13 @@ self._onXHRProgress() } } - + xhr.onerror = function () { if (self._destroyed) return self.emit('error', new Error('XHR error')) } - + try { xhr.send(body) } catch (err) { @@ -50348,7 +50348,7 @@ } } } - + /** * Checks if xhr.status is readable and non-zero, indicating no error. * Even though the spec says it should be available in readyState 3, @@ -50362,40 +50362,40 @@ return false } } - + ClientRequest.prototype._onXHRProgress = function () { var self = this - + if (!statusValid(self._xhr) || self._destroyed) return - + if (!self._response) self._connect() - + self._response._onXHRProgress() } - + ClientRequest.prototype._connect = function () { var self = this - + if (self._destroyed) return - + self._response = new IncomingMessage(self._xhr, self._fetchResponse, self._mode) self._response.on('error', function(err) { self.emit('error', err) }) - + self.emit('response', self._response) } - + ClientRequest.prototype._write = function (chunk, encoding, cb) { var self = this - + self._body.push(chunk) cb() } - + ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function () { var self = this self._destroyed = true @@ -50406,22 +50406,22 @@ else if (self._fetchAbortController) self._fetchAbortController.abort() } - + ClientRequest.prototype.end = function (data, encoding, cb) { var self = this if (typeof data === 'function') { cb = data data = undefined } - + stream.Writable.prototype.end.call(self, data, encoding, cb) } - + ClientRequest.prototype.flushHeaders = function () {} ClientRequest.prototype.setTimeout = function () {} ClientRequest.prototype.setNoDelay = function () {} ClientRequest.prototype.setSocketKeepAlive = function () {} - + // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method var unsafeHeaders = [ 'accept-charset', @@ -50446,14 +50446,14 @@ 'user-agent', 'via' ] - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":313,"./response":315,"_process":257,"buffer":84,"inherits":180,"readable-stream":285,"to-arraybuffer":323}],315:[function(require,module,exports){ (function (process,global,Buffer){ var capability = require('./capability') var inherits = require('inherits') var stream = require('readable-stream') - + var rStates = exports.readyStates = { UNSENT: 0, OPENED: 1, @@ -50461,17 +50461,17 @@ LOADING: 3, DONE: 4 } - + var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) { var self = this stream.Readable.call(self) - + self._mode = mode self.headers = {} self.rawHeaders = [] self.trailers = {} self.rawTrailers = [] - + // Fake the 'close' event, but only once 'end' fires self.on('end', function () { // The nextTick is necessary to prevent the 'request' module from causing an infinite loop @@ -50479,19 +50479,19 @@ self.emit('close') }) }) - + if (mode === 'fetch') { self._fetchResponse = response - + self.url = response.url self.statusCode = response.status self.statusMessage = response.statusText - + response.headers.forEach(function (header, key){ self.headers[key.toLowerCase()] = header self.rawHeaders.push(key, header) }) - + if (capability.writableStream) { var writable = new WritableStream({ write: function (chunk) { @@ -50514,7 +50514,7 @@ self.emit('error', err) } }) - + try { response.body.pipeTo(writable) return @@ -50541,7 +50541,7 @@ } else { self._xhr = xhr self._pos = 0 - + self.url = xhr.responseURL self.statusCode = xhr.status self.statusMessage = xhr.statusText @@ -50563,7 +50563,7 @@ self.rawHeaders.push(matches[1], matches[2]) } }) - + self._charset = 'x-user-defined' if (!capability.overrideMimeType) { var mimeType = self.rawHeaders['mime-type'] @@ -50578,24 +50578,24 @@ } } } - + inherits(IncomingMessage, stream.Readable) - + IncomingMessage.prototype._read = function () { var self = this - + var resolve = self._resumeFetch if (resolve) { self._resumeFetch = null resolve() } } - + IncomingMessage.prototype._onXHRProgress = function () { var self = this - + var xhr = self._xhr - + var response = null switch (self._mode) { case 'text:vbarray': // For IE9 @@ -50609,7 +50609,7 @@ self.push(new Buffer(response)) break } - // Falls through in IE8 + // Falls through in IE8 case 'text': try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 response = xhr.responseText @@ -50623,7 +50623,7 @@ var buffer = new Buffer(newData.length) for (var i = 0; i < newData.length; i++) buffer[i] = newData.charCodeAt(i) & 0xff - + self.push(buffer) } else { self.push(newData, self._charset) @@ -50661,13 +50661,13 @@ reader.readAsArrayBuffer(response) break } - + // The ms-stream case handles end separately in reader.onload() if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { self.push(null) } } - + }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"./capability":313,"_process":257,"buffer":84,"inherits":180,"readable-stream":285}],316:[function(require,module,exports){ 'use strict'; @@ -50676,12 +50676,12 @@ return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); }; - + },{}],317:[function(require,module,exports){ 'use strict'; - + var Buffer = require('safe-buffer').Buffer; - + var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { @@ -50691,7 +50691,7 @@ return false; } }; - + function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; @@ -50719,7 +50719,7 @@ } } }; - + // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { @@ -50727,7 +50727,7 @@ 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. @@ -50759,7 +50759,7 @@ this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } - + StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; @@ -50775,12 +50775,12 @@ 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) { @@ -50790,14 +50790,14 @@ 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. 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 -1; } - + // 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. @@ -50825,7 +50825,7 @@ } 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 @@ -50852,7 +50852,7 @@ } } } - + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; @@ -50865,7 +50865,7 @@ 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. @@ -50877,7 +50877,7 @@ buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } - + // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { @@ -50885,7 +50885,7 @@ if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); 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 @@ -50910,7 +50910,7 @@ 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) { @@ -50921,7 +50921,7 @@ } return r; } - + function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); @@ -50935,24 +50935,24 @@ } 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":290}],318:[function(require,module,exports){ var isHexPrefixed = require('is-hex-prefixed'); - + /** * Removes '0x' from a given `String` is present * @param {String} str the string value @@ -50962,15 +50962,15 @@ if (typeof str !== 'string') { return str; } - + return isHexPrefixed(str) ? str.slice(2) : str; } - + },{"is-hex-prefixed":185}],319:[function(require,module,exports){ var unavailable = function unavailable() { throw "This swarm.js function isn't available on the browser."; }; - + var fsp = { readFile: unavailable }; var files = { download: unavailable, safeDownloadArchived: unavailable, directoryTree: unavailable }; var os = { platform: unavailable, arch: unavailable }; @@ -50984,7 +50984,7 @@ var hash = require("./swarm-hash.js"); var pick = require("./pick.js"); var swarm = require("./swarm"); - + module.exports = swarm({ fsp: fsp, files: files, @@ -51028,7 +51028,7 @@ reader.readAsArrayBuffer(file); }); }; - + var fileInput = void 0; if (type === "directory") { fileInput = document.createElement("input"); @@ -51044,14 +51044,14 @@ fileInput.addEventListener("change", fileLoader); fileInput.type = "file"; }; - + var mouseEvent = document.createEvent("MouseEvents"); mouseEvent.initEvent("click", true, false); fileInput.dispatchEvent(mouseEvent); }); }; }; - + module.exports = { data: picker("data"), file: picker("file"), @@ -51059,16 +51059,16 @@ }; },{}],321:[function(require,module,exports){ // Thanks https://github.com/axic/swarmhash - + var keccak = require("eth-lib/lib/hash").keccak256; var Bytes = require("eth-lib/lib/bytes"); - + var swarmHashBlock = function swarmHashBlock(length, data) { var lengthEncoded = Bytes.reverse(Bytes.pad(6, Bytes.fromNumber(length))); var bytes = Bytes.flatten([lengthEncoded, "0x0000", data]); return keccak(bytes).slice(2); }; - + // (Bytes | Uint8Array | String) -> String var swarmHash = function swarmHash(data) { if (typeof data === "string" && data.slice(0, 2) !== "0x") { @@ -51076,27 +51076,27 @@ } else if (typeof data !== "string" && data.length !== undefined) { data = Bytes.fromUint8Array(data); } - + var length = Bytes.length(data); - + if (length <= 4096) { return swarmHashBlock(length, data); } - + var maxSize = 4096; while (maxSize * (4096 / 32) < length) { maxSize *= 4096 / 32; } - + var innerNodes = []; for (var i = 0; i < length; i += maxSize) { var size = maxSize < length - i ? maxSize : length - i; innerNodes.push(swarmHash(Bytes.slice(data, i, i + size))); } - + return swarmHashBlock(length, Bytes.flatten(innerNodes)); }; - + module.exports = swarmHash; },{"eth-lib/lib/bytes":133,"eth-lib/lib/hash":134}],322:[function(require,module,exports){ // TODO: this is a temporary fix to hide those libraries from the browser. A @@ -51116,8 +51116,8 @@ bytes = _ref.bytes, hash = _ref.hash, pick = _ref.pick; - - + + // ∀ a . String -> JSON -> Map String a -o Map String a // Inserts a key/val pair in an object impurely. var impureInsert = function impureInsert(key) { @@ -51127,7 +51127,7 @@ }; }; }; - + // String -> JSON -> Map String JSON // Merges an array of keys and an array of vals into an object. var toMap = function toMap(keys) { @@ -51138,7 +51138,7 @@ }return map; }; }; - + // ∀ a . Map String a -> Map String a -> Map String a // Merges two maps into one. var merge = function merge(a) { @@ -51151,7 +51151,7 @@ }return map; }; }; - + // ∀ a . [a] -> [a] -> Bool var equals = function equals(a) { return function (b) { @@ -51165,14 +51165,14 @@ return true; }; }; - + // String -> String -> String var rawUrl = function rawUrl(swarmUrl) { return function (hash) { return swarmUrl + "/bzzr:/" + hash; }; }; - + // String -> String -> Promise Uint8Array // Gets the raw contents of a Swarm hash address. var downloadData = function downloadData(swarmUrl) { @@ -51185,10 +51185,10 @@ }); }; }; - + // type Entry = {"type": String, "hash": String} // type File = {"type": String, "data": Uint8Array} - + // String -> String -> Promise (Map String Entry) // Solves the manifest of a Swarm address recursively. // Returns a map from full paths to entries. @@ -51203,7 +51203,7 @@ type: entry.contentType, hash: entry.hash }; }; - + // To download a single entry: // if type is bzz-manifest, go deeper // if not, add it to the routing table @@ -51214,7 +51214,7 @@ return entry.contentType === "application/bzz-manifest+json" ? search(entry.hash)(path + entry.path)(routes) : Promise.resolve(impureInsert(path + entry.path)(format(entry))(routes)); } }; - + // Downloads the initial manifest and then each entry. return downloadData(swarmUrl)(hash).then(function (text) { return JSON.parse(toString(text)).entries; @@ -51226,11 +51226,11 @@ }; }; }; - + return search(hash)("")({}); }; }; - + // String -> String -> Promise (Map String String) // Same as `downloadEntries`, but returns only hashes (no types). var downloadRoutes = function downloadRoutes(swarmUrl) { @@ -51242,7 +51242,7 @@ }); }; }; - + // String -> String -> Promise (Map String File) // Gets the entire directory tree in a Swarm address. // Returns a promise mapping paths to file contents. @@ -51268,7 +51268,7 @@ }); }; }; - + // String -> String -> String -> Promise String // Gets the raw contents of a Swarm hash address. // Returns a promise with the downloaded file path. @@ -51279,7 +51279,7 @@ }; }; }; - + // String -> String -> String -> Promise (Map String String) // Gets the entire directory tree in a Swarm address. // Returns a promise mapping paths to file contents. @@ -51301,7 +51301,7 @@ }; }; }; - + // String -> Uint8Array -> Promise String // Uploads raw data to Swarm. // Returns a promise with the uploaded hash. @@ -51312,7 +51312,7 @@ method: "POST" }); }; }; - + // String -> String -> String -> File -> Promise String // Uploads a file to the Swarm manifest at a given hash, under a specific // route. Returns a promise containing the uploaded hash. @@ -51343,14 +51343,14 @@ }; }; }; - + // String -> {type: String, data: Uint8Array} -> Promise String var uploadFile = function uploadFile(swarmUrl) { return function (file) { return uploadDirectory(swarmUrl)({ "": file }); }; }; - + // String -> String -> Promise String var uploadFileFromDisk = function uploadFileFromDisk(swarmUrl) { return function (filePath) { @@ -51359,7 +51359,7 @@ }); }; }; - + // String -> Map String File -> Promise String // Uploads a directory to Swarm. The directory is // represented as a map of routes and files. @@ -51379,14 +51379,14 @@ }); }; }; - + // String -> Promise String var uploadDataFromDisk = function uploadDataFromDisk(swarmUrl) { return function (filePath) { return fsp.readFile(filePath).then(uploadData(swarmUrl)); }; }; - + // String -> Nullable String -> String -> Promise String var uploadDirectoryFromDisk = function uploadDirectoryFromDisk(swarmUrl) { return function (defaultPath) { @@ -51411,7 +51411,7 @@ }; }; }; - + // String -> UploadInfo -> Promise String // Simplified multi-type upload which calls the correct // one based on the type of the argument given. @@ -51420,15 +51420,15 @@ // Upload raw data from browser if (arg.pick === "data") { return pick.data().then(uploadData(swarmUrl)); - + // Upload a file from browser } else if (arg.pick === "file") { return pick.file().then(uploadFile(swarmUrl)); - + // Upload a directory from browser } else if (arg.pick === "directory") { return pick.directory().then(uploadDirectory(swarmUrl)); - + // Upload directory/file from disk } else if (arg.path) { switch (arg.kind) { @@ -51439,20 +51439,20 @@ case "directory": return uploadDirectoryFromDisk(swarmUrl)(arg.defaultFile)(arg.path); }; - + // Upload UTF-8 string or raw data (buffer) } else if (arg.length || typeof arg === "string") { return uploadData(swarmUrl)(arg); - + // Upload directory with JSON } else if (arg instanceof Object) { return uploadDirectory(swarmUrl)(arg); } - + return Promise.reject(new Error("Bad arguments")); }; }; - + // String -> String -> Nullable String -> Promise (String | Uint8Array | Map String Uint8Array) // Simplified multi-type download which calls the correct function based on // the type of the argument given, and on whether the Swwarm address has a @@ -51470,7 +51470,7 @@ }; }; }; - + // String -> Promise String // Downloads the Swarm binaries into a path. Returns a promise that only // resolves when the exact Swarm file is there, and verified to be correct. @@ -51483,7 +51483,7 @@ var binaryMD5 = archive.binaryMD5; return files.safeDownloadArchived(archiveUrl)(archiveMD5)(binaryMD5)(path); }; - + // type SwarmSetup = { // account : String, // password : String, @@ -51497,14 +51497,14 @@ // archiveMD5: String // }] // } - + // SwarmSetup ~> Promise Process // Starts the Swarm process. var startProcess = function startProcess(swarmSetup) { return new Promise(function (resolve, reject) { var spawn = child_process.spawn; - - + + var hasString = function hasString(str) { return function (buffer) { return ('' + buffer).indexOf(str) !== -1; @@ -51515,19 +51515,19 @@ dataDir = swarmSetup.dataDir, ensApi = swarmSetup.ensApi, privateKey = swarmSetup.privateKey; - - + + var STARTUP_TIMEOUT_SECS = 3; var WAITING_PASSWORD = 0; var STARTING = 1; var LISTENING = 2; var PASSWORD_PROMPT_HOOK = "Passphrase"; var LISTENING_HOOK = "Swarm http proxy started"; - + var state = WAITING_PASSWORD; - + var swarmProcess = spawn(swarmSetup.binPath, ['--bzzaccount', account || privateKey, '--datadir', dataDir, '--ens-api', ensApi]); - + var handleProcessOutput = function handleProcessOutput(data) { if (state === WAITING_PASSWORD && hasString(PASSWORD_PROMPT_HOOK)(data)) { setTimeout(function () { @@ -51540,11 +51540,11 @@ resolve(swarmProcess); } }; - + swarmProcess.stdout.on('data', handleProcessOutput); swarmProcess.stderr.on('data', handleProcessOutput); //swarmProcess.on('close', () => setTimeout(restart, 2000)); - + var restart = function restart() { return startProcess(swarmSetup).then(resolve).catch(reject); }; @@ -51554,7 +51554,7 @@ var timeout = setTimeout(error, 20000); }); }; - + // Process ~> Promise () // Stops the Swarm process. var stopProcess = function stopProcess(process) { @@ -51565,18 +51565,18 @@ process.removeAllListeners('error'); process.removeAllListeners('exit'); process.kill('SIGINT'); - + var killTimeout = setTimeout(function () { return process.kill('SIGKILL'); }, 8000); - + process.once('close', function () { clearTimeout(killTimeout); resolve(); }); }); }; - + // SwarmSetup -> (SwarmAPI -> Promise ()) -> Promise () // Receives a Swarm configuration object and a callback function. It then // checks if a local Swarm node is running. If no local Swarm is found, it @@ -51602,7 +51602,7 @@ }); }; }; - + // String ~> Promise Bool // Returns true if Swarm is available on `url`. // Perfoms a test upload to determine that. @@ -51616,7 +51616,7 @@ return false; }); }; - + // String -> String ~> Promise Bool // Returns a Promise which is true if that Swarm address is a directory. // Determines that by checking that it (i) is a JSON, (ii) has a .entries. @@ -51632,7 +51632,7 @@ }); }; }; - + // Uncurries a function; used to allow the f(x,y,z) style on exports. var uncurry = function uncurry(f) { return function (a, b, c, d, e) { @@ -51646,23 +51646,23 @@ return p; }; }; - + // () -> Promise Bool // Not sure how to mock Swarm to test it properly. Ideas? var test = function test() { return Promise.resolve(true); }; - + // Uint8Array -> String var toString = function toString(uint8Array) { return bytes.toString(bytes.fromUint8Array(uint8Array)); }; - + // String -> Uint8Array var fromString = function fromString(string) { return bytes.toUint8Array(bytes.fromString(string)); }; - + // String -> SwarmAPI // Fixes the `swarmUrl`, returning an API where you don't have to pass it. var at = function at(swarmUrl) { @@ -51695,7 +51695,7 @@ toString: toString }; }; - + return { at: at, local: local, @@ -51724,10 +51724,10 @@ toString: toString }; }; - + },{}],323:[function(require,module,exports){ var Buffer = require('buffer').Buffer - + module.exports = function (buf) { // If the buffer is backed by a Uint8Array, a faster version will work if (buf instanceof Uint8Array) { @@ -51739,7 +51739,7 @@ return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) } } - + if (Buffer.isBuffer(buf)) { // This is the slow version that will work with any Buffer // implementation (even in old browsers) @@ -51753,50 +51753,50 @@ throw new Error('Argument must be a Buffer') } } - + },{"buffer":84}],324:[function(require,module,exports){ - + exports = module.exports = trim; - + function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } - + exports.left = function(str){ return str.replace(/^\s*/, ''); }; - + exports.right = function(str){ return str.replace(/\s*$/, ''); }; - + },{}],325:[function(require,module,exports){ // Underscore.js 1.8.3 // http://underscorejs.org // (c) 2009-2015 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors // Underscore may be freely distributed under the MIT license. - + (function() { - + // Baseline setup // -------------- - + // Establish the root object, `window` in the browser, or `exports` on the server. var root = this; - + // Save the previous value of the `_` variable. var previousUnderscore = root._; - + // Save bytes in the minified (but not gzipped) version: var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; - + // Create quick reference variables for speed access to core prototypes. var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; - + // All **ECMAScript 5** native function implementations that we hope to use // are declared here. var @@ -51804,17 +51804,17 @@ nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; - + // Naked function reference for surrogate-prototype-swapping. var Ctor = function(){}; - + // Create a safe reference to the Underscore object for use below. var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; - + // Export the Underscore object for **Node.js**, with // backwards-compatibility for the old `require()` API. If we're in // the browser, add `_` as a global object. @@ -51826,10 +51826,10 @@ } else { root._ = _; } - + // Current version. _.VERSION = '1.8.3'; - + // Internal function that returns an efficient (for current engines) version // of the passed-in callback, to be repeatedly applied in other Underscore // functions. @@ -51853,7 +51853,7 @@ return func.apply(context, arguments); }; }; - + // A mostly-internal function to generate callbacks that can be applied // to each element in a collection, returning the desired result — either // identity, an arbitrary callback, a property matcher, or a property accessor. @@ -51866,7 +51866,7 @@ _.iteratee = function(value, context) { return cb(value, context, Infinity); }; - + // An internal function for creating assigner functions. var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { @@ -51884,7 +51884,7 @@ return obj; }; }; - + // An internal function for creating a new object that inherits from another. var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; @@ -51894,13 +51894,13 @@ Ctor.prototype = null; return result; }; - + var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; - + // Helper for collection methods to determine whether a collection // should be iterated as an array or as an object // Related: http://people.mozilla.org/~jorendorff/es6-draft.html#sec-tolength @@ -51911,10 +51911,10 @@ var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; - + // Collection Functions // -------------------- - + // The cornerstone, an `each` implementation, aka `forEach`. // Handles raw objects in addition to array-likes. Treats all // sparse array-likes as if they were dense. @@ -51933,7 +51933,7 @@ } return obj; }; - + // Return the results of applying the iteratee to each element. _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); @@ -51946,7 +51946,7 @@ } return results; }; - + // Create a reducing function iterating left or right. function createReduce(dir) { // Optimized iterator function as using arguments.length @@ -51958,7 +51958,7 @@ } return memo; } - + return function(obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), @@ -51972,14 +51972,14 @@ return iterator(obj, iteratee, memo, keys, index, length); }; } - + // **Reduce** builds up a single result from a list of values, aka `inject`, // or `foldl`. _.reduce = _.foldl = _.inject = createReduce(1); - + // The right-associative version of reduce, also known as `foldr`. _.reduceRight = _.foldr = createReduce(-1); - + // Return the first value which passes a truth test. Aliased as `detect`. _.find = _.detect = function(obj, predicate, context) { var key; @@ -51990,7 +51990,7 @@ } if (key !== void 0 && key !== -1) return obj[key]; }; - + // Return all the elements that pass a truth test. // Aliased as `select`. _.filter = _.select = function(obj, predicate, context) { @@ -52001,12 +52001,12 @@ }); return results; }; - + // Return all the elements for which a truth test fails. _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; - + // Determine whether all of the elements match a truth test. // Aliased as `all`. _.every = _.all = function(obj, predicate, context) { @@ -52019,7 +52019,7 @@ } return true; }; - + // Determine if at least one element in the object matches a truth test. // Aliased as `any`. _.some = _.any = function(obj, predicate, context) { @@ -52032,7 +52032,7 @@ } return false; }; - + // Determine if the array or object contains a given item (using `===`). // Aliased as `includes` and `include`. _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { @@ -52040,7 +52040,7 @@ if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; - + // Invoke a method (with arguments) on every item in a collection. _.invoke = function(obj, method) { var args = slice.call(arguments, 2); @@ -52050,24 +52050,24 @@ return func == null ? func : func.apply(value, args); }); }; - + // Convenience version of a common use case of `map`: fetching a property. _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; - + // Convenience version of a common use case of `filter`: selecting only objects // containing specific `key:value` pairs. _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; - + // Convenience version of a common use case of `find`: getting the first object // containing specific `key:value` pairs. _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; - + // Return the maximum element (or element-based computation). _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, @@ -52092,7 +52092,7 @@ } return result; }; - + // Return the minimum element (or element-based computation). _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, @@ -52117,7 +52117,7 @@ } return result; }; - + // Shuffle a collection, using the modern version of the // [Fisher-Yates shuffle](http://en.wikipedia.org/wiki/Fisher–Yates_shuffle). _.shuffle = function(obj) { @@ -52131,7 +52131,7 @@ } return shuffled; }; - + // Sample **n** random values from a collection. // If **n** is not specified, returns a single random element. // The internal `guard` argument allows it to work with `map`. @@ -52142,7 +52142,7 @@ } return _.shuffle(obj).slice(0, Math.max(0, n)); }; - + // Sort the object's values by a criterion produced by an iteratee. _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); @@ -52162,7 +52162,7 @@ return left.index - right.index; }), 'value'); }; - + // An internal function used for aggregate "group by" operations. var group = function(behavior) { return function(obj, iteratee, context) { @@ -52175,26 +52175,26 @@ return result; }; }; - + // Groups the object's values by a criterion. Pass either a string attribute // to group by, or a function that returns the criterion. _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); - + // Indexes the object's values by a criterion, similar to `groupBy`, but for // when you know that your index values will be unique. _.indexBy = group(function(result, value, key) { result[key] = value; }); - + // Counts instances of an object that group by a certain criterion. Pass // either a string attribute to count by, or a function that returns the // criterion. _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); - + // Safely create a real, live array from anything iterable. _.toArray = function(obj) { if (!obj) return []; @@ -52202,13 +52202,13 @@ if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; - + // Return the number of elements in an object. _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; - + // Split a collection into two arrays: one whose elements all satisfy the given // predicate, and one whose elements all do not satisfy the predicate. _.partition = function(obj, predicate, context) { @@ -52219,10 +52219,10 @@ }); return [pass, fail]; }; - + // Array Functions // --------------- - + // Get the first element of an array. Passing **n** will return the first N // values in the array. Aliased as `head` and `take`. The **guard** check // allows it to work with `_.map`. @@ -52231,14 +52231,14 @@ if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; - + // Returns everything but the last entry of the array. Especially useful on // the arguments object. Passing **n** will return all the values in // the array, excluding the last N. _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; - + // Get the last element of an array. Passing **n** will return the last N // values in the array. _.last = function(array, n, guard) { @@ -52246,19 +52246,19 @@ if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; - + // Returns everything but the first entry of the array. Aliased as `tail` and `drop`. // Especially useful on the arguments object. Passing an **n** will return // the rest N values in the array. _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; - + // Trim out all falsy values from an array. _.compact = function(array) { return _.filter(array, _.identity); }; - + // Internal implementation of a recursive `flatten` function. var flatten = function(input, shallow, strict, startIndex) { var output = [], idx = 0; @@ -52278,17 +52278,17 @@ } return output; }; - + // Flatten out an array, either recursively (by default), or just one level. _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; - + // Return a version of the array that does not contain the specified value(s). _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; - + // Produce a duplicate-free version of the array. If the array has already // been sorted, you have the option of using a faster algorithm. // Aliased as `unique`. @@ -52318,13 +52318,13 @@ } return result; }; - + // Produce an array that contains the union: each distinct element from all of // the passed-in arrays. _.union = function() { return _.uniq(flatten(arguments, true, true)); }; - + // Produce an array that contains every item shared between all the // passed-in arrays. _.intersection = function(array) { @@ -52340,7 +52340,7 @@ } return result; }; - + // Take the difference between one array and a number of other arrays. // Only the elements present in just the first array will remain. _.difference = function(array) { @@ -52349,25 +52349,25 @@ return !_.contains(rest, value); }); }; - + // Zip together multiple lists into a single array -- elements that share // an index go together. _.zip = function() { return _.unzip(arguments); }; - + // Complement of _.zip. Unzip accepts an array of arrays and groups // each array's elements on shared indices _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); - + for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; - + // Converts lists into objects. Pass either a single array of `[key, value]` // pairs, or two parallel arrays of the same length -- one of keys, and one of // the corresponding values. @@ -52382,7 +52382,7 @@ } return result; }; - + // Generator function to create the findIndex and findLastIndex functions function createPredicateIndexFinder(dir) { return function(array, predicate, context) { @@ -52395,11 +52395,11 @@ return -1; }; } - + // Returns the first index on an array-like that passes a predicate test _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); - + // Use a comparator function to figure out the smallest index at which // an object should be inserted so as to maintain order. Uses binary search. _.sortedIndex = function(array, obj, iteratee, context) { @@ -52412,7 +52412,7 @@ } return low; }; - + // Generator function to create the indexOf and lastIndexOf functions function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { @@ -52437,14 +52437,14 @@ return -1; }; } - + // Return the position of the first occurrence of an item in an array, // or -1 if the item is not included in the array. // If the array is large and already in sort order, pass `true` // for **isSorted** to use binary search. _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); - + // Generate an integer Array containing an arithmetic progression. A port of // the native Python `range()` function. See // [the Python documentation](http://docs.python.org/library/functions.html#range). @@ -52454,20 +52454,20 @@ start = 0; } step = step || 1; - + var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); - + for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } - + return range; }; - + // Function (ahem) Functions // ------------------ - + // Determines whether to execute a function as a constructor // or a normal function with the provided arguments var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { @@ -52477,7 +52477,7 @@ if (_.isObject(result)) return result; return self; }; - + // Create a function bound to a given object (assigning `this`, and arguments, // optionally). Delegates to **ECMAScript 5**'s native `Function.bind` if // available. @@ -52490,7 +52490,7 @@ }; return bound; }; - + // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. _ acts // as a placeholder, allowing any combination of arguments to be pre-filled. @@ -52507,7 +52507,7 @@ }; return bound; }; - + // Bind a number of an object's methods to that object. Remaining arguments // are the method names to be bound. Useful for ensuring that all callbacks // defined on an object belong to it. @@ -52520,7 +52520,7 @@ } return obj; }; - + // Memoize an expensive function by storing its results. _.memoize = function(func, hasher) { var memoize = function(key) { @@ -52532,7 +52532,7 @@ memoize.cache = {}; return memoize; }; - + // Delays a function for the given number of milliseconds, and then calls // it with the arguments supplied. _.delay = function(func, wait) { @@ -52541,11 +52541,11 @@ return func.apply(null, args); }, wait); }; - + // Defers a function, scheduling it to run after the current call stack has // cleared. _.defer = _.partial(_.delay, _, 1); - + // Returns a function, that, when invoked, will only be triggered at most once // during a given window of time. Normally, the throttled function will run // as much as it can, without ever going more than once per `wait` duration; @@ -52582,17 +52582,17 @@ return result; }; }; - + // Returns a function, that, as long as it continues to be invoked, will not // be triggered. The function will be called after it stops being called for // N milliseconds. If `immediate` is passed, trigger the function on the // leading edge, instead of the trailing. _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; - + var later = function() { var last = _.now() - timestamp; - + if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { @@ -52603,7 +52603,7 @@ } } }; - + return function() { context = this; args = arguments; @@ -52614,25 +52614,25 @@ result = func.apply(context, args); context = args = null; } - + return result; }; }; - + // Returns the first function passed as an argument to the second, // allowing you to adjust arguments, run code before and after, and // conditionally execute the original function. _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; - + // Returns a negated version of the passed-in predicate. _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; - + // Returns a function that is the composition of a list of functions, each // consuming the return value of the function that follows. _.compose = function() { @@ -52645,7 +52645,7 @@ return result; }; }; - + // Returns a function that will only be executed on and after the Nth call. _.after = function(times, func) { return function() { @@ -52654,7 +52654,7 @@ } }; }; - + // Returns a function that will only be executed up to (but not including) the Nth call. _.before = function(times, func) { var memo; @@ -52666,28 +52666,28 @@ return memo; }; }; - + // Returns a function that will be executed at most one time, no matter how // often you call it. Useful for lazy initialization. _.once = _.partial(_.before, 2); - + // Object Functions // ---------------- - + // Keys in IE < 9 that won't be iterated by `for key in ...` and thus missed. var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; - + function collectNonEnumProps(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; - + // Constructor is a special case. var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); - + while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { @@ -52695,7 +52695,7 @@ } } } - + // Retrieve the names of an object's own properties. // Delegates to **ECMAScript 5**'s native `Object.keys` _.keys = function(obj) { @@ -52707,7 +52707,7 @@ if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; - + // Retrieve all the property names of an object. _.allKeys = function(obj) { if (!_.isObject(obj)) return []; @@ -52717,7 +52717,7 @@ if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; - + // Retrieve the values of an object's properties. _.values = function(obj) { var keys = _.keys(obj); @@ -52728,7 +52728,7 @@ } return values; }; - + // Returns the results of applying the iteratee to each element of the object // In contrast to _.map it returns an object _.mapObject = function(obj, iteratee, context) { @@ -52743,7 +52743,7 @@ } return results; }; - + // Convert an object into a list of `[key, value]` pairs. _.pairs = function(obj) { var keys = _.keys(obj); @@ -52754,7 +52754,7 @@ } return pairs; }; - + // Invert the keys and values of an object. The values must be serializable. _.invert = function(obj) { var result = {}; @@ -52764,7 +52764,7 @@ } return result; }; - + // Return a sorted list of the function names available on the object. // Aliased as `methods` _.functions = _.methods = function(obj) { @@ -52774,14 +52774,14 @@ } return names.sort(); }; - + // Extend a given object with all the properties in passed-in object(s). _.extend = createAssigner(_.allKeys); - + // Assigns a given object with all the own properties in the passed-in object(s) // (https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) _.extendOwn = _.assign = createAssigner(_.keys); - + // Returns the first key on an object that passes a predicate test _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); @@ -52791,7 +52791,7 @@ if (predicate(obj[key], key, obj)) return key; } }; - + // Return a copy of the object only containing the whitelisted properties. _.pick = function(object, oiteratee, context) { var result = {}, obj = object, iteratee, keys; @@ -52811,7 +52811,7 @@ } return result; }; - + // Return a copy of the object without the blacklisted properties. _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { @@ -52824,10 +52824,10 @@ } return _.pick(obj, iteratee, context); }; - + // Fill in a given object with default properties. _.defaults = createAssigner(_.allKeys, true); - + // Creates an object that inherits from the given prototype object. // If additional properties are provided then they will be added to the // created object. @@ -52836,13 +52836,13 @@ if (props) _.extendOwn(result, props); return result; }; - + // Create a (shallow-cloned) duplicate of an object. _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; - + // Invokes interceptor with the obj, and then returns obj. // The primary purpose of this method is to "tap into" a method chain, in // order to perform operations on intermediate results within the chain. @@ -52850,7 +52850,7 @@ interceptor(obj); return obj; }; - + // Returns whether an object has a given set of `key:value` pairs. _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; @@ -52862,8 +52862,8 @@ } return true; }; - - + + // Internal recursive comparison function for `isEqual`. var eq = function(a, b, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. @@ -52898,11 +52898,11 @@ // of `NaN` are not equivalent. return +a === +b; } - + var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; - + // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; @@ -52914,7 +52914,7 @@ } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. - + // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; @@ -52925,11 +52925,11 @@ // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } - + // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); - + // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. @@ -52956,12 +52956,12 @@ bStack.pop(); return true; }; - + // Perform a deep comparison to check if two objects are equal. _.isEqual = function(a, b) { return eq(a, b); }; - + // Is a given array, string, or object empty? // An "empty" object has no enumerable own-properties. _.isEmpty = function(obj) { @@ -52969,31 +52969,31 @@ if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; - + // Is a given value a DOM element? _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; - + // Is a given value an array? // Delegates to ECMA5's native Array.isArray _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; - + // Is a given variable an object? _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; - + // Add some isType methods: isArguments, isFunction, isString, isNumber, isDate, isRegExp, isError. _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); - + // Define a fallback version of the method in browsers (ahem, IE < 9), where // there isn't any inspectable "Arguments" type. if (!_.isArguments(arguments)) { @@ -53001,7 +53001,7 @@ return _.has(obj, 'callee'); }; } - + // Optimize `isFunction` if appropriate. Work around some typeof bugs in old v8, // IE 11 (#1621), and in Safari 8 (#1929). if (typeof /./ != 'function' && typeof Int8Array != 'object') { @@ -53009,71 +53009,71 @@ return typeof obj == 'function' || false; }; } - + // Is a given object a finite number? _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; - + // Is the given value `NaN`? (NaN is the only number which does not equal itself). _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; - + // Is a given value a boolean? _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; - + // Is a given value equal to null? _.isNull = function(obj) { return obj === null; }; - + // Is a given variable undefined? _.isUndefined = function(obj) { return obj === void 0; }; - + // Shortcut function for checking if an object has a given property directly // on itself (in other words, not on a prototype). _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; - + // Utility Functions // ----------------- - + // Run Underscore.js in *noConflict* mode, returning the `_` variable to its // previous owner. Returns a reference to the Underscore object. _.noConflict = function() { root._ = previousUnderscore; return this; }; - + // Keep the identity function around for default iteratees. _.identity = function(value) { return value; }; - + // Predicate-generating functions. Often useful outside of Underscore. _.constant = function(value) { return function() { return value; }; }; - + _.noop = function(){}; - + _.property = property; - + // Generates a function for a given object that returns a given property. _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; - + // Returns a predicate for checking whether an object has a given set of // `key:value` pairs. _.matcher = _.matches = function(attrs) { @@ -53082,7 +53082,7 @@ return _.isMatch(obj, attrs); }; }; - + // Run a function **n** times. _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); @@ -53090,7 +53090,7 @@ for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; - + // Return a random integer between min and max (inclusive). _.random = function(min, max) { if (max == null) { @@ -53099,12 +53099,12 @@ } return min + Math.floor(Math.random() * (max - min + 1)); }; - + // A (possibly faster) way to get the current timestamp as an integer. _.now = Date.now || function() { return new Date().getTime(); }; - + // List of HTML entities for escaping. var escapeMap = { '&': '&', @@ -53115,7 +53115,7 @@ '`': '`' }; var unescapeMap = _.invert(escapeMap); - + // Functions for escaping and unescaping strings to/from HTML interpolation. var createEscaper = function(map) { var escaper = function(match) { @@ -53132,7 +53132,7 @@ }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); - + // If the value of the named `property` is a function then invoke it with the // `object` as context; otherwise, return it. _.result = function(object, property, fallback) { @@ -53142,7 +53142,7 @@ } return _.isFunction(value) ? value.call(object) : value; }; - + // Generate a unique integer id (unique within the entire client session). // Useful for temporary DOM ids. var idCounter = 0; @@ -53150,7 +53150,7 @@ var id = ++idCounter + ''; return prefix ? prefix + id : id; }; - + // By default, Underscore uses ERB-style template delimiters, change the // following template settings to use alternative delimiters. _.templateSettings = { @@ -53158,12 +53158,12 @@ interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; - + // When customizing `templateSettings`, if you don't want to define an // interpolation, evaluation or escaping regex, we need one that is // guaranteed not to match. var noMatch = /(.)^/; - + // Certain characters need to be escaped so that they can be put into a // string literal. var escapes = { @@ -53174,13 +53174,13 @@ '\u2028': 'u2028', '\u2029': 'u2029' }; - + var escaper = /\\|'|\r|\n|\u2028|\u2029/g; - + var escapeChar = function(match) { return '\\' + escapes[match]; }; - + // JavaScript micro-templating, similar to John Resig's implementation. // Underscore templating handles arbitrary delimiters, preserves whitespace, // and correctly escapes quotes within interpolated code. @@ -53188,21 +53188,21 @@ _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); - + // Combine delimiters into one regular expression via alternation. var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); - + // Compile the template source, escaping string literals appropriately. var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; - + if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { @@ -53210,55 +53210,55 @@ } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } - + // Adobe VMs need the match returned to produce the correct offest. return match; }); source += "';\n"; - + // If a variable is not specified, place data values in local scope. if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; - + source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; - + try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } - + var template = function(data) { return render.call(this, data, _); }; - + // Provide the compiled source as a convenience for precompilation. var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; - + return template; }; - + // Add a "chain" function. Start chaining a wrapped Underscore object. _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; - + // OOP // --------------- // If Underscore is called as a function, it returns a wrapped object that // can be used OO-style. This wrapper holds altered versions of all the // underscore functions. Wrapped objects may be chained. - + // Helper function to continue chaining intermediate results. var result = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; - + // Add your own custom functions to the Underscore object. _.mixin = function(obj) { _.each(_.functions(obj), function(name) { @@ -53270,10 +53270,10 @@ }; }); }; - + // Add all of the Underscore functions to the wrapper object. _.mixin(_); - + // Add all mutator Array functions to the wrapper. _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; @@ -53284,7 +53284,7 @@ return result(this, obj); }; }); - + // Add all accessor Array functions to the wrapper. _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; @@ -53292,20 +53292,20 @@ return result(this, method.apply(this._wrapped, arguments)); }; }); - + // Extracts the result from a wrapped and chained object. _.prototype.value = function() { return this._wrapped; }; - + // Provide unwrapping proxy for some methods used in engine operations // such as arithmetic and JSON stringification. _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; - + _.prototype.toString = function() { return '' + this._wrapped; }; - + // AMD registration happens at the end for compatibility with AMD loaders // that may not enforce next-turn semantics on modules. Even though general // practice for AMD registration is to be anonymous, underscore registers @@ -53319,17 +53319,17 @@ }); } }.call(this)); - + },{}],326:[function(require,module,exports){ module.exports = urlSetQuery function urlSetQuery (url, query) { if (query) { // remove optional leading symbols query = query.trim().replace(/^(\?|#|&)/, '') - + // don't append empty query query = query ? ('?' + query) : query - + var parts = url.split(/[\?\#]/) var start = parts[0] if (query && /\:\/\/[^\/]*$/.test(start)) { @@ -53344,7 +53344,7 @@ } return url } - + },{}],327:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // @@ -53366,19 +53366,19 @@ // 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 punycode = require('punycode'); var util = require('./util'); - + exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; - + exports.Url = Url; - + function Url() { this.protocol = null; this.slashes = null; @@ -53393,24 +53393,24 @@ this.path = null; this.href = null; } - + // Reference: RFC 3986, RFC 1808, RFC 2396 - + // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, - + // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, - + // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], - + // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), - + // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. @@ -53446,20 +53446,20 @@ 'file:': true }, querystring = require('querystring'); - + function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; - + var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } - + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } - + // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 @@ -53470,13 +53470,13 @@ slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); - + var rest = url; - + // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); - + if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); @@ -53498,7 +53498,7 @@ return this; } } - + var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; @@ -53506,7 +53506,7 @@ this.protocol = lowerProto; rest = rest.substr(proto.length); } - + // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's @@ -53518,10 +53518,10 @@ this.slashes = true; } } - + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { - + // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // @@ -53533,10 +53533,10 @@ // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c - + // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. - + // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { @@ -53544,7 +53544,7 @@ if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } - + // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; @@ -53556,7 +53556,7 @@ // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } - + // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { @@ -53564,7 +53564,7 @@ rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } - + // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { @@ -53575,22 +53575,22 @@ // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; - + this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); - + // pull out port. this.parseHost(); - + // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; - + // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; - + // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); @@ -53627,14 +53627,14 @@ } } } - + if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } - + if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that @@ -53642,12 +53642,12 @@ // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } - + var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; - + // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { @@ -53657,11 +53657,11 @@ } } } - + // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { - + // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. @@ -53676,8 +53676,8 @@ rest = rest.split(ae).join(esc); } } - - + + // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { @@ -53703,19 +53703,19 @@ this.hostname && !this.pathname) { this.pathname = '/'; } - + //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } - + // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; - + // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. @@ -53726,7 +53726,7 @@ if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } - + Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { @@ -53734,13 +53734,13 @@ auth = auth.replace(/%3A/i, ':'); auth += '@'; } - + var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; - + if (this.host) { host = auth + this.host; } else if (this.hostname) { @@ -53751,17 +53751,17 @@ host += ':' + this.port; } } - + if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } - + var search = this.search || (query && ('?' + query)) || ''; - + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; - + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || @@ -53771,55 +53771,55 @@ } else if (!host) { host = ''; } - + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; - + pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); - + return protocol + host + pathname + search + hash; }; - + function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } - + Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; - + function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } - + Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } - + var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } - + // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; - + // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } - + // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative @@ -53829,17 +53829,17 @@ if (rkey !== 'protocol') result[rkey] = relative[rkey]; } - + //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } - + result.href = result.format(); return result; } - + if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things @@ -53858,7 +53858,7 @@ result.href = result.format(); return result; } - + result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); @@ -53887,7 +53887,7 @@ result.href = result.format(); return result; } - + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || @@ -53899,7 +53899,7 @@ srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; - + // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. @@ -53924,7 +53924,7 @@ } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } - + if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? @@ -53969,7 +53969,7 @@ result.href = result.format(); return result; } - + if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. @@ -53983,7 +53983,7 @@ result.href = result.format(); return result; } - + // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. @@ -53991,7 +53991,7 @@ var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); - + // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; @@ -54007,26 +54007,26 @@ up--; } } - + // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } - + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } - + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } - + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); - + // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : @@ -54041,20 +54041,20 @@ result.host = result.hostname = authInHost.shift(); } } - + mustEndAbs = mustEndAbs || (result.host && srcPath.length); - + if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } - + if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } - + //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + @@ -54065,7 +54065,7 @@ result.href = result.format(); return result; }; - + Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); @@ -54078,10 +54078,10 @@ } if (host) this.hostname = host; }; - + },{"./util":328,"punycode":265,"querystring":269}],328:[function(require,module,exports){ 'use strict'; - + module.exports = { isString: function(arg) { return typeof(arg) === 'string'; @@ -54096,30 +54096,30 @@ return arg == null; } }; - + },{}],329:[function(require,module,exports){ (function (global){ /*! https://mths.be/utf8js v2.0.0 by @mathias */ ;(function(root) { - + // Detect free variables `exports` var freeExports = typeof exports == 'object' && exports; - + // Detect free variable `module` var freeModule = typeof module == 'object' && module && module.exports == freeExports && module; - + // Detect free variable `global`, from Node.js or Browserified code, // and use it as `root` var freeGlobal = typeof global == 'object' && global; if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) { root = freeGlobal; } - + /*--------------------------------------------------------------------------*/ - + var stringFromCharCode = String.fromCharCode; - + // Taken from https://mths.be/punycode function ucs2decode(string) { var output = []; @@ -54146,7 +54146,7 @@ } return output; } - + // Taken from https://mths.be/punycode function ucs2encode(array) { var length = array.length; @@ -54164,7 +54164,7 @@ } return output; } - + function checkScalarValue(codePoint) { if (codePoint >= 0xD800 && codePoint <= 0xDFFF) { throw Error( @@ -54174,11 +54174,11 @@ } } /*--------------------------------------------------------------------------*/ - + function createByte(codePoint, shift) { return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80); } - + function encodeCodePoint(codePoint) { if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence return stringFromCharCode(codePoint); @@ -54200,7 +54200,7 @@ symbol += stringFromCharCode((codePoint & 0x3F) | 0x80); return symbol; } - + function utf8encode(string) { var codePoints = ucs2decode(string); var length = codePoints.length; @@ -54213,49 +54213,49 @@ } return byteString; } - + /*--------------------------------------------------------------------------*/ - + function readContinuationByte() { if (byteIndex >= byteCount) { throw Error('Invalid byte index'); } - + var continuationByte = byteArray[byteIndex] & 0xFF; byteIndex++; - + if ((continuationByte & 0xC0) == 0x80) { return continuationByte & 0x3F; } - + // If we end up here, it’s not a continuation byte throw Error('Invalid continuation byte'); } - + function decodeSymbol() { var byte1; var byte2; var byte3; var byte4; var codePoint; - + if (byteIndex > byteCount) { throw Error('Invalid byte index'); } - + if (byteIndex == byteCount) { return false; } - + // Read first byte byte1 = byteArray[byteIndex] & 0xFF; byteIndex++; - + // 1-byte sequence (no continuation bytes) if ((byte1 & 0x80) == 0) { return byte1; } - + // 2-byte sequence if ((byte1 & 0xE0) == 0xC0) { var byte2 = readContinuationByte(); @@ -54266,7 +54266,7 @@ throw Error('Invalid continuation byte'); } } - + // 3-byte sequence (may include unpaired surrogates) if ((byte1 & 0xF0) == 0xE0) { byte2 = readContinuationByte(); @@ -54279,7 +54279,7 @@ throw Error('Invalid continuation byte'); } } - + // 4-byte sequence if ((byte1 & 0xF8) == 0xF0) { byte2 = readContinuationByte(); @@ -54291,10 +54291,10 @@ return codePoint; } } - + throw Error('Invalid UTF-8 detected'); } - + var byteArray; var byteCount; var byteIndex; @@ -54309,15 +54309,15 @@ } return ucs2encode(codePoints); } - + /*--------------------------------------------------------------------------*/ - + var utf8 = { 'version': '2.0.0', 'encode': utf8encode, 'decode': utf8decode }; - + // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( @@ -54341,19 +54341,19 @@ } else { // in Rhino or a web browser root.utf8 = utf8; } - + }(this)); - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],330:[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. @@ -54371,12 +54371,12 @@ * @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) { @@ -54391,10 +54391,10 @@ } return fn.apply(this, arguments); } - + return deprecated; } - + /** * Checks `localStorage` for boolean values for the given `name`. * @@ -54402,7 +54402,7 @@ * @returns {Boolean} * @api private */ - + function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { @@ -54414,7 +54414,7 @@ if (null == val) return false; return String(val).toLowerCase() === 'true'; } - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],331:[function(require,module,exports){ arguments[4][180][0].apply(exports,arguments) @@ -54447,7 +54447,7 @@ // 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)) { @@ -54457,7 +54457,7 @@ } return objects.join(' '); } - + var i = 1; var args = arguments; var len = args.length; @@ -54486,8 +54486,8 @@ } 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. @@ -54498,11 +54498,11 @@ return exports.deprecate(fn, msg).apply(this, arguments); }; } - + if (process.noDeprecation === true) { return fn; } - + var warned = false; function deprecated() { if (!warned) { @@ -54517,11 +54517,11 @@ } return fn.apply(this, arguments); } - + return deprecated; }; - - + + var debugs = {}; var debugEnviron; exports.debuglog = function(set) { @@ -54541,8 +54541,8 @@ } return debugs[set]; }; - - + + /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. @@ -54576,8 +54576,8 @@ return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; - - + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], @@ -54594,7 +54594,7 @@ 'red' : [31, 39], 'yellow' : [33, 39] }; - + // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', @@ -54607,11 +54607,11 @@ // "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'; @@ -54619,24 +54619,24 @@ 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 @@ -54653,28 +54653,28 @@ } 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)) { @@ -54691,40 +54691,40 @@ 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'); @@ -54732,9 +54732,9 @@ return ctx.stylize('[Object]', 'special'); } } - + ctx.seen.push(value); - + var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); @@ -54743,13 +54743,13 @@ 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'); @@ -54767,13 +54767,13 @@ 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) { @@ -54792,8 +54792,8 @@ }); return output; } - - + + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; @@ -54848,11 +54848,11 @@ name = ctx.stylize(name, 'string'); } } - + return name + ': ' + str; } - - + + function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { @@ -54860,7 +54860,7 @@ 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 ') + @@ -54869,79 +54869,79 @@ ' ' + 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' || @@ -54951,22 +54951,22 @@ 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(); @@ -54975,14 +54975,14 @@ 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. * @@ -54997,11 +54997,11 @@ * @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--) { @@ -55009,15 +55009,15 @@ } 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":332,"_process":257,"inherits":331}],334:[function(require,module,exports){ var indexOf = require('indexof'); - + var Object_keys = function (obj) { if (Object.keys) return Object.keys(obj) else { @@ -55026,14 +55026,14 @@ return res; } }; - + var forEach = function (xs, fn) { if (xs.forEach) return xs.forEach(fn) else for (var i = 0; i < xs.length; i++) { fn(xs[i], i, xs); } }; - + var defineProp = (function() { try { Object.defineProperty({}, '_', {}); @@ -55051,41 +55051,41 @@ }; } }()); - + var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; - + function Context() {} Context.prototype = {}; - + var Script = exports.Script = function NodeScript (code) { if (!(this instanceof Script)) return new Script(code); this.code = code; }; - + Script.prototype.runInContext = function (context) { if (!(context instanceof Context)) { throw new TypeError("needs a 'context' argument."); } - + var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; - + document.body.appendChild(iframe); - + var win = iframe.contentWindow; var wEval = win.eval, wExecScript = win.execScript; - + if (!wEval && wExecScript) { // win.eval() magically appears when this is called in IE: wExecScript.call(win, 'null'); wEval = win.eval; } - + forEach(Object_keys(context), function (key) { win[key] = context[key]; }); @@ -55094,11 +55094,11 @@ win[key] = context[key]; } }); - + var winKeys = Object_keys(win); - + var res = wEval.call(win, this.code); - + forEach(Object_keys(win), function (key) { // Avoid copying circular objects like `top` and `window` by only // updating existing context properties or new properties in the `win` @@ -55107,44 +55107,44 @@ context[key] = win[key]; } }); - + forEach(globals, function (key) { if (!(key in context)) { defineProp(context, key, win[key]); } }); - + document.body.removeChild(iframe); - + return res; }; - + Script.prototype.runInThisContext = function () { return eval(this.code); // maybe... }; - + Script.prototype.runInNewContext = function (context) { var ctx = Script.createContext(context); var res = this.runInContext(ctx); - + forEach(Object_keys(ctx), function (key) { context[key] = ctx[key]; }); - + return res; }; - + forEach(Object_keys(Script.prototype), function (name) { exports[name] = Script[name] = function (code) { var s = Script(code); return s[name].apply(s, [].slice.call(arguments, 1)); }; }); - + exports.createScript = function (code) { return exports.Script(code); }; - + exports.createContext = Script.createContext = function (context) { var copy = new Context(); if(typeof context === 'object') { @@ -55154,21 +55154,21 @@ } return copy; }; - + },{"indexof":179}],335:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -55177,29 +55177,29 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var swarm = require("swarm-js"); - - + + var Bzz = function Bzz(provider) { - + this.givenProvider = Bzz.givenProvider; - + if (provider && provider._requestManager) { provider = provider.currentProvider; } - + // only allow file picker when in browser if(typeof document !== 'undefined') { this.pick = swarm.pick; } - + this.setProvider(provider); }; - + // set default ethereum provider /* jshint ignore:start */ Bzz.givenProvider = null; @@ -55207,7 +55207,7 @@ Bzz.givenProvider = ethereumProvider.bzz; } /* jshint ignore:end */ - + Bzz.prototype.setProvider = function(provider) { // is ethereum provider if(_.isObject(provider) && _.isString(provider.bzz)) { @@ -55217,48 +55217,48 @@ // else if(!_.isString(provider)) { // provider = 'http://swarm-gateways.net'; // default to gateway // } - - + + if(_.isString(provider)) { this.currentProvider = provider; } else { this.currentProvider = null; - + var noProviderError = new Error('No provider set, please set one using bzz.setProvider().'); - + this.download = this.upload = this.isAvailable = function(){ throw noProviderError; }; - + return false; } - + // add functions this.download = swarm.at(provider).download; this.upload = swarm.at(provider).upload; this.isAvailable = swarm.at(provider).isAvailable; - + return true; }; - - + + module.exports = Bzz; - - + + },{"swarm-js":319,"underscore":325}],336:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -55268,9 +55268,9 @@ * @author Marek Kotewicz * @date 2017 */ - + "use strict"; - + module.exports = { ErrorResponse: function (result) { var message = !!result && !!result.error && !!result.error.message ? result.error.message : JSON.stringify(result); @@ -55293,21 +55293,21 @@ return new Error('CONNECTION TIMEOUT: timeout of ' + ms + ' ms achived'); } }; - + },{}],337:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -55317,14 +55317,14 @@ * @author Marek Kotewicz * @date 2017 */ - + "use strict"; - - + + var _ = require('underscore'); var utils = require('web3-utils'); var Iban = require('web3-eth-iban'); - + /** * Should the format output to a big number * @@ -55335,11 +55335,11 @@ var outputBigNumberFormatter = function (number) { return utils.toBN(number).toString(10); }; - + var isPredefinedBlockNumber = function (blockNumber) { return blockNumber === 'latest' || blockNumber === 'pending' || blockNumber === 'earliest'; }; - + var inputDefaultBlockNumberFormatter = function (blockNumber) { if (this && (blockNumber === undefined || blockNumber === null)) { return this.defaultBlock; @@ -55349,7 +55349,7 @@ } return inputBlockNumberFormatter(blockNumber); }; - + var inputBlockNumberFormatter = function (blockNumber) { if (blockNumber === undefined) { return undefined; @@ -55358,7 +55358,7 @@ } return (utils.isHexStrict(blockNumber)) ? ((_.isString(blockNumber)) ? blockNumber.toLowerCase() : blockNumber) : utils.numberToHex(blockNumber); }; - + /** * Formats the input of a transaction and converts all values to HEX * @@ -55367,38 +55367,38 @@ * @returns object */ var _txInputFormatter = function (options){ - + if (options.to) { // it might be contract creation options.to = inputAddressFormatter(options.to); } - + if (options.data && options.input) { throw new Error('You can\'t have "data" and "input" as properties of transactions at the same time, please use either "data" or "input" instead.'); } - + if (!options.data && options.input) { options.data = options.input; delete options.input; } - + if(options.data && !utils.isHex(options.data)) { throw new Error('The data field must be HEX encoded data.'); } - + // allow both if (options.gas || options.gasLimit) { options.gas = options.gas || options.gasLimit; } - + ['gasPrice', 'gas', 'value', 'nonce'].filter(function (key) { return options[key] !== undefined; }).forEach(function(key){ options[key] = utils.numberToHex(options[key]); }); - + return options; }; - + /** * Formats the input of a transaction and converts all values to HEX * @@ -55407,19 +55407,19 @@ * @returns object */ var inputCallFormatter = function (options){ - + options = _txInputFormatter(options); - + var from = options.from || (this ? this.defaultAccount : null); - + if (from) { options.from = inputAddressFormatter(from); } - - + + return options; }; - + /** * Formats the input of a transaction and converts all values to HEX * @@ -55428,23 +55428,23 @@ * @returns object */ var inputTransactionFormatter = function (options) { - + options = _txInputFormatter(options); - + // check from, only if not number, or object if (!_.isNumber(options.from) && !_.isObject(options.from)) { options.from = options.from || (this ? this.defaultAccount : null); - + if (!options.from && !_.isNumber(options.from)) { throw new Error('The send transactions "from" field must be defined!'); } - + options.from = inputAddressFormatter(options.from); } - + return options; }; - + /** * Hex encodes the data passed to eth_sign and personal_sign * @@ -55455,7 +55455,7 @@ var inputSignFormatter = function (data) { return (utils.isHexStrict(data)) ? data : utils.utf8ToHex(data); }; - + /** * Formats the output of a transaction to its proper values * @@ -55472,20 +55472,20 @@ tx.gas = utils.hexToNumber(tx.gas); tx.gasPrice = outputBigNumberFormatter(tx.gasPrice); tx.value = outputBigNumberFormatter(tx.value); - + if(tx.to && utils.isAddress(tx.to)) { // tx.to could be `0x0` or `null` while contract creation tx.to = utils.toChecksumAddress(tx.to); } else { tx.to = null; // set to `null` if invalid address } - + if(tx.from) { tx.from = utils.toChecksumAddress(tx.from); } - + return tx; }; - + /** * Formats the output of a transaction receipt to its proper values * @@ -55497,29 +55497,29 @@ if(typeof receipt !== 'object') { throw new Error('Received receipt is invalid: '+ receipt); } - + if(receipt.blockNumber !== null) receipt.blockNumber = utils.hexToNumber(receipt.blockNumber); if(receipt.transactionIndex !== null) receipt.transactionIndex = utils.hexToNumber(receipt.transactionIndex); receipt.cumulativeGasUsed = utils.hexToNumber(receipt.cumulativeGasUsed); receipt.gasUsed = utils.hexToNumber(receipt.gasUsed); - + if(_.isArray(receipt.logs)) { receipt.logs = receipt.logs.map(outputLogFormatter); } - + if(receipt.contractAddress) { receipt.contractAddress = utils.toChecksumAddress(receipt.contractAddress); } - + if(typeof receipt.status !== 'undefined') { receipt.status = Boolean(parseInt(receipt.status)); } - + return receipt; }; - + /** * Formats the output of a block to its proper values * @@ -55528,7 +55528,7 @@ * @returns {Object} */ var outputBlockFormatter = function(block) { - + // transform to number block.gasLimit = utils.hexToNumber(block.gasLimit); block.gasUsed = utils.hexToNumber(block.gasUsed); @@ -55536,25 +55536,25 @@ block.timestamp = utils.hexToNumber(block.timestamp); if (block.number !== null) block.number = utils.hexToNumber(block.number); - + if(block.difficulty) block.difficulty = outputBigNumberFormatter(block.difficulty); if(block.totalDifficulty) block.totalDifficulty = outputBigNumberFormatter(block.totalDifficulty); - + if (_.isArray(block.transactions)) { block.transactions.forEach(function(item){ if(!_.isString(item)) return outputTransactionFormatter(item); }); } - + if (block.miner) block.miner = utils.toChecksumAddress(block.miner); - + return block; }; - + /** * Formats the input of a log * @@ -55564,42 +55564,42 @@ */ var inputLogFormatter = function(options) { var toTopic = function(value){ - + if(value === null || typeof value === 'undefined') return null; - + value = String(value); - + if(value.indexOf('0x') === 0) return value; else return utils.fromUtf8(value); }; - + if (options.fromBlock) options.fromBlock = inputBlockNumberFormatter(options.fromBlock); - + if (options.toBlock) options.toBlock = inputBlockNumberFormatter(options.toBlock); - - + + // make sure topics, get converted to hex options.topics = options.topics || []; options.topics = options.topics.map(function(topic){ return (_.isArray(topic)) ? topic.map(toTopic) : toTopic(topic); }); - + toTopic = null; - + if (options.address) { options.address = (_.isArray(options.address)) ? options.address.map(function (addr) { return inputAddressFormatter(addr); }) : inputAddressFormatter(options.address); } - + return options; }; - + /** * Formats the output of a log * @@ -55608,7 +55608,7 @@ * @returns {Object} log */ var outputLogFormatter = function(log) { - + // generate a custom log id if(typeof log.blockHash === 'string' && typeof log.transactionHash === 'string' && @@ -55618,21 +55618,21 @@ } else if(!log.id) { log.id = null; } - + if (log.blockNumber !== null) log.blockNumber = utils.hexToNumber(log.blockNumber); if (log.transactionIndex !== null) log.transactionIndex = utils.hexToNumber(log.transactionIndex); if (log.logIndex !== null) log.logIndex = utils.hexToNumber(log.logIndex); - + if (log.address) { log.address = utils.toChecksumAddress(log.address); } - + return log; }; - + /** * Formats the input of a whisper post and converts all values to HEX * @@ -55641,30 +55641,30 @@ * @returns {Object} */ var inputPostFormatter = function(post) { - + // post.payload = utils.toHex(post.payload); - + if (post.ttl) post.ttl = utils.numberToHex(post.ttl); if (post.workToProve) post.workToProve = utils.numberToHex(post.workToProve); if (post.priority) post.priority = utils.numberToHex(post.priority); - + // fallback if (!_.isArray(post.topics)) { post.topics = post.topics ? [post.topics] : []; } - + // format the following options post.topics = post.topics.map(function(topic){ // convert only if not hex return (topic.indexOf('0x') === 0) ? topic : utils.fromUtf8(topic); }); - + return post; }; - + /** * Formats the output of a received post message * @@ -55673,18 +55673,18 @@ * @returns {Object} */ var outputPostFormatter = function(post){ - + post.expiry = utils.hexToNumber(post.expiry); post.sent = utils.hexToNumber(post.sent); post.ttl = utils.hexToNumber(post.ttl); post.workProved = utils.hexToNumber(post.workProved); // post.payloadRaw = post.payload; // post.payload = utils.hexToAscii(post.payload); - + // if (utils.isJson(post.payload)) { // post.payload = JSON.parse(post.payload); // } - + // format the following options if (!post.topics) { post.topics = []; @@ -55692,10 +55692,10 @@ post.topics = post.topics.map(function(topic){ return utils.toUtf8(topic); }); - + return post; }; - + var inputAddressFormatter = function (address) { var iban = new Iban(address); if (iban.isValid() && iban.isDirect()) { @@ -55705,10 +55705,10 @@ } throw new Error('Provided address "'+ address +'" is invalid, the capitalization checksum test failed, or its an indrect IBAN address which can\'t be converted.'); }; - - + + var outputSyncingFormatter = function(result) { - + result.startingBlock = utils.hexToNumber(result.startingBlock); result.currentBlock = utils.hexToNumber(result.currentBlock); result.highestBlock = utils.hexToNumber(result.highestBlock); @@ -55716,10 +55716,10 @@ result.knownStates = utils.hexToNumber(result.knownStates); result.pulledStates = utils.hexToNumber(result.pulledStates); } - + return result; }; - + module.exports = { inputDefaultBlockNumberFormatter: inputDefaultBlockNumberFormatter, inputBlockNumberFormatter: inputBlockNumberFormatter, @@ -55737,22 +55737,22 @@ outputPostFormatter: outputPostFormatter, outputSyncingFormatter: outputSyncingFormatter }; - - + + },{"underscore":325,"web3-eth-iban":368,"web3-utils":403}],338:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -55761,32 +55761,32 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var errors = require('./errors'); var formatters = require('./formatters'); - + module.exports = { errors: errors, formatters: formatters }; - - + + },{"./errors":336,"./formatters":337}],339:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -55796,26 +55796,26 @@ * @author Marek Kotewicz * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var errors = require('web3-core-helpers').errors; var formatters = require('web3-core-helpers').formatters; var utils = require('web3-utils'); var promiEvent = require('web3-core-promievent'); var Subscriptions = require('web3-core-subscriptions').subscriptions; - + var TIMEOUTBLOCK = 50; var POLLINGTIMEOUT = 15 * TIMEOUTBLOCK; // ~average block time (seconds) * TIMEOUTBLOCK var CONFIRMATIONBLOCKS = 24; - + var Method = function Method(options) { - + if(!options.call || !options.name) { throw new Error('When creating a method you need to provide at least the "name" and "call" property.'); } - + this.name = options.name; this.call = options.call; this.params = options.params || 0; @@ -55823,35 +55823,35 @@ this.outputFormatter = options.outputFormatter; this.transformPayload = options.transformPayload; this.extraFormatters = options.extraFormatters; - + this.requestManager = options.requestManager; - + // reference to eth.accounts this.accounts = options.accounts; - + this.defaultBlock = options.defaultBlock || 'latest'; this.defaultAccount = options.defaultAccount || null; }; - + Method.prototype.setRequestManager = function (requestManager, accounts) { this.requestManager = requestManager; - + // reference to eth.accounts if (accounts) { this.accounts = accounts; } - + }; - + Method.prototype.createFunction = function (requestManager, accounts) { var func = this.buildCall(); func.call = this.call; - + this.setRequestManager(requestManager || this.requestManager, accounts || this.accounts); - + return func; }; - + Method.prototype.attachToObject = function (obj) { var func = this.buildCall(); func.call = this.call; @@ -55863,7 +55863,7 @@ obj[name[0]] = func; } }; - + /** * Should be used to determine name of the jsonrpc method based on arguments * @@ -55874,7 +55874,7 @@ Method.prototype.getCall = function (args) { return _.isFunction(this.call) ? this.call(args) : this.call; }; - + /** * Should be used to extract callback from array of arguments. Modifies input param * @@ -55887,7 +55887,7 @@ return args.pop(); // modify the args array! } }; - + /** * Should be called to check if the number of arguments is correct * @@ -55900,7 +55900,7 @@ throw errors.InvalidNumberOfParams(args.length, this.params, this.name); } }; - + /** * Should be called to format input args of method * @@ -55910,17 +55910,17 @@ */ Method.prototype.formatInput = function (args) { var _this = this; - + if (!this.inputFormatter) { return args; } - + return this.inputFormatter.map(function (formatter, index) { // bind this for defaultBlock, and defaultAccount return formatter ? formatter.call(_this, args[index]) : args[index]; }); }; - + /** * Should be called to format output(result) of method * @@ -55930,7 +55930,7 @@ */ Method.prototype.formatOutput = function (result) { var _this = this; - + if(_.isArray(result)) { return result.map(function(res){ return _this.outputFormatter && res ? _this.outputFormatter(res) : res; @@ -55939,7 +55939,7 @@ return this.outputFormatter && result ? this.outputFormatter(result) : result; } }; - + /** * Should create payload from given input args * @@ -55952,21 +55952,21 @@ var callback = this.extractCallback(args); var params = this.formatInput(args); this.validateArgs(params); - + var payload = { method: call, params: params, callback: callback }; - + if (this.transformPayload) { payload = this.transformPayload(payload); } - + return payload; }; - - + + Method.prototype._confirmTransaction = function (defer, result, payload) { var method = this, promiseResolved = false, @@ -55980,7 +55980,7 @@ payload.params[0].data && payload.params[0].from && !payload.params[0].to; - + // add custom send Methods var _ethereumCalls = [ new Method({ @@ -56014,8 +56014,8 @@ mthd.attachToObject(_ethereumCall); mthd.requestManager = method.requestManager; // assign rather than call setRequestManager() }); - - + + // fire "receipt" and confirmation events and resolve after var checkConfirmation = function (existingReceipt, isPolling, err, blockHeader, sub) { if (!err) { @@ -56040,100 +56040,100 @@ if (!receipt || !receipt.blockHash) { throw new Error('Receipt missing or blockHash null'); } - + // apply extra formatters if (method.extraFormatters && method.extraFormatters.receiptFormatter) { receipt = method.extraFormatters.receiptFormatter(receipt); } - + // check if confirmation listener exists if (defer.eventEmitter.listeners('confirmation').length > 0) { - + // If there was an immediately retrieved receipt, it's already // been confirmed by the direct call to checkConfirmation needed // for parity instant-seal if (existingReceipt === undefined || confirmationCount !== 0){ defer.eventEmitter.emit('confirmation', confirmationCount, receipt); } - + canUnsubscribe = false; confirmationCount++; - + if (confirmationCount === CONFIRMATIONBLOCKS + 1) { // add 1 so we account for conf 0 sub.unsubscribe(); defer.eventEmitter.removeAllListeners(); } } - + return receipt; }) // CHECK for CONTRACT DEPLOYMENT .then(function(receipt) { - + if (isContractDeployment && !promiseResolved) { - + if (!receipt.contractAddress) { - + if (canUnsubscribe) { sub.unsubscribe(); promiseResolved = true; } - + utils._fireError(new Error('The transaction receipt didn\'t contain a contract address.'), defer.eventEmitter, defer.reject); return; } - + _ethereumCall.getCode(receipt.contractAddress, function (e, code) { - + if (!code) { return; } - - + + if (code.length > 2) { defer.eventEmitter.emit('receipt', receipt); - + // if contract, return instance instead of receipt if (method.extraFormatters && method.extraFormatters.contractDeployFormatter) { defer.resolve(method.extraFormatters.contractDeployFormatter(receipt)); } else { defer.resolve(receipt); } - + // need to remove listeners, as they aren't removed automatically when succesfull if (canUnsubscribe) { defer.eventEmitter.removeAllListeners(); } - + } else { utils._fireError(new Error('The contract code couldn\'t be stored, please check your gas limit.'), defer.eventEmitter, defer.reject); } - + if (canUnsubscribe) { sub.unsubscribe(); } promiseResolved = true; }); } - + return receipt; }) // CHECK for normal tx check for receipt only .then(function(receipt) { - + if (!isContractDeployment && !promiseResolved) { - + if(!receipt.outOfGas && (!gasProvided || gasProvided !== receipt.gasUsed) && (receipt.status === true || receipt.status === '0x1' || typeof receipt.status === 'undefined')) { defer.eventEmitter.emit('receipt', receipt); defer.resolve(receipt); - + // need to remove listeners, as they aren't removed automatically when succesfull if (canUnsubscribe) { defer.eventEmitter.removeAllListeners(); } - + } else { receiptJSON = JSON.stringify(receipt, null, 2); if (receipt.status === false || receipt.status === '0x0') { @@ -56145,18 +56145,18 @@ defer.eventEmitter, defer.reject); } } - + if (canUnsubscribe) { sub.unsubscribe(); } promiseResolved = true; } - + }) // time out the transaction if not mined after 50 blocks .catch(function () { timeoutCount++; - + // check to see if we are http polling if(!!isPolling) { // polling timeout is different than TIMEOUTBLOCK blocks since we are triggering every second @@ -56173,15 +56173,15 @@ } } }); - - + + } else { sub.unsubscribe(); promiseResolved = true; utils._fireError({message: 'Failed to subscribe to new newBlockHeaders to confirm the transaction receipts.', data: err}, defer.eventEmitter, defer.reject); } }; - + // start watching for confirmation depending on the support features of the provider var startWatching = function(existingReceipt) { // if provider allows PUB/SUB @@ -56191,8 +56191,8 @@ intervalId = setInterval(checkConfirmation.bind(null, existingReceipt, true), 1000); } }.bind(this); - - + + // first check if we already have a confirmed transaction _ethereumCall.getTransactionReceipt(result) .then(function(receipt) { @@ -56202,7 +56202,7 @@ startWatching(receipt); } checkConfirmation(receipt, false); - + } else if (!promiseResolved) { startWatching(); } @@ -56210,39 +56210,39 @@ .catch(function(){ if (!promiseResolved) startWatching(); }); - + }; - - + + var getWallet = function(from, accounts) { var wallet = null; - + // is index given if (_.isNumber(from)) { wallet = accounts.wallet[from]; - + // is account given } else if (_.isObject(from) && from.address && from.privateKey) { wallet = from; - + // search in wallet for address } else { wallet = accounts.wallet[from.toLowerCase()]; } - + return wallet; }; - + Method.prototype.buildCall = function() { var method = this, isSendTx = (method.call === 'eth_sendTransaction' || method.call === 'eth_sendRawTransaction'); // || method.call === 'personal_sendTransaction' - + // actual send function var send = function () { var defer = promiEvent(!isSendTx), payload = method.toPayload(Array.prototype.slice.call(arguments)); - - + + // CALLBACK function var sendTxCallback = function (err, result) { try { @@ -56250,11 +56250,11 @@ } catch(e) { err = e; } - + if (result instanceof Error) { err = result; } - + if (!err) { if (payload.callback) { payload.callback(null, result); @@ -56263,111 +56263,111 @@ if(err.error) { err = err.error; } - + return utils._fireError(err, defer.eventEmitter, defer.reject, payload.callback); } - + // return PROMISE if (!isSendTx) { - + if (!err) { defer.resolve(result); - + } - + // return PROMIEVENT } else { defer.eventEmitter.emit('transactionHash', result); - + method._confirmTransaction(defer, result, payload); } - + }; - + // SENDS the SIGNED SIGNATURE var sendSignedTx = function(sign){ - + var signedPayload = _.extend({}, payload, { method: 'eth_sendRawTransaction', params: [sign.rawTransaction] }); - + method.requestManager.send(signedPayload, sendTxCallback); }; - - + + var sendRequest = function(payload, method) { - + if (method && method.accounts && method.accounts.wallet && method.accounts.wallet.length) { var wallet; - + // ETH_SENDTRANSACTION if (payload.method === 'eth_sendTransaction') { var tx = payload.params[0]; wallet = getWallet((_.isObject(tx)) ? tx.from : null, method.accounts); - - + + // If wallet was found, sign tx, and send using sendRawTransaction if (wallet && wallet.privateKey) { return method.accounts.signTransaction(_.omit(tx, 'from'), wallet.privateKey).then(sendSignedTx); } - + // ETH_SIGN } else if (payload.method === 'eth_sign') { var data = payload.params[1]; wallet = getWallet(payload.params[0], method.accounts); - + // If wallet was found, sign tx, and send using sendRawTransaction if (wallet && wallet.privateKey) { var sign = method.accounts.sign(data, wallet.privateKey); - + if (payload.callback) { payload.callback(null, sign.signature); } - + defer.resolve(sign.signature); return; } - - + + } } - + return method.requestManager.send(payload, sendTxCallback); }; - + // Send the actual transaction if(isSendTx && _.isObject(payload.params[0]) && typeof payload.params[0].gasPrice === 'undefined') { - + var getGasPrice = (new Method({ name: 'getGasPrice', call: 'eth_gasPrice', params: 0 })).createFunction(method.requestManager); - + getGasPrice(function (err, gasPrice) { - + if (gasPrice) { payload.params[0].gasPrice = gasPrice; } sendRequest(payload, method); }); - + } else { sendRequest(payload, method); } - - + + return defer.eventEmitter; }; - + // necessary to attach things to the method send.method = method; // necessary for batch requests send.request = this.request.bind(this); return send; }; - + /** * Should be called to create the pure JSONRPC request which can be used in a batch request * @@ -56379,23 +56379,23 @@ payload.format = this.formatOutput.bind(this); return payload; }; - + module.exports = Method; - + },{"underscore":325,"web3-core-helpers":338,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-utils":403}],340:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56404,12 +56404,12 @@ * @author Fabian Vogelsteller * @date 2016 */ - + "use strict"; - + var EventEmitter = require('eventemitter3'); var Promise = require("any-promise"); - + /** * This function generates a defer promise and adds eventEmitter functionality to it * @@ -56421,7 +56421,7 @@ resolve = arguments[0]; reject = arguments[1]; }); - + if(justPromise) { return { resolve: resolve, @@ -56429,10 +56429,10 @@ eventEmitter: eventEmitter }; } - + // get eventEmitter var emitter = new EventEmitter(); - + // add eventEmitter to the promise eventEmitter._events = emitter._events; eventEmitter.emit = emitter.emit; @@ -56443,36 +56443,36 @@ eventEmitter.addListener = emitter.addListener; eventEmitter.removeListener = emitter.removeListener; eventEmitter.removeAllListeners = emitter.removeAllListeners; - + return { resolve: resolve, reject: reject, eventEmitter: eventEmitter }; }; - + PromiEvent.resolve = function(value) { var promise = PromiEvent(true); promise.resolve(value); return promise.eventEmitter; }; - + module.exports = PromiEvent; - + },{"any-promise":2,"eventemitter3":156}],341:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56481,17 +56481,17 @@ * @author Marek Kotewicz * @date 2015 */ - + "use strict"; - + var Jsonrpc = require('./jsonrpc'); var errors = require('web3-core-helpers').errors; - + var Batch = function (requestManager) { this.requestManager = requestManager; this.requests = []; }; - + /** * Should be called to add create new request to batch request * @@ -56501,7 +56501,7 @@ Batch.prototype.add = function (request) { this.requests.push(request); }; - + /** * Should be called to execute batch request * @@ -56518,11 +56518,11 @@ if (result && result.error) { return requests[index].callback(errors.ErrorResponse(result)); } - + if (!Jsonrpc.isValidResponse(result)) { return requests[index].callback(errors.InvalidResponse(result)); } - + try { requests[index].callback(null, requests[index].format ? requests[index].format(result.result) : result.result); } catch (err) { @@ -56532,24 +56532,24 @@ }); }); }; - + module.exports = Batch; - - + + },{"./jsonrpc":344,"web3-core-helpers":338}],342:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56558,85 +56558,85 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var givenProvider = null; - + // ADD GIVEN PROVIDER /* jshint ignore:start */ var global = window; // EthereumProvider if(typeof global.ethereumProvider !== 'undefined') { givenProvider = global.ethereumProvider; - + // Legacy web3.currentProvider } else if(typeof global.web3 !== 'undefined' && global.web3.currentProvider) { - + if(global.web3.currentProvider.sendAsync) { global.web3.currentProvider.send = global.web3.currentProvider.sendAsync; delete global.web3.currentProvider.sendAsync; } - + // if connection is 'ipcProviderWrapper', add subscription support if(!global.web3.currentProvider.on && global.web3.currentProvider.connection && global.web3.currentProvider.connection.constructor.name === 'ipcProviderWrapper') { - + global.web3.currentProvider.on = function (type, callback) { - + if(typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); - + switch(type){ case 'data': this.connection.on('data', function(data) { var result = ''; - + data = data.toString(); - + try { result = JSON.parse(data); } catch(e) { return callback(new Error('Couldn\'t parse response data'+ data)); } - + // notification if(!result.id && result.method.indexOf('_subscription') !== -1) { callback(null, result); } - + }); break; - + default: this.connection.on(type, callback); break; } }; } - + givenProvider = global.web3.currentProvider; } /* jshint ignore:end */ - - + + module.exports = givenProvider; - + },{}],343:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56645,18 +56645,18 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - - + + var _ = require('underscore'); var errors = require('web3-core-helpers').errors; var Jsonrpc = require('./jsonrpc.js'); var BatchManager = require('./batch.js'); var givenProvider = require('./givenProvider.js'); - - - + + + /** * It's responsible for passing messages to providers * It's also responsible for polling the ethereum node for incoming messages @@ -56666,23 +56666,23 @@ var RequestManager = function RequestManager(provider) { this.provider = null; this.providers = RequestManager.providers; - + this.setProvider(provider); this.subscriptions = {}; }; - - - + + + RequestManager.givenProvider = givenProvider; - + RequestManager.providers = { WebsocketProvider: require('web3-providers-ws'), HttpProvider: require('web3-providers-http'), IpcProvider: require('web3-providers-ipc') }; - - - + + + /** * Should be used to set provider of request manager * @@ -56691,39 +56691,39 @@ */ RequestManager.prototype.setProvider = function (p, net) { var _this = this; - + // autodetect provider if(p && typeof p === 'string' && this.providers) { - + // HTTP if(/^http(s)?:\/\//i.test(p)) { p = new this.providers.HttpProvider(p); - + // WS } else if(/^ws(s)?:\/\//i.test(p)) { p = new this.providers.WebsocketProvider(p); - + // IPC } else if(p && typeof net === 'object' && typeof net.connect === 'function') { p = new this.providers.IpcProvider(p, net); - + } else if(p) { throw new Error('Can\'t autodetect provider for "'+ p +'"'); } } - + // reset the old one before changing, if still connected if(this.provider && this.provider.connected) this.clearSubscriptions(); - - + + this.provider = p || null; - + // listen to incoming notifications if(this.provider && this.provider.on) { this.provider.on('data', function requestManagerNotification(result, deprecatedResult){ result = result || deprecatedResult; // this is for possible old providers, which may had the error first handler - + // check for result.method, to prevent old providers errors to pass as result if(result.method && _this.subscriptions[result.params.subscription] && _this.subscriptions[result.params.subscription].callback) { _this.subscriptions[result.params.subscription].callback(null, result.params.result); @@ -56738,8 +56738,8 @@ // } } }; - - + + /** * Should be used to asynchronously send request * @@ -56749,31 +56749,31 @@ */ RequestManager.prototype.send = function (data, callback) { callback = callback || function(){}; - + if (!this.provider) { return callback(errors.InvalidProvider()); } - + var payload = Jsonrpc.toPayload(data.method, data.params); this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, result) { if(result && result.id && payload.id !== result.id) return callback(new Error('Wrong response id "'+ result.id +'" (expected: "'+ payload.id +'") in '+ JSON.stringify(payload))); - + if (err) { return callback(err); } - + if (result && result.error) { return callback(errors.ErrorResponse(result)); } - + if (!Jsonrpc.isValidResponse(result)) { return callback(errors.InvalidResponse(result)); } - + callback(null, result.result); }); }; - + /** * Should be called to asynchronously send batch request * @@ -56785,22 +56785,22 @@ if (!this.provider) { return callback(errors.InvalidProvider()); } - + var payload = Jsonrpc.toBatchPayload(data); this.provider[this.provider.sendAsync ? 'sendAsync' : 'send'](payload, function (err, results) { if (err) { return callback(err); } - + if (!_.isArray(results)) { return callback(errors.InvalidResponse(results)); } - + callback(null, results); }); }; - - + + /** * Waits for notifications * @@ -56817,12 +56817,12 @@ type: type, name: name }; - + } else { throw new Error('The provider doesn\'t support subscriptions: '+ this.provider.constructor.name); } }; - + /** * Waits for notifications * @@ -56832,19 +56832,19 @@ */ RequestManager.prototype.removeSubscription = function (id, callback) { var _this = this; - + if(this.subscriptions[id]) { - + this.send({ method: this.subscriptions[id].type + '_unsubscribe', params: [id] }, callback); - + // remove subscription delete _this.subscriptions[id]; } }; - + /** * Should be called to reset the subscriptions * @@ -56852,39 +56852,39 @@ */ RequestManager.prototype.clearSubscriptions = function (keepIsSyncing) { var _this = this; - - + + // uninstall all subscriptions Object.keys(this.subscriptions).forEach(function(id){ if(!keepIsSyncing || _this.subscriptions[id].name !== 'syncing') _this.removeSubscription(id); }); - - + + // reset notification callbacks etc. if(this.provider.reset) this.provider.reset(); }; - + module.exports = { Manager: RequestManager, BatchManager: BatchManager }; - + },{"./batch.js":341,"./givenProvider.js":342,"./jsonrpc.js":344,"underscore":325,"web3-core-helpers":338,"web3-providers-http":398,"web3-providers-ipc":399,"web3-providers-ws":400}],344:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56895,14 +56895,14 @@ * Aaron Kumavis * @date 2015 */ - + "use strict"; - + // Initialize Jsonrpc as a simple object with utility functions. var Jsonrpc = { messageId: 0 }; - + /** * Should be called to valid json create payload object * @@ -56915,10 +56915,10 @@ if (!method) { throw new Error('JSONRPC method should be specified for params: "'+ JSON.stringify(params) +'"!'); } - + // advance message ID Jsonrpc.messageId++; - + return { jsonrpc: '2.0', id: Jsonrpc.messageId, @@ -56926,7 +56926,7 @@ params: params || [] }; }; - + /** * Should be called to check if jsonrpc response is valid * @@ -56936,7 +56936,7 @@ */ Jsonrpc.isValidResponse = function (response) { return Array.isArray(response) ? response.every(validateSingleMessage) : validateSingleMessage(response); - + function validateSingleMessage(message){ return !!message && !message.error && @@ -56945,7 +56945,7 @@ message.result !== undefined; // only undefined is not valid json object } }; - + /** * Should be called to create batch payload object * @@ -56958,24 +56958,24 @@ return Jsonrpc.toPayload(message.method, message.params); }); }; - + module.exports = Jsonrpc; - - + + },{}],345:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -56984,25 +56984,25 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var Subscription = require('./subscription.js'); - - + + var Subscriptions = function Subscriptions(options) { this.name = options.name; this.type = options.type; this.subscriptions = options.subscriptions || {}; this.requestManager = null; }; - - + + Subscriptions.prototype.setRequestManager = function (rm) { this.requestManager = rm; }; - - + + Subscriptions.prototype.attachToObject = function (obj) { var func = this.buildCall(); var name = this.name.split('.'); @@ -57013,46 +57013,46 @@ obj[name[0]] = func; } }; - - + + Subscriptions.prototype.buildCall = function() { var _this = this; - + return function(){ if(!_this.subscriptions[arguments[0]]) { console.warn('Subscription '+ JSON.stringify(arguments[0]) +' doesn\'t exist. Subscribing anyway.'); } - + var subscription = new Subscription({ subscription: _this.subscriptions[arguments[0]], requestManager: _this.requestManager, type: _this.type }); - + return subscription.subscribe.apply(subscription, arguments); }; }; - - + + module.exports = { subscriptions: Subscriptions, subscription: Subscription }; - + },{"./subscription.js":346}],346:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -57061,33 +57061,33 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var errors = require('web3-core-helpers').errors; var EventEmitter = require('eventemitter3'); - + function Subscription(options) { EventEmitter.call(this); - + this.id = null; this.callback = _.identity; this.arguments = null; this._reconnectIntervalId = null; - + this.options = { subscription: options.subscription, type: options.type, requestManager: options.requestManager }; } - + // INHERIT Subscription.prototype = Object.create(EventEmitter.prototype); Subscription.prototype.constructor = Subscription; - - + + /** * Should be used to extract callback from array of arguments. Modifies input param * @@ -57095,13 +57095,13 @@ * @param {Array} arguments * @return {Function|Null} callback, if exists */ - + Subscription.prototype._extractCallback = function (args) { if (_.isFunction(args[args.length - 1])) { return args.pop(); // modify the args array! } }; - + /** * Should be called to check if the number of arguments is correct * @@ -57109,21 +57109,21 @@ * @param {Array} arguments * @throws {Error} if it is not */ - + Subscription.prototype._validateArgs = function (args) { var subscription = this.options.subscription; - + if(!subscription) subscription = {}; - + if(!subscription.params) subscription.params = 0; - + if (args.length !== subscription.params) { throw errors.InvalidNumberOfParams(args.length, subscription.params + 1, args[0]); } }; - + /** * Should be called to format input args of method * @@ -57131,25 +57131,25 @@ * @param {Array} * @return {Array} */ - + Subscription.prototype._formatInput = function (args) { var subscription = this.options.subscription; - + if (!subscription) { return args; } - + if (!subscription.inputFormatter) { return args; } - + var formattedArgs = subscription.inputFormatter.map(function (formatter, index) { return formatter ? formatter(args[index]) : args[index]; }); - + return formattedArgs; }; - + /** * Should be called to format output(result) of method * @@ -57157,13 +57157,13 @@ * @param {Object} * @return {Object} */ - + Subscription.prototype._formatOutput = function (result) { var subscription = this.options.subscription; - + return (subscription && subscription.outputFormatter && result) ? subscription.outputFormatter(result) : result; }; - + /** * Should create payload from given input args * @@ -57174,38 +57174,38 @@ Subscription.prototype._toPayload = function (args) { var params = []; this.callback = this._extractCallback(args) || _.identity; - + if (!this.subscriptionMethod) { this.subscriptionMethod = args.shift(); - + // replace subscription with given name if (this.options.subscription.subscriptionName) { this.subscriptionMethod = this.options.subscription.subscriptionName; } } - + if (!this.arguments) { this.arguments = this._formatInput(args); this._validateArgs(this.arguments); args = []; // make empty after validation - + } - + // re-add subscriptionName params.push(this.subscriptionMethod); params = params.concat(this.arguments); - - + + if (args.length) { throw new Error('Only a callback is allowed as parameter on an already instantiated subscription.'); } - + return { method: this.options.type + '_subscribe', params: params }; }; - + /** * Unsubscribes and clears callbacks * @@ -57218,7 +57218,7 @@ this.removeAllListeners(); clearInterval(this._reconnectIntervalId); }; - + /** * Subscribes and watches for changes * @@ -57231,18 +57231,18 @@ var _this = this; var args = Array.prototype.slice.call(arguments); var payload = this._toPayload(args); - + if(!payload) { return this; } - + if(!this.options.requestManager.provider) { var err1 = new Error('No provider set.'); this.callback(err1, null, this); this.emit('error', err1); return this; } - + // throw error, if provider doesnt support subscriptions if(!this.options.requestManager.provider.on) { var err2 = new Error('The current provider doesn\'t support subscriptions: '+ this.options.requestManager.provider.constructor.name); @@ -57250,15 +57250,15 @@ this.emit('error', err2); return this; } - + // if id is there unsubscribe first if (this.id) { this.unsubscribe(); } - + // store the params in the options object this.options.params = payload.params[1]; - + // get past logs, if fromBlock is available if(payload.params[0] === 'logs' && _.isObject(payload.params[1]) && payload.params[1].hasOwnProperty('fromBlock') && isFinite(payload.params[1].fromBlock)) { // send the subscription request @@ -57272,50 +57272,50 @@ _this.callback(null, output, _this); _this.emit('data', output); }); - + // TODO subscribe here? after the past logs? - + } else { _this.callback(err, null, _this); _this.emit('error', err); } }); } - + // create subscription // TODO move to separate function? so that past logs can go first? - + if(typeof payload.params[1] === 'object') delete payload.params[1].fromBlock; - + this.options.requestManager.send(payload, function (err, result) { if(!err && result) { _this.id = result; - + // call callback on notifications _this.options.requestManager.addSubscription(_this.id, payload.params[0] , _this.options.type, function(err, result) { - + if (!err) { if (!_.isArray(result)) { result = [result]; } - + result.forEach(function(resultItem) { var output = _this._formatOutput(resultItem); - + if (_.isFunction(_this.options.subscription.subscriptionHandler)) { return _this.options.subscription.subscriptionHandler.call(_this, output); } else { _this.emit('data', output); } - + // call the callback, last so that unsubscribe there won't affect the emit above _this.callback(null, output, _this); }); } else { // unsubscribe, but keep listeners _this.options.requestManager.removeSubscription(_this.id); - + // re-subscribe, if connection fails if(_this.options.requestManager.provider.once) { _this._reconnectIntervalId = setInterval(function () { @@ -57324,14 +57324,14 @@ _this.options.requestManager.provider.reconnect(); } }, 500); - + _this.options.requestManager.provider.once('connect', function () { clearInterval(_this._reconnectIntervalId); _this.subscribe(_this.callback); }); } _this.emit('error', err); - + // call the callback, last so that unsubscribe there won't affect the emit above _this.callback(err, null, _this); } @@ -57341,27 +57341,27 @@ _this.emit('error', err); } }); - + // return an object to cancel the subscription return this; }; - + module.exports = Subscription; - + },{"eventemitter3":156,"underscore":325,"web3-core-helpers":338}],347:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -57370,19 +57370,19 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - - + + var formatters = require('web3-core-helpers').formatters; var Method = require('web3-core-method'); var utils = require('web3-utils'); - - + + var extend = function (pckg) { /* jshint maxcomplexity:5 */ var ex = function (extension) { - + var extendedObject; if (extension.property) { if (!pckg[extension.property]) { @@ -57392,47 +57392,47 @@ } else { extendedObject = pckg; } - + if (extension.methods) { extension.methods.forEach(function (method) { if(!(method instanceof Method)) { method = new Method(method); } - + method.attachToObject(extendedObject); method.setRequestManager(pckg._requestManager); }); } - + return pckg; }; - + ex.formatters = formatters; ex.utils = utils; ex.Method = Method; - + return ex; }; - - - + + + module.exports = extend; - - + + },{"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],348:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -57441,22 +57441,22 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - - + + var requestManager = require('web3-core-requestmanager'); var extend = require('./extend.js'); - + module.exports = { packageInit: function (pkg, args) { args = Array.prototype.slice.call(args); - + if (!pkg) { throw new Error('You need to instantiate using the "new" keyword.'); } - - + + // make property of pkg._provider, which can properly set providers Object.defineProperty(pkg, 'currentProvider', { get: function () { @@ -57468,23 +57468,23 @@ enumerable: true, configurable: true }); - + // inherit from web3 umbrella package if (args[0] && args[0]._requestManager) { pkg._requestManager = new requestManager.Manager(args[0].currentProvider); - + // set requestmanager on package } else { pkg._requestManager = new requestManager.Manager(); pkg._requestManager.setProvider(args[0], args[1]); } - + // add givenProvider pkg.givenProvider = requestManager.Manager.givenProvider; pkg.providers = requestManager.Manager.providers; - + pkg._provider = pkg._requestManager.provider; - + // add SETPROVIDER function (don't overwrite if already existing) if (!pkg.setProvider) { pkg.setProvider = function (provider, net) { @@ -57493,10 +57493,10 @@ return true; }; } - + // attach batch request creation pkg.BatchRequest = requestManager.BatchManager.bind(null, pkg._requestManager); - + // attach extend function pkg.extend = extend(pkg); }, @@ -57505,22 +57505,22 @@ pkg.providers = requestManager.Manager.providers; } }; - - + + },{"./extend.js":347,"web3-core-requestmanager":343}],349:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -57530,10 +57530,10 @@ * @author Fabian Vogelsteller * @date 2018 */ - + var _ = require('underscore'); var utils = require('web3-utils'); - + var EthersAbi = require('ethers/utils/abi-coder').AbiCoder; var ethersAbiCoder = new EthersAbi(function (type, value) { if (type.match(/^u?int/) && !_.isArray(value) && (!_.isObject(value) || value.constructor.name !== 'BN')) { @@ -57541,17 +57541,17 @@ } return value; }); - + // result method function Result() { } - + /** * ABICoder prototype should be used to encode/decode solidity params of any type */ var ABICoder = function () { }; - + /** * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. * @@ -57563,10 +57563,10 @@ if (_.isObject(functionName)) { functionName = utils._jsonInterfaceMethodToString(functionName); } - + return utils.sha3(functionName).slice(0, 10); }; - + /** * Encodes the function name to its ABI representation, which are the first 4 bytes of the sha3 of the function name including types. * @@ -57578,10 +57578,10 @@ if (_.isObject(functionName)) { functionName = utils._jsonInterfaceMethodToString(functionName); } - + return utils.sha3(functionName); }; - + /** * Should be used to encode plain param * @@ -57593,7 +57593,7 @@ ABICoder.prototype.encodeParameter = function (type, param) { return this.encodeParameters([type], [param]); }; - + /** * Should be used to encode list of params * @@ -57605,7 +57605,7 @@ ABICoder.prototype.encodeParameters = function (types, params) { return ethersAbiCoder.encode(this.mapTypes(types), params); }; - + /** * Map types if simplified format is used * @@ -57627,16 +57627,16 @@ } ) ); - + return; } - + mappedTypes.push(type); }); - + return mappedTypes; }; - + /** * Check if type is simplified struct format * @@ -57647,7 +57647,7 @@ ABICoder.prototype.isSimplifiedStructFormat = function (type) { return typeof type === 'object' && typeof type.components === 'undefined' && typeof type.name === 'undefined'; }; - + /** * Maps the correct tuple type and name when the simplified format in encode/decodeParameter is used * @@ -57657,15 +57657,15 @@ */ ABICoder.prototype.mapStructNameAndType = function (structName) { var type = 'tuple'; - + if (structName.indexOf('[]') > -1) { type = 'tuple[]'; structName = structName.slice(0, -2); } - + return {type: type, name: structName}; }; - + /** * Maps the simplified format in to the expected format of the ABICoder * @@ -57686,19 +57686,19 @@ } ) ); - + return; } - + components.push({ name: key, type: struct[key] }); }); - + return components; }; - + /** * Encodes a function call from its json interface and parameters. * @@ -57710,7 +57710,7 @@ ABICoder.prototype.encodeFunctionCall = function (jsonInterface, params) { return this.encodeFunctionSignature(jsonInterface) + this.encodeParameters(jsonInterface.inputs, params).replace('0x', ''); }; - + /** * Should be used to decode bytes to plain param * @@ -57722,7 +57722,7 @@ ABICoder.prototype.decodeParameter = function (type, bytes) { return this.decodeParameters([type], bytes)[0]; }; - + /** * Should be used to decode list of params * @@ -57735,27 +57735,27 @@ if (!bytes || bytes === '0x' || bytes === '0X') { throw new Error('Returned values aren\'t valid, did it run Out of Gas?'); } - + var res = ethersAbiCoder.decode(this.mapTypes(outputs), '0x' + bytes.replace(/0x/i, '')); var returnValue = new Result(); returnValue.__length__ = 0; - + outputs.forEach(function (output, i) { var decodedValue = res[returnValue.__length__]; decodedValue = (decodedValue === '0x') ? null : decodedValue; - + returnValue[i] = decodedValue; - + if (_.isObject(output) && output.name) { returnValue[output.name] = decodedValue; } - + returnValue.__length__++; }); - + return returnValue; }; - + /** * Decodes events non- and indexed parameters. * @@ -57768,15 +57768,15 @@ ABICoder.prototype.decodeLog = function (inputs, data, topics) { var _this = this; topics = _.isArray(topics) ? topics : [topics]; - + data = data || ''; - + var notIndexedInputs = []; var indexedParams = []; var topicCount = 0; - + // TODO check for anonymous logs? - + inputs.forEach(function (input, i) { if (input.indexed) { indexedParams[i] = (['bool', 'int', 'uint', 'address', 'fixed', 'ufixed'].find(function (staticType) { @@ -57787,60 +57787,60 @@ notIndexedInputs[i] = input; } }); - - + + var nonIndexedData = data; var notIndexedParams = (nonIndexedData) ? this.decodeParameters(notIndexedInputs, nonIndexedData) : []; - + var returnValue = new Result(); returnValue.__length__ = 0; - - + + inputs.forEach(function (res, i) { returnValue[i] = (res.type === 'string') ? '' : null; - + if (typeof notIndexedParams[i] !== 'undefined') { returnValue[i] = notIndexedParams[i]; } if (typeof indexedParams[i] !== 'undefined') { returnValue[i] = indexedParams[i]; } - + if (res.name) { returnValue[res.name] = returnValue[i]; } - + returnValue.__length__++; }); - + return returnValue; }; - + var coder = new ABICoder(); - + module.exports = coder; - + },{"ethers/utils/abi-coder":143,"underscore":325,"web3-utils":403}],350:[function(require,module,exports){ (function (Buffer){ var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); - + var Bytes = require("./bytes"); var Nat = require("./nat"); var elliptic = require("elliptic"); var rlp = require("./rlp"); var secp256k1 = new elliptic.ec("secp256k1"); // eslint-disable-line - + var _require = require("./hash"), keccak256 = _require.keccak256, keccak256s = _require.keccak256s; - + var create = function create(entropy) { var innerHex = keccak256(Bytes.concat(Bytes.random(32), entropy || Bytes.random(32))); var middleHex = Bytes.concat(Bytes.concat(Bytes.random(32), innerHex), Bytes.random(32)); var outerHex = keccak256(middleHex); return fromPrivate(outerHex); }; - + var toChecksum = function toChecksum(address) { var addressHash = keccak256s(address.slice(2)); var checksumAddress = "0x"; @@ -57848,7 +57848,7 @@ checksumAddress += parseInt(addressHash[i + 2], 16) > 7 ? address[i + 2].toUpperCase() : address[i + 2]; }return checksumAddress; }; - + var fromPrivate = function fromPrivate(privateKey) { var buffer = new Buffer(privateKey.slice(2), "hex"); var ecKey = secp256k1.keyFromPrivate(buffer); @@ -57860,29 +57860,29 @@ privateKey: privateKey }; }; - + var encodeSignature = function encodeSignature(_ref) { var _ref2 = _slicedToArray(_ref, 3), v = _ref2[0], r = Bytes.pad(32, _ref2[1]), s = Bytes.pad(32, _ref2[2]); - + return Bytes.flatten([r, s, v]); }; - + var decodeSignature = function decodeSignature(hex) { return [Bytes.slice(64, Bytes.length(hex), hex), Bytes.slice(0, 32, hex), Bytes.slice(32, 64, hex)]; }; - + var makeSigner = function makeSigner(addToV) { return function (hash, privateKey) { var signature = secp256k1.keyFromPrivate(new Buffer(privateKey.slice(2), "hex")).sign(new Buffer(hash.slice(2), "hex"), { canonical: true }); return encodeSignature([Nat.fromString(Bytes.fromNumber(addToV + signature.recoveryParam)), Bytes.pad(32, Bytes.fromNat("0x" + signature.r.toString(16))), Bytes.pad(32, Bytes.fromNat("0x" + signature.s.toString(16)))]); }; }; - + var sign = makeSigner(27); // v=27|28 instead of 0|1... - + var recover = function recover(hash, signature) { var vals = decodeSignature(signature); var vrs = { v: Bytes.toNumber(vals[0]), r: vals[1].slice(2), s: vals[2].slice(2) }; @@ -57892,7 +57892,7 @@ var address = toChecksum("0x" + publicHash.slice(-40)); return address; }; - + module.exports = { create: create, toChecksum: toChecksum, @@ -57913,55 +57913,55 @@ },{"dup":134}],354:[function(require,module,exports){ var BN = require("bn.js"); var Bytes = require("./bytes"); - + var fromBN = function fromBN(bn) { return "0x" + bn.toString("hex"); }; - + var toBN = function toBN(str) { return new BN(str.slice(2), 16); }; - + var fromString = function fromString(str) { var bn = "0x" + (str.slice(0, 2) === "0x" ? new BN(str.slice(2), 16) : new BN(str, 10)).toString("hex"); return bn === "0x0" ? "0x" : bn; }; - + var toEther = function toEther(wei) { return toNumber(div(wei, fromString("10000000000"))) / 100000000; }; - + var fromEther = function fromEther(eth) { return mul(fromNumber(Math.floor(eth * 100000000)), fromString("10000000000")); }; - + var toString = function toString(a) { return toBN(a).toString(10); }; - + var fromNumber = function fromNumber(a) { return typeof a === "string" ? /^0x/.test(a) ? a : "0x" + a : "0x" + new BN(a).toString("hex"); }; - + var toNumber = function toNumber(a) { return toBN(a).toNumber(); }; - + var toUint256 = function toUint256(a) { return Bytes.pad(32, a); }; - + var bin = function bin(method) { return function (a, b) { return fromBN(toBN(a)[method](toBN(b))); }; }; - + var add = bin("add"); var mul = bin("mul"); var div = bin("div"); var sub = bin("sub"); - + module.exports = { toString: toString, fromString: fromString, @@ -57985,20 +57985,20 @@ // | 184 to 191 | HEX(length_of_length_of_leaf + 128 + 55) + HEX(length_of_leaf) + HEX(leaf) | // | 192 to 247 | HEX(length_of_node + 192) + HEX(node) | // | 248 to 255 | HEX(length_of_length_of_node + 128 + 55) + HEX(length_of_node) + HEX(node) | - + var encode = function encode(tree) { var padEven = function padEven(str) { return str.length % 2 === 0 ? str : "0" + str; }; - + var uint = function uint(num) { return padEven(num.toString(16)); }; - + var length = function length(len, add) { return len < 56 ? uint(add + len) : uint(add + uint(len).length / 2 + 55) + uint(len); }; - + var dataTree = function dataTree(tree) { if (typeof tree === "string") { var hex = tree.slice(2); @@ -58010,29 +58010,29 @@ return _pre + _hex; } }; - + return "0x" + dataTree(tree); }; - + var decode = function decode(hex) { var i = 2; - + var parseTree = function parseTree() { if (i >= hex.length) throw ""; var head = hex.slice(i, i + 2); return head < "80" ? (i += 2, "0x" + head) : head < "c0" ? parseHex() : parseList(); }; - + var parseLength = function parseLength() { var len = parseInt(hex.slice(i, i += 2), 16) % 64; return len < 56 ? len : parseInt(hex.slice(i, i += (len - 55) * 2), 16); }; - + var parseHex = function parseHex() { var len = parseLength(); return "0x" + hex.slice(i, i += len * 2); }; - + var parseList = function parseList() { var lim = parseLength() * 2 + i; var list = []; @@ -58040,20 +58040,20 @@ list.push(parseTree()); }return list; }; - + try { return parseTree(); } catch (e) { return []; } }; - + module.exports = { encode: encode, decode: decode }; },{}],356:[function(require,module,exports){ (function (global){ - + var rng; - + if (global.crypto && crypto.getRandomValues) { // WHATWG crypto-based RNG - http://wiki.whatwg.org/wiki/Crypto // Moderately fast, high quality @@ -58063,7 +58063,7 @@ return _rnds8; }; } - + if (!rng) { // Math.random()-based (RNG) // @@ -58075,26 +58075,26 @@ if ((i & 0x03) === 0) r = Math.random() * 0x100000000; _rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; } - + return _rnds; }; } - + module.exports = rng; - - + + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],357:[function(require,module,exports){ // uuid.js // // Copyright (c) 2010-2012 Robert Kieffer // MIT License - http://opensource.org/licenses/mit-license.php - + // Unique ID creation requires a high quality random # generator. We feature // detect to determine the best RNG source, normalizing to a function that // returns 128-bits of randomness, since that's what's usually required var _rng = require('./rng'); - + // Maps for number <-> hex string conversion var _byteToHex = []; var _hexToByte = {}; @@ -58102,26 +58102,26 @@ _byteToHex[i] = (i + 0x100).toString(16).substr(1); _hexToByte[_byteToHex[i]] = i; } - + // **`parse()` - Parse a UUID into it's component bytes** function parse(s, buf, offset) { var i = (buf && offset) || 0, ii = 0; - + buf = buf || []; s.toLowerCase().replace(/[0-9a-f]{2}/g, function(oct) { if (ii < 16) { // Don't overflow! buf[i + ii++] = _hexToByte[oct]; } }); - + // Zero out remaining bytes if string was short while (ii < 16) { buf[i + ii++] = 0; } - + return buf; } - + // **`unparse()` - Convert UUID byte array (ala parse()) into a string** function unparse(buf, offset) { var i = offset || 0, bth = _byteToHex; @@ -58134,156 +58134,156 @@ bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]] + bth[buf[i++]]; } - + // **`v1()` - Generate time-based UUID** // // Inspired by https://github.com/LiosK/UUID.js // and http://docs.python.org/library/uuid.html - + // random #'s we need to init node and clockseq var _seedBytes = _rng(); - + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) var _nodeId = [ _seedBytes[0] | 0x01, _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] ]; - + // Per 4.2.2, randomize (14 bit) clockseq var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; - + // Previous uuid creation time var _lastMSecs = 0, _lastNSecs = 0; - + // See https://github.com/broofa/node-uuid for API details function v1(options, buf, offset) { var i = buf && offset || 0; var b = buf || []; - + options = options || {}; - + var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; - + // UUID timestamps are 100 nano-second units since the Gregorian epoch, // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); - + // Per 4.2.1.2, use count of uuid's generated during the current clock // cycle to simulate higher resolution clock var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - + // Time since last uuid creation (in msecs) var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; - + // Per 4.2.1.2, Bump clockseq on clock regression if (dt < 0 && options.clockseq === undefined) { clockseq = clockseq + 1 & 0x3fff; } - + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new // time interval if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { nsecs = 0; } - + // Per 4.2.1.2 Throw error if too many uuids are requested if (nsecs >= 10000) { throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); } - + _lastMSecs = msecs; _lastNSecs = nsecs; _clockseq = clockseq; - + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch msecs += 12219292800000; - + // `time_low` var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; b[i++] = tl >>> 24 & 0xff; b[i++] = tl >>> 16 & 0xff; b[i++] = tl >>> 8 & 0xff; b[i++] = tl & 0xff; - + // `time_mid` var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; b[i++] = tmh >>> 8 & 0xff; b[i++] = tmh & 0xff; - + // `time_high_and_version` b[i++] = tmh >>> 24 & 0xf | 0x10; // include version b[i++] = tmh >>> 16 & 0xff; - + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) b[i++] = clockseq >>> 8 | 0x80; - + // `clock_seq_low` b[i++] = clockseq & 0xff; - + // `node` var node = options.node || _nodeId; for (var n = 0; n < 6; n++) { b[i + n] = node[n]; } - + return buf ? buf : unparse(b); } - + // **`v4()` - Generate random UUID** - + // See https://github.com/broofa/node-uuid for API details function v4(options, buf, offset) { // Deprecated - 'format' argument, as supported in v1.2 var i = buf && offset || 0; - + if (typeof(options) == 'string') { buf = options == 'binary' ? new Array(16) : null; options = null; } options = options || {}; - + var rnds = options.random || (options.rng || _rng)(); - + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` rnds[6] = (rnds[6] & 0x0f) | 0x40; rnds[8] = (rnds[8] & 0x3f) | 0x80; - + // Copy bytes to buffer, if provided if (buf) { for (var ii = 0; ii < 16; ii++) { buf[i + ii] = rnds[ii]; } } - + return buf || unparse(rnds); } - + // Export public API var uuid = v4; uuid.v1 = v1; uuid.v4 = v4; uuid.parse = parse; uuid.unparse = unparse; - + module.exports = uuid; - + },{"./rng":356}],358:[function(require,module,exports){ (function (global,Buffer){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -58292,9 +58292,9 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require("underscore"); var core = require('web3-core'); var Method = require('web3-core-method'); @@ -58309,36 +58309,36 @@ var uuid = require('uuid'); var utils = require('web3-utils'); var helpers = require('web3-core-helpers'); - + var isNot = function(value) { return (_.isUndefined(value) || _.isNull(value)); }; - + var trimLeadingZero = function (hex) { while (hex && hex.startsWith('0x0')) { hex = '0x' + hex.slice(3); } return hex; }; - + var makeEven = function (hex) { if(hex.length % 2 === 1) { hex = hex.replace('0x', '0x0'); } return hex; }; - - + + var Accounts = function Accounts() { var _this = this; - + // sets _requestmanager core.packageInit(this, arguments); - + // remove unecessary core functions delete this.BatchRequest; delete this.extend; - + var _ethereumCall = [ new Method({ name: 'getId', @@ -58370,14 +58370,14 @@ method.attachToObject(_this._ethereumCall); method.setRequestManager(_this._requestManager); }); - - + + this.wallet = new Wallet(this); }; - + Accounts.prototype._addAccountFunctions = function (account) { var _this = this; - + // add sign functions account.signTransaction = function signTransaction(tx, callback) { return _this.signTransaction(tx, account.privateKey, callback); @@ -58385,64 +58385,64 @@ account.sign = function sign(data) { return _this.sign(data, account.privateKey); }; - + account.encrypt = function encrypt(password, options) { return _this.encrypt(account.privateKey, password, options); }; - - + + return account; }; - + Accounts.prototype.create = function create(entropy) { return this._addAccountFunctions(Account.create(entropy || utils.randomHex(32))); }; - + Accounts.prototype.privateKeyToAccount = function privateKeyToAccount(privateKey) { return this._addAccountFunctions(Account.fromPrivate(privateKey)); }; - + Accounts.prototype.signTransaction = function signTransaction(tx, privateKey, callback) { var _this = this, error = false, result; - + callback = callback || function () {}; - + if (!tx) { error = new Error('No transaction object given!'); - + callback(error); return Promise.reject(error); } - + function signed (tx) { - + if (!tx.gas && !tx.gasLimit) { error = new Error('"gas" is missing'); } - + if (tx.nonce < 0 || tx.gas < 0 || tx.gasPrice < 0 || tx.chainId < 0) { error = new Error('Gas, gasPrice, nonce or chainId is lower than 0'); } - + if (error) { callback(error); return Promise.reject(error); } - + try { tx = helpers.formatters.inputCallFormatter(tx); - + var transaction = tx; transaction.to = tx.to || '0x'; transaction.data = tx.data || '0x'; transaction.value = tx.value || '0x'; transaction.chainId = utils.numberToHex(tx.chainId); - + var rlpEncoded = RLP.encode([ Bytes.fromNat(transaction.nonce), Bytes.fromNat(transaction.gasPrice), @@ -58453,20 +58453,20 @@ Bytes.fromNat(transaction.chainId || "0x1"), "0x", "0x"]); - - + + var hash = Hash.keccak256(rlpEncoded); - + var signature = Account.makeSigner(Nat.toNumber(transaction.chainId || "0x1") * 2 + 35)(Hash.keccak256(rlpEncoded), privateKey); - + var rawTx = RLP.decode(rlpEncoded).slice(0, 6).concat(Account.decodeSignature(signature)); - + rawTx[6] = makeEven(trimLeadingZero(rawTx[6])); rawTx[7] = makeEven(trimLeadingZero(rawTx[7])); rawTx[8] = makeEven(trimLeadingZero(rawTx[8])); - + var rawTransaction = RLP.encode(rawTx); - + var values = RLP.decode(rawTransaction); result = { messageHash: hash, @@ -58475,22 +58475,22 @@ s: trimLeadingZero(values[8]), rawTransaction: rawTransaction }; - + } catch(e) { callback(e); return Promise.reject(e); } - + callback(null, result); return result; } - + // Resolve immediately if nonce, chainId and price are provided if (tx.nonce !== undefined && tx.chainId !== undefined && tx.gasPrice !== undefined) { return Promise.resolve(signed(tx)); } - - + + // Otherwise, get the missing info from the Ethereum Node return Promise.all([ isNot(tx.chainId) ? _this._ethereumCall.getId() : tx.chainId, @@ -58503,7 +58503,7 @@ return signed(_.extend(tx, {chainId: args[0], gasPrice: args[1], nonce: args[2]})); }); }; - + /* jshint ignore:start */ Accounts.prototype.recoverTransaction = function recoverTransaction(rawTx) { var values = RLP.decode(rawTx); @@ -58515,7 +58515,7 @@ return Account.recover(Hash.keccak256(signingDataHex), signature); }; /* jshint ignore:end */ - + Accounts.prototype.hashMessage = function hashMessage(data) { var message = utils.isHexStrict(data) ? utils.hexToBytes(data) : data; var messageBuffer = Buffer.from(message); @@ -58524,7 +58524,7 @@ var ethMessage = Buffer.concat([preambleBuffer, messageBuffer]); return Hash.keccak256s(ethMessage); }; - + Accounts.prototype.sign = function sign(data, privateKey) { var hash = this.hashMessage(data); var signature = Account.sign(hash, privateKey); @@ -58538,89 +58538,89 @@ signature: signature }; }; - + Accounts.prototype.recover = function recover(message, signature, preFixed) { var args = [].slice.apply(arguments); - - + + if (_.isObject(message)) { return this.recover(message.messageHash, Account.encodeSignature([message.v, message.r, message.s]), true); } - + if (!preFixed) { message = this.hashMessage(message); } - + if (args.length >= 4) { preFixed = args.slice(-1)[0]; preFixed = _.isBoolean(preFixed) ? !!preFixed : false; - + return this.recover(message, Account.encodeSignature(args.slice(1, 4)), preFixed); // v, r, s } return Account.recover(message, signature); }; - + // Taken from https://github.com/ethereumjs/ethereumjs-wallet Accounts.prototype.decrypt = function (v3Keystore, password, nonStrict) { /* jshint maxcomplexity: 10 */ - + if(!_.isString(password)) { throw new Error('No password given.'); } - + var json = (_.isObject(v3Keystore)) ? v3Keystore : JSON.parse(nonStrict ? v3Keystore.toLowerCase() : v3Keystore); - + if (json.version !== 3) { throw new Error('Not a valid V3 wallet'); } - + var derivedKey; var kdfparams; if (json.crypto.kdf === 'scrypt') { kdfparams = json.crypto.kdfparams; - + // FIXME: support progress reporting callback derivedKey = scryptsy(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); } else if (json.crypto.kdf === 'pbkdf2') { kdfparams = json.crypto.kdfparams; - + if (kdfparams.prf !== 'hmac-sha256') { throw new Error('Unsupported parameters to PBKDF2'); } - + derivedKey = cryp.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); } else { throw new Error('Unsupported key derivation scheme'); } - + var ciphertext = new Buffer(json.crypto.ciphertext, 'hex'); - + var mac = utils.sha3(Buffer.concat([ derivedKey.slice(16, 32), ciphertext ])).replace('0x',''); if (mac !== json.crypto.mac) { throw new Error('Key derivation failed - possibly wrong password'); } - + var decipher = cryp.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex')); var seed = '0x'+ Buffer.concat([ decipher.update(ciphertext), decipher.final() ]).toString('hex'); - + return this.privateKeyToAccount(seed); }; - + Accounts.prototype.encrypt = function (privateKey, password, options) { /* jshint maxcomplexity: 20 */ var account = this.privateKeyToAccount(privateKey); - + options = options || {}; var salt = options.salt || cryp.randomBytes(32); var iv = options.iv || cryp.randomBytes(16); - + var derivedKey; var kdf = options.kdf || 'scrypt'; var kdfparams = { dklen: options.dklen || 32, salt: salt.toString('hex') }; - + if (kdf === 'pbkdf2') { kdfparams.c = options.c || 262144; kdfparams.prf = 'hmac-sha256'; @@ -58634,16 +58634,16 @@ } else { throw new Error('Unsupported kdf'); } - + var cipher = cryp.createCipheriv(options.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); if (!cipher) { throw new Error('Unsupported cipher'); } - + var ciphertext = Buffer.concat([ cipher.update(new Buffer(account.privateKey.replace('0x',''), 'hex')), cipher.final() ]); - + var mac = utils.sha3(Buffer.concat([ derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex') ])).replace('0x',''); - + return { version: 3, id: uuid.v4({ random: options.uuid || cryp.randomBytes(16) }), @@ -58660,17 +58660,17 @@ } }; }; - - + + // Note: this is trying to follow closely the specs on // http://web3js.readthedocs.io/en/1.0/web3-eth-accounts.html - + function Wallet(accounts) { this._accounts = accounts; this.length = 0; this.defaultKeyName = "web3js_wallet"; } - + Wallet.prototype._findSafeIndex = function (pointer) { pointer = pointer || 0; if (_.has(this, pointer)) { @@ -58679,47 +58679,47 @@ return pointer; } }; - + Wallet.prototype._currentIndexes = function () { var keys = Object.keys(this); var indexes = keys .map(function(key) { return parseInt(key); }) .filter(function(n) { return (n < 9e20); }); - + return indexes; }; - + Wallet.prototype.create = function (numberOfAccounts, entropy) { for (var i = 0; i < numberOfAccounts; ++i) { this.add(this._accounts.create(entropy).privateKey); } return this; }; - + Wallet.prototype.add = function (account) { - + if (_.isString(account)) { account = this._accounts.privateKeyToAccount(account); } if (!this[account.address]) { account = this._accounts.privateKeyToAccount(account.privateKey); account.index = this._findSafeIndex(); - + this[account.index] = account; this[account.address] = account; this[account.address.toLowerCase()] = account; - + this.length++; - + return account; } else { return this[account.address]; } }; - + Wallet.prototype.remove = function (addressOrIndex) { var account = this[addressOrIndex]; - + if (account && account.address) { // address this[account.address].privateKey = null; @@ -58730,97 +58730,97 @@ // index this[account.index].privateKey = null; delete this[account.index]; - + this.length--; - + return true; } else { return false; } }; - + Wallet.prototype.clear = function () { var _this = this; var indexes = this._currentIndexes(); - + indexes.forEach(function(index) { _this.remove(index); }); - + return this; }; - + Wallet.prototype.encrypt = function (password, options) { var _this = this; var indexes = this._currentIndexes(); - + var accounts = indexes.map(function(index) { return _this[index].encrypt(password, options); }); - + return accounts; }; - - + + Wallet.prototype.decrypt = function (encryptedWallet, password) { var _this = this; - + encryptedWallet.forEach(function (keystore) { var account = _this._accounts.decrypt(keystore, password); - + if (account) { _this.add(account); } else { throw new Error('Couldn\'t decrypt accounts. Password wrong?'); } }); - + return this; }; - + Wallet.prototype.save = function (password, keyName) { localStorage.setItem(keyName || this.defaultKeyName, JSON.stringify(this.encrypt(password))); - + return true; }; - + Wallet.prototype.load = function (password, keyName) { var keystore = localStorage.getItem(keyName || this.defaultKeyName); - + if (keystore) { try { keystore = JSON.parse(keystore); } catch(e) { - + } } - + return this.decrypt(keystore || [], password); }; - + if (typeof localStorage === 'undefined') { delete Wallet.prototype.save; delete Wallet.prototype.load; } - - + + module.exports = Accounts; - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) },{"any-promise":2,"buffer":84,"crypto":97,"crypto-browserify":97,"eth-lib/lib/account":350,"eth-lib/lib/bytes":352,"eth-lib/lib/hash":353,"eth-lib/lib/nat":354,"eth-lib/lib/rlp":355,"scrypt.js":293,"underscore":325,"uuid":357,"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-utils":403}],359:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -58836,11 +58836,11 @@ * @author Fabian Vogelsteller * @date 2017 */ - - + + "use strict"; - - + + var _ = require('underscore'); var core = require('web3-core'); var Method = require('web3-core-method'); @@ -58850,8 +58850,8 @@ var errors = require('web3-core-helpers').errors; var promiEvent = require('web3-core-promievent'); var abi = require('web3-eth-abi'); - - + + /** * Should be called to create new contract instance * @@ -58864,37 +58864,37 @@ var Contract = function Contract(jsonInterface, address, options) { var _this = this, args = Array.prototype.slice.call(arguments); - + if(!(this instanceof Contract)) { throw new Error('Please use the "new" keyword to instantiate a web3.eth.contract() object!'); } - + // sets _requestmanager core.packageInit(this, [this.constructor.currentProvider]); - + this.clearSubscriptions = this._requestManager.clearSubscriptions; - - - + + + if(!jsonInterface || !(Array.isArray(jsonInterface))) { throw new Error('You must provide the json interface of the contract when instantiating a contract object.'); } - - - + + + // create the options object this.options = {}; - + var lastArg = args[args.length - 1]; if(_.isObject(lastArg) && !_.isArray(lastArg)) { options = lastArg; - + this.options = _.extend(this.options, this._getOrSetDefaultOptions(options)); if(_.isObject(address)) { address = null; } } - + // set address Object.defineProperty(this.options, 'address', { set: function(value){ @@ -58907,27 +58907,27 @@ }, enumerable: true }); - + // add method and event signatures, when the jsonInterface gets set Object.defineProperty(this.options, 'jsonInterface', { set: function(value){ _this.methods = {}; _this.events = {}; - + _this._jsonInterface = value.map(function(method) { var func, funcName; - + // make constant and payable backwards compatible method.constant = (method.stateMutability === "view" || method.stateMutability === "pure" || method.constant); method.payable = (method.stateMutability === "payable" || method.payable); - - + + if (method.name) { funcName = utils._jsonInterfaceMethodToString(method); } - - + + // function if (method.type === 'function') { method.signature = abi.encodeFunctionSignature(funcName); @@ -58935,8 +58935,8 @@ method: method, parent: _this }); - - + + // add method only if not one already exists if(!_this.methods[method.name]) { _this.methods[method.name] = func; @@ -58948,37 +58948,37 @@ }); _this.methods[method.name] = cascadeFunc; } - + // definitely add the method based on its signature _this.methods[method.signature] = func; - + // add method by name _this.methods[funcName] = func; - - + + // event } else if (method.type === 'event') { method.signature = abi.encodeEventSignature(funcName); var event = _this._on.bind(_this, method.signature); - + // add method only if not already exists if(!_this.events[method.name] || _this.events[method.name].name === 'bound ') _this.events[method.name] = event; - + // definitely add the method based on its signature _this.events[method.signature] = event; - + // add event by name _this.events[funcName] = event; } - - + + return method; }); - + // add allEvents _this.events.allEvents = _this._on.bind(_this, 'allevents'); - + return _this._jsonInterface; }, get: function(){ @@ -58986,11 +58986,11 @@ }, enumerable: true }); - + // get default account from the Class var defaultAccount = this.constructor.defaultAccount; var defaultBlock = this.constructor.defaultBlock || 'latest'; - + Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; @@ -58999,7 +58999,7 @@ if(val) { defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); } - + return val; }, enumerable: true @@ -59010,33 +59010,33 @@ }, set: function (val) { defaultBlock = val; - + return val; }, enumerable: true }); - + // properties this.methods = {}; this.events = {}; - + this._address = null; this._jsonInterface = []; - + // set getter/setter properties this.options.address = address; this.options.jsonInterface = jsonInterface; - + }; - + Contract.setProvider = function(provider, accounts) { // Contract.currentProvider = provider; core.packageInit(this, [provider]); - + this._ethAccounts = accounts; }; - - + + /** * Get the callback and modiufy the array if necessary * @@ -59049,7 +59049,7 @@ return args.pop(); // modify the args array! } }; - + /** * Checks that no listener with name "newListener" or "removeListener" is added. * @@ -59063,8 +59063,8 @@ throw new Error('The event "'+ type +'" is a reserved event name, you can\'t use it.'); } }; - - + + /** * Use default values, if options are not available * @@ -59075,20 +59075,20 @@ Contract.prototype._getOrSetDefaultOptions = function getOrSetDefaultOptions(options) { var gasPrice = options.gasPrice ? String(options.gasPrice): null; var from = options.from ? utils.toChecksumAddress(formatters.inputAddressFormatter(options.from)) : null; - + options.data = options.data || this.options.data; - + options.from = from || this.options.from; options.gasPrice = gasPrice || this.options.gasPrice; options.gas = options.gas || options.gasLimit || this.options.gas; - + // TODO replace with only gasLimit? delete options.gasLimit; - + return options; }; - - + + /** * Should be used to encode indexed params and options to one final object * @@ -59101,27 +59101,27 @@ options = options || {}; var filter = options.filter || {}, result = {}; - + ['fromBlock', 'toBlock'].filter(function (f) { return options[f] !== undefined; }).forEach(function (f) { result[f] = formatters.inputBlockNumberFormatter(options[f]); }); - + // use given topics if(_.isArray(options.topics)) { result.topics = options.topics; - + // create topics based on filter } else { - + result.topics = []; - + // add event signature if (event && !event.anonymous && event.name !== 'ALLEVENTS') { result.topics.push(event.signature); } - + // add event topics (indexed arguments) if (event.name !== 'ALLEVENTS') { var indexedTopics = event.inputs.filter(function (i) { @@ -59131,10 +59131,10 @@ if (!value) { return null; } - + // TODO: https://github.com/ethereum/web3.js/issues/344 // TODO: deal properly with components - + if (_.isArray(value)) { return value.map(function (v) { return abi.encodeParameter(i.type, v); @@ -59142,21 +59142,21 @@ } return abi.encodeParameter(i.type, value); }); - + result.topics = result.topics.concat(indexedTopics); } - + if(!result.topics.length) delete result.topics; } - + if(this.options.address) { result.address = this.options.address.toLowerCase(); } - + return result; }; - + /** * Should be used to decode indexed params and options * @@ -59166,33 +59166,33 @@ */ Contract.prototype._decodeEventABI = function (data) { var event = this; - + data.data = data.data || ''; data.topics = data.topics || []; var result = formatters.outputLogFormatter(data); - + // if allEvents get the right event if(event.name === 'ALLEVENTS') { event = event.jsonInterface.find(function (intf) { return (intf.signature === data.topics[0]); }) || {anonymous: true}; } - + // create empty inputs if none are present (e.g. anonymous events on allEvents) event.inputs = event.inputs || []; - - + + var argTopics = event.anonymous ? data.topics : data.topics.slice(1); - + result.returnValues = abi.decodeLog(event.inputs, data.data, argTopics); delete result.returnValues.__length__; - + // add name result.event = event.name; - + // add signature result.signature = (event.anonymous || !data.topics[0]) ? null : data.topics[0]; - + // move the data and topics to "raw" result.raw = { data: result.data, @@ -59200,11 +59200,11 @@ }; delete result.data; delete result.topics; - - + + return result; }; - + /** * Encodes an ABI for a method, including signature or the method. * Or when constructor encodes only the constructor parameters. @@ -59216,18 +59216,18 @@ Contract.prototype._encodeMethodABI = function _encodeMethodABI() { var methodSignature = this._method.signature, args = this.arguments || []; - + var signature = false, paramsABI = this._parent.options.jsonInterface.filter(function (json) { return ((methodSignature === 'constructor' && json.type === methodSignature) || ((json.signature === methodSignature || json.signature === methodSignature.replace('0x','') || json.name === methodSignature) && json.type === 'function')); }).map(function (json) { var inputLength = (_.isArray(json.inputs)) ? json.inputs.length : 0; - + if (inputLength !== args.length) { throw new Error('The number of arguments is not matching the methods required number. You need to pass '+ inputLength +' arguments.'); } - + if (json.type === 'function') { signature = json.signature; } @@ -59235,29 +59235,29 @@ }).map(function (inputs) { return abi.encodeParameters(inputs, args).replace('0x',''); })[0] || ''; - + // return constructor if(methodSignature === 'constructor') { if(!this._deployData) throw new Error('The contract has no contract data option set. This is necessary to append the constructor parameters.'); - + return this._deployData + paramsABI; - + // return method } else { - + var returnValue = (signature) ? signature + paramsABI : paramsABI; - + if(!returnValue) { throw new Error('Couldn\'t find a matching contract method named "'+ this._method.name +'".'); } else { return returnValue; } } - + }; - - + + /** * Decode method return values * @@ -59270,10 +59270,10 @@ if (!returnValues) { return null; } - + returnValues = returnValues.length >= 2 ? returnValues.slice(2) : returnValues; var result = abi.decodeParameters(outputs, returnValues); - + if (result.__length__ === 1) { return result[0]; } else { @@ -59281,8 +59281,8 @@ return result; } }; - - + + /** * Deploys a contract and fire events based on its state: transactionHash, receipt * @@ -59294,32 +59294,32 @@ * @return {Object} EventEmitter possible events are "error", "transactionHash" and "receipt" */ Contract.prototype.deploy = function(options, callback){ - + options = options || {}; - + options.arguments = options.arguments || []; options = this._getOrSetDefaultOptions(options); - - + + // return error, if no "data" is specified if(!options.data) { return utils._fireError(new Error('No "data" specified in neither the given options, nor the default options.'), null, null, callback); } - + var constructor = _.find(this.options.jsonInterface, function (method) { return (method.type === 'constructor'); }) || {}; constructor.signature = 'constructor'; - + return this._createTxObject.apply({ method: constructor, parent: this, deployData: options.data, _ethAccounts: this.constructor._ethAccounts }, options.arguments); - + }; - + /** * Gets the event signature and outputformatters * @@ -59331,13 +59331,13 @@ */ Contract.prototype._generateEventOptions = function() { var args = Array.prototype.slice.call(arguments); - + // get the callback var callback = this._getCallback(args); - + // get the options var options = (_.isObject(args[args.length - 1])) ? args.pop() : {}; - + var event = (_.isString(args[0])) ? args[0] : 'allevents'; event = (event.toLowerCase() === 'allevents') ? { name: 'ALLEVENTS', @@ -59345,22 +59345,22 @@ } : this.options.jsonInterface.find(function (json) { return (json.type === 'event' && (json.name === event || json.signature === '0x'+ event.replace('0x',''))); }); - + if (!event) { throw new Error('Event "' + event.name + '" doesn\'t exist in this contract.'); } - + if (!utils.isAddress(this.options.address)) { throw new Error('This contract object doesn\'t have address set yet, please set an address first.'); } - + return { params: this._encodeEventABI(event, options), event: event, callback: callback }; }; - + /** * Adds event listeners and creates a subscription, and remove it once its fired. * @@ -59370,8 +59370,8 @@ Contract.prototype.clone = function() { return new this.constructor(this.options.jsonInterface, this.options.address, this.options); }; - - + + /** * Adds event listeners and creates a subscription, and remove it once its fired. * @@ -59383,18 +59383,18 @@ */ Contract.prototype.once = function(event, options, callback) { var args = Array.prototype.slice.call(arguments); - + // get the callback callback = this._getCallback(args); - + if (!callback) { throw new Error('Once requires a callback as the second parameter.'); } - + // don't allow fromBlock if (options) delete options.fromBlock; - + // don't return as once shouldn't provide "on" this._on(event, options, function (err, res, sub) { sub.unsubscribe(); @@ -59402,10 +59402,10 @@ callback(err, res, sub); } }); - + return undefined; }; - + /** * Adds event listeners and creates a subscription. * @@ -59417,14 +59417,14 @@ */ Contract.prototype._on = function(){ var subOptions = this._generateEventOptions.apply(this, arguments); - - + + // prevent the event "newListener" and "removeListener" from being overwritten this._checkListener('newListener', subOptions.event.name, subOptions.callback); this._checkListener('removeListener', subOptions.event.name, subOptions.callback); - + // TODO check if listener already exists? and reuse subscription if options are the same. - + // create new subscription var subscription = new Subscription({ subscription: { @@ -59438,7 +59438,7 @@ } else { this.emit('data', output); } - + if (_.isFunction(this.callback)) { this.callback(null, output, this); } @@ -59448,10 +59448,10 @@ requestManager: this._requestManager }); subscription.subscribe('logs', subOptions.params, subOptions.callback || function () {}); - + return subscription; }; - + /** * Get past events from contracts * @@ -59463,7 +59463,7 @@ */ Contract.prototype.getPastEvents = function(){ var subOptions = this._generateEventOptions.apply(this, arguments); - + var getPastLogs = new Method({ name: 'getPastLogs', call: 'eth_getLogs', @@ -59473,13 +59473,13 @@ }); getPastLogs.setRequestManager(this._requestManager); var call = getPastLogs.buildCall(); - + getPastLogs = null; - + return call(subOptions.params, subOptions.callback); }; - - + + /** * returns the an object with call, send, estimate functions * @@ -59489,39 +59489,39 @@ Contract.prototype._createTxObject = function _createTxObject(){ var args = Array.prototype.slice.call(arguments); var txObject = {}; - + if(this.method.type === 'function') { - + txObject.call = this.parent._executeMethod.bind(txObject, 'call'); txObject.call.request = this.parent._executeMethod.bind(txObject, 'call', true); // to make batch requests - + } - + txObject.send = this.parent._executeMethod.bind(txObject, 'send'); txObject.send.request = this.parent._executeMethod.bind(txObject, 'send', true); // to make batch requests txObject.encodeABI = this.parent._encodeMethodABI.bind(txObject); txObject.estimateGas = this.parent._executeMethod.bind(txObject, 'estimate'); - + if (args && this.method.inputs && args.length !== this.method.inputs.length) { if (this.nextMethod) { return this.nextMethod.apply(null, args); } throw errors.InvalidNumberOfParams(args.length, this.method.inputs.length, this.method.name); } - + txObject.arguments = args || []; txObject._method = this.method; txObject._parent = this.parent; txObject._ethAccounts = this.parent.constructor._ethAccounts || this._ethAccounts; - + if(this.deployData) { txObject._deployData = this.deployData; } - + return txObject; }; - - + + /** * Generates the options for the execute call * @@ -59531,39 +59531,39 @@ */ Contract.prototype._processExecuteArguments = function _processExecuteArguments(args, defer) { var processedArgs = {}; - + processedArgs.type = args.shift(); - + // get the callback processedArgs.callback = this._parent._getCallback(args); - + // get block number to use for call if(processedArgs.type === 'call' && args[args.length - 1] !== true && (_.isString(args[args.length - 1]) || isFinite(args[args.length - 1]))) processedArgs.defaultBlock = args.pop(); - + // get the options processedArgs.options = (_.isObject(args[args.length - 1])) ? args.pop() : {}; - + // get the generateRequest argument for batch requests processedArgs.generateRequest = (args[args.length - 1] === true)? args.pop() : false; - + processedArgs.options = this._parent._getOrSetDefaultOptions(processedArgs.options); processedArgs.options.data = this.encodeABI(); - + // add contract address if(!this._deployData && !utils.isAddress(this._parent.options.address)) throw new Error('This contract object doesn\'t have address set yet, please set an address first.'); - + if(!this._deployData) processedArgs.options.to = this._parent.options.address; - + // return error, if no "data" is specified if(!processedArgs.options.data) return utils._fireError(new Error('Couldn\'t find a matching contract method, or the number of parameters is wrong.'), defer.eventEmitter, defer.reject, processedArgs.callback); - + return processedArgs; }; - + /** * Executes a call, transact or estimateGas on a contract function * @@ -59576,15 +59576,15 @@ args = this._parent._processExecuteArguments.call(this, Array.prototype.slice.call(arguments), defer), defer = promiEvent((args.type !== 'send')), ethAccounts = _this.constructor._ethAccounts || _this._ethAccounts; - + // simple return request for batch requests if(args.generateRequest) { - + var payload = { params: [formatters.inputCallFormatter.call(this._parent, args.options)], callback: args.callback }; - + if(args.type === 'call') { payload.params.push(formatters.inputDefaultBlockNumberFormatter.call(this._parent, args.defaultBlock)); payload.method = 'eth_call'; @@ -59592,14 +59592,14 @@ } else { payload.method = 'eth_sendTransaction'; } - + return payload; - + } else { - + switch (args.type) { case 'estimate': - + var estimateGas = (new Method({ name: 'estimateGas', call: 'eth_estimateGas', @@ -59611,13 +59611,13 @@ defaultAccount: _this._parent.defaultAccount, defaultBlock: _this._parent.defaultBlock })).createFunction(); - + return estimateGas(args.options, args.callback); - + case 'call': - + // TODO check errors: missing "from" should give error on deploy and send, call ? - + var call = (new Method({ name: 'call', call: 'eth_call', @@ -59632,26 +59632,26 @@ defaultAccount: _this._parent.defaultAccount, defaultBlock: _this._parent.defaultBlock })).createFunction(); - + return call(args.options, args.defaultBlock, args.callback); - + case 'send': - + // return error, if no "from" is specified if(!utils.isAddress(args.options.from)) { return utils._fireError(new Error('No "from" address specified in neither the given options, nor the default options.'), defer.eventEmitter, defer.reject, args.callback); } - + if (_.isBoolean(this._method.payable) && !this._method.payable && args.options.value && args.options.value > 0) { return utils._fireError(new Error('Can not send value to non-payable contract method or constructor'), defer.eventEmitter, defer.reject, args.callback); } - - + + // make sure receipt logs are decoded var extraFormatters = { receiptFormatter: function (receipt) { if (_.isArray(receipt.logs)) { - + // decode logs var events = _.map(receipt.logs, function(log) { return _this._parent._decodeEventABI.call({ @@ -59659,7 +59659,7 @@ jsonInterface: _this._parent.options.jsonInterface }, log); }); - + // make log names keys receipt.events = {}; var count = 0; @@ -59680,7 +59680,7 @@ count++; } }); - + delete receipt.logs; } return receipt; @@ -59691,7 +59691,7 @@ return newContract; } }; - + var sendTransaction = (new Method({ name: 'sendTransaction', call: 'eth_sendTransaction', @@ -59703,17 +59703,17 @@ defaultBlock: _this._parent.defaultBlock, extraFormatters: extraFormatters })).createFunction(); - + return sendTransaction(args.options, args.callback); - + } - + } - + }; - + module.exports = Contract; - + },{"underscore":325,"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-core-promievent":340,"web3-core-subscriptions":345,"web3-eth-abi":349,"web3-utils":403}],360:[function(require,module,exports){ /* This file is part of web3.js. @@ -59734,13 +59734,13 @@ * @author Samuel Furter * @date 2018 */ - + "use strict"; - + var config = require('./config'); var Registry = require('./contracts/Registry'); var ResolverMethodHandler = require('./lib/ResolverMethodHandler'); - + /** * Constructs a new instance of ENS * @@ -59751,21 +59751,21 @@ function ENS(eth) { this.eth = eth; } - + Object.defineProperty(ENS.prototype, 'registry', { get: function () { return new Registry(this); }, enumerable: true }); - + Object.defineProperty(ENS.prototype, 'resolverMethodHandler', { get: function () { return new ResolverMethodHandler(this.registry); }, enumerable: true }); - + /** * @param {string} name * @returns {Promise} @@ -59773,7 +59773,7 @@ ENS.prototype.resolver = function (name) { return this.registry.resolver(name); }; - + /** * Returns the address record associated with a name. * @@ -59785,7 +59785,7 @@ ENS.prototype.getAddress = function (name, callback) { return this.resolverMethodHandler.method(name, 'addr', []).call(callback); }; - + /** * Sets a new address * @@ -59799,7 +59799,7 @@ ENS.prototype.setAddress = function (name, address, sendOptions, callback) { return this.resolverMethodHandler.method(name, 'setAddr', [address]).send(sendOptions, callback); }; - + /** * Returns the public key * @@ -59811,7 +59811,7 @@ ENS.prototype.getPubkey = function (name, callback) { return this.resolverMethodHandler.method(name, 'pubkey', [], callback).call(callback); }; - + /** * Set the new public key * @@ -59826,7 +59826,7 @@ ENS.prototype.setPubkey = function (name, x, y, sendOptions, callback) { return this.resolverMethodHandler.method(name, 'setPubkey', [x, y]).send(sendOptions, callback); }; - + /** * Returns the content * @@ -59838,7 +59838,7 @@ ENS.prototype.getContent = function (name, callback) { return this.resolverMethodHandler.method(name, 'content', []).call(callback); }; - + /** * Set the content * @@ -59852,7 +59852,7 @@ ENS.prototype.setContent = function (name, hash, sendOptions, callback) { return this.resolverMethodHandler.method(name, 'setContent', [hash]).send(sendOptions, callback); }; - + /** * Get the multihash * @@ -59864,7 +59864,7 @@ ENS.prototype.getMultihash = function (name, callback) { return this.resolverMethodHandler.method(name, 'multihash', []).call(callback); }; - + /** * Set the multihash * @@ -59878,7 +59878,7 @@ ENS.prototype.setMultihash = function (name, hash, sendOptions, callback) { return this.resolverMethodHandler.method(name, 'multihash', [hash]).send(sendOptions, callback); }; - + /** * Checks if the current used network is synced and looks for ENS support there. * Throws an error if not. @@ -59898,16 +59898,16 @@ if (typeof addr === 'undefined') { throw new Error("ENS is not supported on network " + networkType); } - + return addr; }); }; - + module.exports = ENS; - + },{"./config":361,"./contracts/Registry":362,"./lib/ResolverMethodHandler":364}],361:[function(require,module,exports){ "use strict"; - + var config = { addresses: { main: "0x314159265dD8dbb310642f98f50C066173C1259b", @@ -59915,9 +59915,9 @@ rinkeby: "0xe7410170f87102df0055eb195163a03b7f2bff4a" }, }; - + module.exports = config; - + },{}],362:[function(require,module,exports){ /* This file is part of web3.js. @@ -59938,17 +59938,17 @@ * @author Samuel Furter * @date 2018 */ - + "use strict"; - + var _ = require('underscore'); var Contract = require('web3-eth-contract'); var namehash = require('eth-ens-namehash'); var PromiEvent = require('web3-core-promievent'); var REGISTRY_ABI = require('../ressources/ABI/Registry'); var RESOLVER_ABI = require('../ressources/ABI/Resolver'); - - + + /** * A wrapper around the ENS registry contract. * @@ -59962,11 +59962,11 @@ this.contract = ens.checkNetwork().then(function (address) { var contract = new Contract(REGISTRY_ABI, address); contract.setProvider(self.ens.eth.currentProvider); - + return contract; }); } - + /** * Returns the address of the owner of an ENS name. * @@ -59977,28 +59977,28 @@ */ Registry.prototype.owner = function (name, callback) { var promiEvent = new PromiEvent(true); - + this.contract.then(function (contract) { contract.methods.owner(namehash.hash(name)).call() .then(function (receipt) { promiEvent.resolve(receipt); - + if (_.isFunction(callback)) { callback(receipt); } }) .catch(function (error) { promiEvent.reject(error); - + if (_.isFunction(callback)) { callback(error); } }); }); - + return promiEvent.eventEmitter; }; - + /** * Returns the resolver contract associated with a name. * @@ -60008,7 +60008,7 @@ */ Registry.prototype.resolver = function (name) { var self = this; - + return this.contract.then(function (contract) { return contract.methods.resolver(namehash.hash(name)).call(); }).then(function (address) { @@ -60017,9 +60017,9 @@ return contract; }); }; - + module.exports = Registry; - + },{"../ressources/ABI/Registry":365,"../ressources/ABI/Resolver":366,"eth-ens-namehash":127,"underscore":325,"web3-core-promievent":340,"web3-eth-contract":359}],363:[function(require,module,exports){ /* This file is part of web3.js. @@ -60040,13 +60040,13 @@ * @author Samuel Furter * @date 2018 */ - + "use strict"; - + var ENS = require('./ENS'); - + module.exports = ENS; - + },{"./ENS":360}],364:[function(require,module,exports){ /* This file is part of web3.js. @@ -60067,13 +60067,13 @@ * @author Samuel Furter * @date 2018 */ - + "use strict"; - + var PromiEvent = require('web3-core-promievent'); var namehash = require('eth-ens-namehash'); var _ = require('underscore'); - + /** * @param {Registry} registry * @constructor @@ -60081,7 +60081,7 @@ function ResolverMethodHandler(registry) { this.registry = registry; } - + /** * Executes an resolver method and returns an eventifiedPromise * @@ -60109,7 +60109,7 @@ }) }; }; - + /** * Executes call * @@ -60119,17 +60119,17 @@ var self = this; var promiEvent = new PromiEvent(); var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); - + this.parent.registry.resolver(this.ensName).then(function (resolver) { self.parent.handleCall(promiEvent, resolver.methods[self.methodName], preparedArguments, callback); }).catch(function (error) { promiEvent.reject(error); }); - + return promiEvent.eventEmitter; }; - - + + /** * Executes send * @@ -60141,16 +60141,16 @@ var self = this; var promiEvent = new PromiEvent(); var preparedArguments = this.parent.prepareArguments(this.ensName, this.methodArguments); - + this.parent.registry.resolver(this.ensName).then(function (resolver) { self.parent.handleSend(promiEvent, resolver.methods[self.methodName], preparedArguments, sendOptions, callback); }).catch(function (error) { promiEvent.reject(error); }); - + return promiEvent.eventEmitter; }; - + /** * Handles a call method * @@ -60164,21 +60164,21 @@ method.apply(this, preparedArguments).call() .then(function (receipt) { promiEvent.resolve(receipt); - + if (_.isFunction(callback)) { callback(receipt); } }).catch(function (error) { promiEvent.reject(error); - + if (_.isFunction(callback)) { callback(error); } }); - + return promiEvent; }; - + /** * Handles a send method * @@ -60200,7 +60200,7 @@ .on('receipt', function (receipt) { promiEvent.eventEmitter.emit('receipt', receipt); promiEvent.resolve(receipt); - + if (_.isFunction(callback)) { callback(receipt); } @@ -60208,15 +60208,15 @@ .on('error', function (error) { promiEvent.eventEmitter.emit('error', error); promiEvent.reject(error); - + if (_.isFunction(callback)) { callback(error); } }); - + return promiEvent; }; - + /** * Adds the ENS node to the arguments * @@ -60226,21 +60226,21 @@ */ ResolverMethodHandler.prototype.prepareArguments = function (name, methodArguments) { var node = namehash.hash(name); - + if (methodArguments.length > 0) { methodArguments.unshift(node); - + return methodArguments; } - + return [node]; }; - + module.exports = ResolverMethodHandler; - + },{"eth-ens-namehash":127,"underscore":325,"web3-core-promievent":340}],365:[function(require,module,exports){ "use strict"; - + var REGISTRY = [ { "constant": true, @@ -60442,12 +60442,12 @@ "type": "event" } ]; - + module.exports = REGISTRY; - + },{}],366:[function(require,module,exports){ "use strict"; - + var RESOLVER = [ { "constant": true, @@ -60800,25 +60800,25 @@ "type": "event" } ]; - + module.exports = RESOLVER; - + },{}],367:[function(require,module,exports){ arguments[4][154][0].apply(exports,arguments) },{"dup":154}],368:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -60830,13 +60830,13 @@ * @author Marek Kotewicz * @date 2015 */ - + "use strict"; - + var utils = require('web3-utils'); var BigNumber = require('bn.js'); - - + + var leftPad = function (string, bytes) { var result = string; while (result.length < bytes * 2) { @@ -60844,7 +60844,7 @@ } return result; }; - + /** * Prepare an IBAN for mod 97 computation by moving the first 4 chars to the end and transforming the letters to * numbers (A = 10, B = 11, ..., Z = 35), as specified in ISO13616. @@ -60856,10 +60856,10 @@ var iso13616Prepare = function (iban) { var A = 'A'.charCodeAt(0); var Z = 'Z'.charCodeAt(0); - + iban = iban.toUpperCase(); iban = iban.substr(4) + iban.substr(0,4); - + return iban.split('').map(function(n){ var code = n.charCodeAt(0); if (code >= A && code <= Z){ @@ -60870,7 +60870,7 @@ } }).join(''); }; - + /** * Calculates the MOD 97 10 of the passed IBAN as specified in ISO7064. * @@ -60881,15 +60881,15 @@ var mod9710 = function (iban) { var remainder = iban, block; - + while (remainder.length > 2){ block = remainder.slice(0, 9); remainder = parseInt(block, 10) % 97 + remainder.slice(block.length); } - + return parseInt(remainder, 10) % 97; }; - + /** * This prototype should be used to create iban object from iban correct string * @@ -60898,7 +60898,7 @@ var Iban = function Iban(iban) { this._iban = iban; }; - + /** * This method should be used to create an ethereum address from a direct iban address * @@ -60908,14 +60908,14 @@ */ Iban.toAddress = function (ib) { ib = new Iban(ib); - + if(!ib.isDirect()) { throw new Error('IBAN is indirect and can\'t be converted'); } - + return ib.toAddress(); }; - + /** * This method should be used to create iban address from an ethereum address * @@ -60926,7 +60926,7 @@ Iban.toIban = function (address) { return Iban.fromAddress(address).toString(); }; - + /** * This method should be used to create iban object from an ethereum address * @@ -60938,15 +60938,15 @@ if(!utils.isAddress(address)){ throw new Error('Provided address is not a valid address: '+ address); } - + address = address.replace('0x','').replace('0X',''); - + var asBn = new BigNumber(address, 16); var base36 = asBn.toString(36); var padded = leftPad(base36, 15); return Iban.fromBban(padded.toUpperCase()); }; - + /** * Convert the passed BBAN to an IBAN for this country specification. * Please note that "generation of the IBAN shall be the exclusive responsibility of the bank/branch servicing the account". @@ -60958,13 +60958,13 @@ */ Iban.fromBban = function (bban) { var countryCode = 'XE'; - + var remainder = mod9710(iso13616Prepare(countryCode + '00' + bban)); var checkDigit = ('0' + (98 - remainder)).slice(-2); - + return new Iban(countryCode + checkDigit + bban); }; - + /** * Should be used to create IBAN object for given institution and identifier * @@ -60975,7 +60975,7 @@ Iban.createIndirect = function (options) { return Iban.fromBban('ETH' + options.institution + options.identifier); }; - + /** * This method should be used to check if given string is valid iban object * @@ -60987,7 +60987,7 @@ var i = new Iban(iban); return i.isValid(); }; - + /** * Should be called to check if iban is correct * @@ -60998,7 +60998,7 @@ return /^XE[0-9]{2}(ETH[0-9A-Z]{13}|[0-9A-Z]{30,31})$/.test(this._iban) && mod9710(iso13616Prepare(this._iban)) === 1; }; - + /** * Should be called to check if iban number is direct * @@ -61008,7 +61008,7 @@ Iban.prototype.isDirect = function () { return this._iban.length === 34 || this._iban.length === 35; }; - + /** * Should be called to check if iban number if indirect * @@ -61018,7 +61018,7 @@ Iban.prototype.isIndirect = function () { return this._iban.length === 20; }; - + /** * Should be called to get iban checksum * Uses the mod-97-10 checksumming protocol (ISO/IEC 7064:2003) @@ -61029,7 +61029,7 @@ Iban.prototype.checksum = function () { return this._iban.substr(2, 2); }; - + /** * Should be called to get institution identifier * eg. XREG @@ -61040,7 +61040,7 @@ Iban.prototype.institution = function () { return this.isIndirect() ? this._iban.substr(7, 4) : ''; }; - + /** * Should be called to get client identifier within institution * eg. GAVOFYORK @@ -61051,7 +61051,7 @@ Iban.prototype.client = function () { return this.isIndirect() ? this._iban.substr(11) : ''; }; - + /** * Should be called to get client direct address * @@ -61064,30 +61064,30 @@ var asBn = new BigNumber(base36, 36); return utils.toChecksumAddress(asBn.toString(16, 20)); } - + return ''; }; - + Iban.prototype.toString = function () { return this._iban; }; - + module.exports = Iban; - + },{"bn.js":367,"web3-utils":403}],369:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -61096,28 +61096,28 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var core = require('web3-core'); var Method = require('web3-core-method'); var utils = require('web3-utils'); var Net = require('web3-net'); - + var formatters = require('web3-core-helpers').formatters; - - + + var Personal = function Personal() { var _this = this; - + // sets _requestmanager core.packageInit(this, arguments); - + this.net = new Net(this.currentProvider); - + var defaultAccount = null; var defaultBlock = 'latest'; - + Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; @@ -61126,12 +61126,12 @@ if(val) { defaultAccount = utils.toChecksumAddress(formatters.inputAddressFormatter(val)); } - + // update defaultBlock methods.forEach(function(method) { method.defaultAccount = defaultAccount; }); - + return val; }, enumerable: true @@ -61142,18 +61142,18 @@ }, set: function (val) { defaultBlock = val; - + // update defaultBlock methods.forEach(function(method) { method.defaultBlock = defaultBlock; }); - + return val; }, enumerable: true }); - - + + var methods = [ new Method({ name: 'getAccounts', @@ -61217,29 +61217,29 @@ method.defaultAccount = _this.defaultAccount; }); }; - + core.addProviders(Personal); - - - + + + module.exports = Personal; - - - + + + },{"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-net":372,"web3-utils":403}],370:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -61248,26 +61248,26 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); - + var getNetworkType = function (callback) { var _this = this, id; - - + + return this.net.getId() .then(function (givenId) { - + id = givenId; - + return _this.getBlock(0); }) .then(function (genesis) { var returnValue = 'private'; - + if (genesis.hash === '0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3' && id === 1) { returnValue = 'main'; @@ -61288,11 +61288,11 @@ id === 42) { returnValue = 'kovan'; } - + if (_.isFunction(callback)) { callback(null, returnValue); } - + return returnValue; }) .catch(function (err) { @@ -61303,23 +61303,23 @@ } }); }; - + module.exports = getNetworkType; - + },{"underscore":325}],371:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -61328,9 +61328,9 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var core = require('web3-core'); var helpers = require('web3-core-helpers'); @@ -61338,45 +61338,45 @@ var Method = require('web3-core-method'); var utils = require('web3-utils'); var Net = require('web3-net'); - + var ENS = require('web3-eth-ens'); var Personal = require('web3-eth-personal'); var BaseContract = require('web3-eth-contract'); var Iban = require('web3-eth-iban'); var Accounts = require('web3-eth-accounts'); var abi = require('web3-eth-abi'); - + var getNetworkType = require('./getNetworkType.js'); var formatter = helpers.formatters; - - + + var blockCall = function (args) { return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? "eth_getBlockByHash" : "eth_getBlockByNumber"; }; - + var transactionFromBlockCall = function (args) { return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getTransactionByBlockHashAndIndex' : 'eth_getTransactionByBlockNumberAndIndex'; }; - + var uncleCall = function (args) { return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleByBlockHashAndIndex' : 'eth_getUncleByBlockNumberAndIndex'; }; - + var getBlockTransactionCountCall = function (args) { return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getBlockTransactionCountByHash' : 'eth_getBlockTransactionCountByNumber'; }; - + var uncleCountCall = function (args) { return (_.isString(args[0]) && args[0].indexOf('0x') === 0) ? 'eth_getUncleCountByBlockHash' : 'eth_getUncleCountByBlockNumber'; }; - - + + var Eth = function Eth() { var _this = this; - + // sets _requestmanager core.packageInit(this, arguments); - + // overwrite setProvider var setProvider = this.setProvider; this.setProvider = function () { @@ -61386,11 +61386,11 @@ _this.accounts.setProvider.apply(_this, arguments); _this.Contract.setProvider(_this.currentProvider, _this.accounts); }; - - + + var defaultAccount = null; var defaultBlock = 'latest'; - + Object.defineProperty(this, 'defaultAccount', { get: function () { return defaultAccount; @@ -61399,16 +61399,16 @@ if(val) { defaultAccount = utils.toChecksumAddress(formatter.inputAddressFormatter(val)); } - + // also set on the Contract object _this.Contract.defaultAccount = defaultAccount; _this.personal.defaultAccount = defaultAccount; - + // update defaultBlock methods.forEach(function(method) { method.defaultAccount = defaultAccount; }); - + return val; }, enumerable: true @@ -61422,32 +61422,32 @@ // also set on the Contract object _this.Contract.defaultBlock = defaultBlock; _this.personal.defaultBlock = defaultBlock; - + // update defaultBlock methods.forEach(function(method) { method.defaultBlock = defaultBlock; }); - + return val; }, enumerable: true }); - - + + this.clearSubscriptions = _this._requestManager.clearSubscriptions; - + // add net this.net = new Net(this.currentProvider); // add chain detection this.net.getNetworkType = getNetworkType.bind(this); - + // add accounts this.accounts = new Accounts(this.currentProvider); - + // add personal this.personal = new Personal(this.currentProvider); this.personal.defaultAccount = this.defaultAccount; - + // create a proxy Contract type for this instance, as a Contract's provider // is stored as a class member rather than an instance variable. If we do // not create this proxy type, changing the provider in one instance of @@ -61456,7 +61456,7 @@ var self = this; var Contract = function Contract() { BaseContract.apply(this, arguments); - + // when Eth.setProvider is called, call packageInit // on all contract instances instantiated via this Eth // instances. This will update the currentProvider for @@ -61468,31 +61468,31 @@ core.packageInit(_this, [self.currentProvider]); }; }; - + Contract.setProvider = function() { BaseContract.setProvider.apply(this, arguments); }; - + // make our proxy Contract inherit from web3-eth-contract so that it has all // the right functionality and so that instanceof and friends work properly Contract.prototype = Object.create(BaseContract.prototype); Contract.prototype.constructor = Contract; - + // add contract this.Contract = Contract; this.Contract.defaultAccount = this.defaultAccount; this.Contract.defaultBlock = this.defaultBlock; this.Contract.setProvider(this.currentProvider, this.accounts); - + // add IBAN this.Iban = Iban; - + // add ABI this.abi = abi; - + // add ENS this.ens = new ENS(this); - + var methods = [ new Method({ name: 'getNodeInfo', @@ -61575,7 +61575,7 @@ params: 2, inputFormatter: [formatter.inputBlockNumberFormatter, utils.numberToHex], outputFormatter: formatter.outputBlockFormatter, - + }), new Method({ name: 'getBlockTransactionCount', @@ -61677,7 +61677,7 @@ inputFormatter: [formatter.inputLogFormatter], outputFormatter: formatter.outputLogFormatter }), - + // subscriptions new Subscriptions({ name: 'subscribe', @@ -61704,7 +61704,7 @@ } else { this.emit('data', output); } - + if (_.isFunction(this.callback)) { this.callback(null, output, this); } @@ -61715,38 +61715,38 @@ outputFormatter: formatter.outputSyncingFormatter, subscriptionHandler: function (output) { var _this = this; - + // fire TRUE at start if(this._isSyncing !== true) { this._isSyncing = true; this.emit('changed', _this._isSyncing); - + if (_.isFunction(this.callback)) { this.callback(null, _this._isSyncing, this); } - + setTimeout(function () { _this.emit('data', output); - + if (_.isFunction(_this.callback)) { _this.callback(null, output, _this); } }, 0); - + // fire sync status } else { this.emit('data', output); if (_.isFunction(_this.callback)) { this.callback(null, output, this); } - + // wait for some time before fireing the FALSE clearTimeout(this._isSyncingTimeout); this._isSyncingTimeout = setTimeout(function () { if(output.currentBlock > output.highestBlock - 200) { _this._isSyncing = false; _this.emit('changed', _this._isSyncing); - + if (_.isFunction(_this.callback)) { _this.callback(null, _this._isSyncing, _this); } @@ -61758,36 +61758,36 @@ } }) ]; - + methods.forEach(function(method) { method.attachToObject(_this); method.setRequestManager(_this._requestManager, _this.accounts); // second param means is eth.accounts (necessary for wallet signing) method.defaultBlock = _this.defaultBlock; method.defaultAccount = _this.defaultAccount; }); - + }; - + core.addProviders(Eth); - - + + module.exports = Eth; - - + + },{"./getNetworkType.js":370,"underscore":325,"web3-core":348,"web3-core-helpers":338,"web3-core-method":339,"web3-core-subscriptions":345,"web3-eth-abi":349,"web3-eth-accounts":358,"web3-eth-contract":359,"web3-eth-ens":363,"web3-eth-iban":368,"web3-eth-personal":369,"web3-net":372,"web3-utils":403}],372:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -61796,21 +61796,21 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var core = require('web3-core'); var Method = require('web3-core-method'); var utils = require('web3-utils'); - - + + var Net = function () { var _this = this; - + // sets _requestmanager core.packageInit(this, arguments); - - + + [ new Method({ name: 'getId', @@ -61833,16 +61833,16 @@ method.attachToObject(_this); method.setRequestManager(_this._requestManager); }); - + }; - + core.addProviders(Net); - - + + module.exports = Net; - - - + + + },{"web3-core":348,"web3-core-method":339,"web3-utils":403}],373:[function(require,module,exports){ const EventEmitter = require('events').EventEmitter const inherits = require('util').inherits @@ -61854,19 +61854,19 @@ const cacheUtils = require('./util/rpc-cache-utils.js') const createPayload = require('./util/create-payload.js') const noop = function(){} - + module.exports = Web3ProviderEngine - - + + inherits(Web3ProviderEngine, EventEmitter) - + function Web3ProviderEngine(opts) { const self = this EventEmitter.call(self) self.setMaxListeners(30) // parse options opts = opts || {} - + // block polling const directProvider = { sendAsync: self._handleAsync.bind(self) } const blockTrackerProvider = opts.blockTrackerProvider || directProvider @@ -61874,18 +61874,18 @@ provider: blockTrackerProvider, pollingInterval: opts.pollingInterval || 4000, }) - + // handle new block self._blockTracker.on('block', (jsonBlock) => { const bufferBlock = toBufferBlock(jsonBlock) self._setCurrentBlock(bufferBlock) }) - + // emit block events from the block tracker self._blockTracker.on('block', self.emit.bind(self, 'rawBlock')) self._blockTracker.on('sync', self.emit.bind(self, 'sync')) self._blockTracker.on('latest', self.emit.bind(self, 'latest')) - + // set initialization blocker self._ready = new Stoplight() // unblock initialization after first block @@ -61896,35 +61896,35 @@ self.currentBlock = null self._providers = [] } - + // public - + Web3ProviderEngine.prototype.start = function(cb = noop){ const self = this // start block polling self._blockTracker.start().then(cb).catch(cb) } - + Web3ProviderEngine.prototype.stop = function(){ const self = this // stop block polling self._blockTracker.stop() } - + Web3ProviderEngine.prototype.addProvider = function(source){ const self = this self._providers.push(source) source.setEngine(this) } - + Web3ProviderEngine.prototype.send = function(payload){ throw new Error('Web3ProviderEngine does not support synchronous requests.') } - + Web3ProviderEngine.prototype.sendAsync = function(payload, cb){ const self = this self._ready.await(function(){ - + if (Array.isArray(payload)) { // handle batch map(payload, self._handleAsync.bind(self), cb) @@ -61932,26 +61932,26 @@ // handle single self._handleAsync(payload, cb) } - + }) } - + // private - + Web3ProviderEngine.prototype._handleAsync = function(payload, finished) { var self = this var currentProvider = -1 var result = null var error = null - + var stack = [] - + next() - + function next(after) { currentProvider += 1 stack.unshift(after) - + // Bubbled down as far as we could go, and the request wasn't // handled. Return an error. if (currentProvider >= self._providers.length) { @@ -61965,13 +61965,13 @@ } } } - + function end(_error, _result) { error = _error result = _result - + eachSeries(stack, function(fn, callback) { - + if (fn) { fn(error, result, callback) } else { @@ -61980,13 +61980,13 @@ }, function() { // console.log('COMPLETED:', payload) // console.log('RESULT: ', result) - + var resultObj = { id: payload.id, jsonrpc: payload.jsonrpc, result: result } - + if (error != null) { resultObj.error = { message: error.stack || error.message || error, @@ -62000,19 +62000,19 @@ }) } } - + // // from remote-data // - + Web3ProviderEngine.prototype._setCurrentBlock = function(block){ const self = this self.currentBlock = block self.emit('block', block) } - + // util - + function toBufferBlock (jsonBlock) { return { number: ethUtil.toBuffer(jsonBlock.number), @@ -62036,10 +62036,10 @@ transactions: jsonBlock.transactions, } } - + },{"./util/create-payload.js":391,"./util/rpc-cache-utils.js":394,"./util/stoplight.js":396,"async/eachSeries":25,"async/map":41,"eth-block-tracker":126,"ethereumjs-util":141,"events":157,"util":333}],374:[function(require,module,exports){ var json = typeof JSON !== 'undefined' ? JSON : require('jsonify'); - + module.exports = function (obj, opts) { if (!opts) opts = {}; if (typeof opts === 'function') opts = { cmp: opts }; @@ -62047,7 +62047,7 @@ if (typeof space === 'number') space = Array(space+1).join(' '); var cycles = (typeof opts.cycles === 'boolean') ? opts.cycles : false; var replacer = opts.replacer || function(key, value) { return value; }; - + var cmp = opts.cmp && (function (f) { return function (node) { return function (a, b) { @@ -62057,18 +62057,18 @@ }; }; })(opts.cmp); - + var seen = []; return (function stringify (parent, key, node, level) { var indent = space ? ('\n' + new Array(level + 1).join(space)) : ''; var colonSeparator = space ? ': ' : ':'; - + if (node && node.toJSON && typeof node.toJSON === 'function') { node = node.toJSON(); } - + node = replacer.call(parent, key, node); - + if (node === undefined) { return; } @@ -62089,15 +62089,15 @@ throw new TypeError('Converting circular structure to JSON'); } else seen.push(node); - + var keys = objectKeys(node).sort(cmp && cmp(node)); var out = []; for (var i = 0; i < keys.length; i++) { var key = keys[i]; var value = stringify(node, key, node[key], level+1); - + if(!value) continue; - + var keyValue = json.stringify(key) + colonSeparator + value; @@ -62109,11 +62109,11 @@ } })({ '': obj }, '', obj, 0); }; - + var isArray = Array.isArray || function (x) { return {}.toString.call(x) === '[object Array]'; }; - + var objectKeys = Object.keys || function (obj) { var has = Object.prototype.hasOwnProperty || function () { return true }; var keys = []; @@ -62122,7 +62122,7 @@ } return keys; }; - + },{"jsonify":192}],375:[function(require,module,exports){ module.exports={ "_from": "web3-provider-engine@14.1.0", @@ -62210,7 +62210,7 @@ }, "version": "14.1.0" } - + },{}],376:[function(require,module,exports){ const inherits = require('util').inherits const ethUtil = require('ethereumjs-util') @@ -62219,11 +62219,11 @@ const cacheUtils = require('../util/rpc-cache-utils.js') const Stoplight = require('../util/stoplight.js') const Subprovider = require('./subprovider.js') - + module.exports = BlockCacheProvider - + inherits(BlockCacheProvider, Subprovider) - + function BlockCacheProvider(opts) { const self = this opts = opts || {} @@ -62238,7 +62238,7 @@ fork: new BlockCacheStrategy(self), } } - + // setup a block listener on 'setEngine' BlockCacheProvider.prototype.setEngine = function(engine) { const self = this @@ -62250,7 +62250,7 @@ // from now on, empty old cache every block engine.on('block', clearOldCache) }) - + function clearOldCache(newBlock) { var previousBlock = self.currentBlock self.currentBlock = newBlock @@ -62259,49 +62259,49 @@ self.strategies.fork.cacheRollOff(previousBlock) } } - + BlockCacheProvider.prototype.handleRequest = function(payload, next, end){ const self = this - + // skip cache if told to do so if (payload.skipCache) { // console.log('CACHE SKIP - skip cache if told to do so') return next() } - + // Ignore block polling requests. if (payload.method === 'eth_getBlockByNumber' && payload.params[0] === 'latest') { // console.log('CACHE SKIP - Ignore block polling requests.') return next() } - + // wait for first block self._ready.await(function(){ // actually handle the request self._handleRequest(payload, next, end) }) } - + BlockCacheProvider.prototype._handleRequest = function(payload, next, end){ const self = this - + var type = cacheUtils.cacheTypeForPayload(payload) var strategy = this.strategies[type] - + // If there's no strategy in place, pass it down the chain. if (!strategy) { return next() } - + // If the strategy can't cache this request, ignore it. if (!strategy.canCache(payload)) { return next() } - + var blockTag = cacheUtils.blockTagForPayload(payload) if (!blockTag) blockTag = 'latest' var requestedBlockNumber - + if (blockTag === 'earliest') { requestedBlockNumber = '0x00' } else if (blockTag === 'latest') { @@ -62310,9 +62310,9 @@ // We have a hex number requestedBlockNumber = blockTag } - + //console.log('REQUEST at block 0x' + requestedBlockNumber.toString('hex')) - + // end on a hit, continue on a miss strategy.hitCheck(payload, requestedBlockNumber, end, function() { // miss fallthrough to provider chain, caching the result on the way back up. @@ -62323,11 +62323,11 @@ }) }) } - + // // Cache Strategies // - + function PermaCacheStrategy() { var self = this self.cache = {} @@ -62338,13 +62338,13 @@ // do not require the Node.js event loop to remain active if (timeout.unref) timeout.unref() } - + PermaCacheStrategy.prototype.hitCheck = function(payload, requestedBlockNumber, hit, miss) { var identifier = cacheUtils.cacheIdentifierForPayload(payload) var cached = this.cache[identifier] - + if (!cached) return miss() - + // If the block number we're requesting at is greater than or // equal to the block where we cached a previous response, // the cache is valid. If it's from earlier than the cache, @@ -62357,10 +62357,10 @@ return miss() } } - + PermaCacheStrategy.prototype.cacheResult = function(payload, result, requestedBlockNumber, callback) { var identifier = cacheUtils.cacheIdentifierForPayload(payload) - + if (result) { var clonedValue = clone(result) this.cache[identifier] = { @@ -62368,30 +62368,30 @@ result: clonedValue, } } - + callback() } - + PermaCacheStrategy.prototype.canCache = function(payload) { return cacheUtils.canCache(payload) } - + // // ConditionalPermaCacheStrategy // - + function ConditionalPermaCacheStrategy(conditionals) { this.strategy = new PermaCacheStrategy() this.conditionals = conditionals } - + ConditionalPermaCacheStrategy.prototype.hitCheck = function(payload, requestedBlockNumber, hit, miss) { return this.strategy.hitCheck(payload, requestedBlockNumber, hit, miss) } - + ConditionalPermaCacheStrategy.prototype.cacheResult = function(payload, result, requestedBlockNumber, callback) { var conditional = this.conditionals[payload.method] - + if (conditional) { if (conditional(result)) { this.strategy.cacheResult(payload, result, requestedBlockNumber, callback) @@ -62403,19 +62403,19 @@ this.strategy.cacheResult(payload, result, requestedBlockNumber, callback) } } - + ConditionalPermaCacheStrategy.prototype.canCache = function(payload) { return this.strategy.canCache(payload) } - + // // BlockCacheStrategy // - + function BlockCacheStrategy() { this.cache = {} } - + BlockCacheStrategy.prototype.getBlockCacheForPayload = function(payload, blockNumberHex) { const blockNumber = Number.parseInt(blockNumberHex, 16) let blockCache = this.cache[blockNumber] @@ -62427,24 +62427,24 @@ } return blockCache } - + BlockCacheStrategy.prototype.hitCheck = function(payload, requestedBlockNumber, hit, miss) { var blockCache = this.getBlockCacheForPayload(payload, requestedBlockNumber) - + if (!blockCache) { return miss() } - + var identifier = cacheUtils.cacheIdentifierForPayload(payload) var cached = blockCache[identifier] - + if (cached) { return hit(null, cached) } else { return miss() } } - + BlockCacheStrategy.prototype.cacheResult = function(payload, result, requestedBlockNumber, callback) { if (result) { var blockCache = this.getBlockCacheForPayload(payload, requestedBlockNumber) @@ -62453,17 +62453,17 @@ } callback() } - + BlockCacheStrategy.prototype.canCache = function(payload) { if (!cacheUtils.canCache(payload)) { return false } - + var blockTag = cacheUtils.blockTagForPayload(payload) - + return (blockTag !== 'pending') } - + // naively removes older block caches BlockCacheStrategy.prototype.cacheRollOff = function(previousBlock){ const self = this @@ -62475,37 +62475,37 @@ .filter(num => num <= oldBlockNumber) .forEach(num => delete self.cache[num]) } - - + + // util - + function compareHex(hexA, hexB){ var numA = parseInt(hexA, 16) var numB = parseInt(hexB, 16) return numA === numB ? 0 : (numA > numB ? 1 : -1 ) } - + function hexToBN(hex){ return new BN(ethUtil.toBuffer(hex)) } - + function containsBlockhash(result) { if (!result) return false if (!result.blockHash) return false const hasNonZeroHash = hexToBN(result.blockHash).gt(new BN(0)) return hasNonZeroHash } - + },{"../util/rpc-cache-utils.js":394,"../util/stoplight.js":396,"./subprovider.js":387,"clone":87,"ethereumjs-util":141,"util":333}],377:[function(require,module,exports){ const inherits = require('util').inherits const extend = require('xtend') const FixtureProvider = require('./fixture.js') const version = require('../package.json').version - + module.exports = DefaultFixtures - + inherits(DefaultFixtures, FixtureProvider) - + function DefaultFixtures(opts) { const self = this opts = opts || {} @@ -62517,7 +62517,7 @@ }, opts) FixtureProvider.call(self, responses) } - + },{"../package.json":375,"./fixture.js":380,"util":333,"xtend":423}],378:[function(require,module,exports){ const fetch = require('cross-fetch') const inherits = require('util').inherits @@ -62528,7 +62528,7 @@ const promiseToCallback = require('promise-to-callback') const createPayload = require('../util/create-payload.js') const Subprovider = require('./subprovider.js') - + const RETRIABLE_ERRORS = [ // ignore server overload errors 'Gateway timeout', @@ -62537,26 +62537,26 @@ // or truncated json responses 'SyntaxError', ] - + module.exports = RpcSource - + inherits(RpcSource, Subprovider) - + function RpcSource (opts) { const self = this self.rpcUrl = opts.rpcUrl self.originHttpHeaderKey = opts.originHttpHeaderKey } - + RpcSource.prototype.handleRequest = function (payload, next, end) { const self = this const originDomain = payload.origin - + // overwrite id to not conflict with other concurrent users const newPayload = createPayload(payload) // remove extra parameter from request delete newPayload.origin - + const reqParams = { method: 'POST', headers: { @@ -62565,11 +62565,11 @@ }, body: JSON.stringify(newPayload) } - + if (self.originHttpHeaderKey && originDomain) { reqParams.headers[self.originHttpHeaderKey] = originDomain } - + retry({ times: 5, interval: 1000, @@ -62587,14 +62587,14 @@ return end(err, result) }) } - + RpcSource.prototype._submitRequest = function (reqParams, cb) { const self = this const targetUrl = self.rpcUrl - + promiseToCallback(fetch(targetUrl, reqParams))((err, res) => { if (err) return cb(err) - + // continue parsing result waterfall([ checkForHttpErrors, @@ -62604,25 +62604,25 @@ asyncify((rawBody) => JSON.parse(rawBody)), parseResponse ], cb) - + function checkForHttpErrors (cb) { // check for errors switch (res.status) { case 405: return cb(new JsonRpcError.MethodNotFound()) - + case 418: return cb(createRatelimitError()) - + case 503: case 504: return cb(createTimeoutError()) - + default: return cb() } } - + function parseResponse (body, cb) { // check for error code if (res.status !== 200) { @@ -62635,25 +62635,25 @@ } }) } - + function isErrorRetriable(err){ const errMsg = err.toString() return RETRIABLE_ERRORS.some(phrase => errMsg.includes(phrase)) } - + function createRatelimitError () { let msg = `Request is being rate limited.` const err = new Error(msg) return new JsonRpcError.InternalError(err) } - + function createTimeoutError () { let msg = `Gateway timeout. The request took too long to process. ` msg += `This can happen when querying logs over too wide a block range.` const err = new Error(msg) return new JsonRpcError.InternalError(err) } - + },{"../util/create-payload.js":391,"./subprovider.js":387,"async/asyncify":20,"async/retry":43,"async/waterfall":44,"cross-fetch":96,"json-rpc-error":189,"promise-to-callback":258,"util":333}],379:[function(require,module,exports){ const async = require('async') const inherits = require('util').inherits @@ -62661,9 +62661,9 @@ const Subprovider = require('./subprovider.js') const Stoplight = require('../util/stoplight.js') const EventEmitter = require('events').EventEmitter - + module.exports = FilterSubprovider - + // handles the following RPC methods: // eth_newBlockFilter // eth_newPendingTransactionFilter @@ -62671,9 +62671,9 @@ // eth_getFilterChanges // eth_uninstallFilter // eth_getFilterLogs - + inherits(FilterSubprovider, Subprovider) - + function FilterSubprovider(opts) { opts = opts || {} const self = this @@ -62687,7 +62687,7 @@ self._ready.go() self.pendingBlockTimeout = opts.pendingBlockTimeout || 4000 self.checkForPendingBlocksActive = false - + // we dont have engine immeditately setTimeout(function(){ // asyncBlockHandlers require locking provider until updates are completed @@ -62704,81 +62704,81 @@ }) }) }) - + } - + FilterSubprovider.prototype.handleRequest = function(payload, next, end){ const self = this switch(payload.method){ - + case 'eth_newBlockFilter': self.newBlockFilter(end) return - + case 'eth_newPendingTransactionFilter': self.newPendingTransactionFilter(end) self.checkForPendingBlocks() return - + case 'eth_newFilter': self.newLogFilter(payload.params[0], end) return - + case 'eth_getFilterChanges': self._ready.await(function(){ self.getFilterChanges(payload.params[0], end) }) return - + case 'eth_getFilterLogs': self._ready.await(function(){ self.getFilterLogs(payload.params[0], end) }) return - + case 'eth_uninstallFilter': self._ready.await(function(){ self.uninstallFilter(payload.params[0], end) }) return - + default: next() return } } - + FilterSubprovider.prototype.newBlockFilter = function(cb) { const self = this - + self._getBlockNumber(function(err, blockNumber){ if (err) return cb(err) - + var filter = new BlockFilter({ blockNumber: blockNumber, }) - + var newBlockHandler = filter.update.bind(filter) self.engine.on('block', newBlockHandler) var destroyHandler = function(){ self.engine.removeListener('block', newBlockHandler) } - + self.filterIndex++ self.filters[self.filterIndex] = filter self.filterDestroyHandlers[self.filterIndex] = destroyHandler - + var hexFilterIndex = intToHex(self.filterIndex) cb(null, hexFilterIndex) }) } - + FilterSubprovider.prototype.newLogFilter = function(opts, cb) { const self = this - + self._getBlockNumber(function(err, blockNumber){ if (err) return cb(err) - + var filter = new LogFilter(opts) var newLogHandler = filter.update.bind(filter) var blockHandler = function(block, cb){ @@ -62788,19 +62788,19 @@ cb() }) } - + self.filterIndex++ self.asyncBlockHandlers[self.filterIndex] = blockHandler self.filters[self.filterIndex] = filter - + var hexFilterIndex = intToHex(self.filterIndex) cb(null, hexFilterIndex) }) } - + FilterSubprovider.prototype.newPendingTransactionFilter = function(cb) { const self = this - + var filter = new PendingTransactionFilter() var newTxHandler = filter.update.bind(filter) var blockHandler = function(block, cb){ @@ -62810,18 +62810,18 @@ cb() }) } - + self.filterIndex++ self.asyncPendingBlockHandlers[self.filterIndex] = blockHandler self.filters[self.filterIndex] = filter - + var hexFilterIndex = intToHex(self.filterIndex) cb(null, hexFilterIndex) } - + FilterSubprovider.prototype.getFilterChanges = function(hexFilterId, cb) { const self = this - + var filterId = Number.parseInt(hexFilterId, 16) var filter = self.filters[filterId] if (!filter) console.warn('FilterSubprovider - no filter with that id:', hexFilterId) @@ -62830,10 +62830,10 @@ filter.clearChanges() cb(null, results) } - + FilterSubprovider.prototype.getFilterLogs = function(hexFilterId, cb) { const self = this - + var filterId = Number.parseInt(hexFilterId, 16) var filter = self.filters[filterId] if (!filter) console.warn('FilterSubprovider - no filter with that id:', hexFilterId) @@ -62856,31 +62856,31 @@ cb(null, results) } } - + FilterSubprovider.prototype.uninstallFilter = function(hexFilterId, cb) { const self = this - + var filterId = Number.parseInt(hexFilterId, 16) var filter = self.filters[filterId] if (!filter) { cb(null, false) return } - + self.filters[filterId].removeAllListeners() - + var destroyHandler = self.filterDestroyHandlers[filterId] delete self.filters[filterId] delete self.asyncBlockHandlers[filterId] delete self.asyncPendingBlockHandlers[filterId] delete self.filterDestroyHandlers[filterId] if (destroyHandler) destroyHandler() - + cb(null, true) } - + // private - + // check for pending blocks FilterSubprovider.prototype.checkForPendingBlocks = function(){ const self = this @@ -62905,7 +62905,7 @@ }) } } - + FilterSubprovider.prototype.onNewPendingBlock = function(block, cb){ const self = this // update filters @@ -62913,13 +62913,13 @@ .map(function(fn){ return fn.bind(null, block) }) async.parallel(updaters, cb) } - + FilterSubprovider.prototype._getBlockNumber = function(cb) { const self = this var blockNumber = bufferToNumberHex(self.engine.currentBlock.number) cb(null, blockNumber) } - + FilterSubprovider.prototype._logsForBlock = function(block, cb) { const self = this var blockNumber = bufferToNumberHex(block.number) @@ -62934,9 +62934,9 @@ if (response.error) return cb(response.error) cb(null, response.result) }) - + } - + FilterSubprovider.prototype._txHashesForBlock = function(block, cb) { const self = this var txs = block.transactions @@ -62951,13 +62951,13 @@ cb(null, results) } } - + // // BlockFilter // - + inherits(BlockFilter, EventEmitter) - + function BlockFilter(opts) { // console.log('BlockFilter - new') const self = this @@ -62967,7 +62967,7 @@ self.blockNumber = opts.blockNumber self.updates = [] } - + BlockFilter.prototype.update = function(block){ // console.log('BlockFilter - update') const self = this @@ -62975,26 +62975,26 @@ self.updates.push(blockHash) self.emit('data', block) } - + BlockFilter.prototype.getChanges = function(){ const self = this var results = self.updates // console.log('BlockFilter - getChanges:', results.length) return results } - + BlockFilter.prototype.clearChanges = function(){ // console.log('BlockFilter - clearChanges') const self = this self.updates = [] } - + // // LogFilter // - + inherits(LogFilter, EventEmitter) - + function LogFilter(opts) { // console.log('LogFilter - new') const self = this @@ -63008,21 +63008,21 @@ self.updates = [] self.allResults = [] } - + LogFilter.prototype.validateLog = function(log){ // console.log('LogFilter - validateLog:', log) const self = this - + // check if block number in bounds: // console.log('LogFilter - validateLog - blockNumber', self.fromBlock, self.toBlock) if (blockTagIsNumber(self.fromBlock) && hexToInt(self.fromBlock) >= hexToInt(log.blockNumber)) return false if (blockTagIsNumber(self.toBlock) && hexToInt(self.toBlock) <= hexToInt(log.blockNumber)) return false - + // address is correct: // console.log('LogFilter - validateLog - address', self.address) if (self.address && !(self.address.map((a) => a.toLowerCase()).includes( log.address.toLowerCase()))) return false - + // topics match: // topics are position-dependant // topics can be nested to represent `or` [[a || b], c] @@ -63044,11 +63044,11 @@ }).length > 0 return topicDoesMatch }, true) - + // console.log('LogFilter - validateLog - '+(topicsMatch ? 'approved!' : 'denied!')+' ==============') return topicsMatch } - + LogFilter.prototype.update = function(logs){ // console.log('LogFilter - update') const self = this @@ -63066,33 +63066,33 @@ self.emit('data', validLogs) } } - + LogFilter.prototype.getChanges = function(){ // console.log('LogFilter - getChanges') const self = this var results = self.updates return results } - + LogFilter.prototype.getAllResults = function(){ // console.log('LogFilter - getAllResults') const self = this var results = self.allResults return results } - + LogFilter.prototype.clearChanges = function(){ // console.log('LogFilter - clearChanges') const self = this self.updates = [] } - + // // PendingTxFilter // - + inherits(PendingTransactionFilter, EventEmitter) - + function PendingTransactionFilter(){ // console.log('PendingTransactionFilter - new') const self = this @@ -63101,12 +63101,12 @@ self.updates = [] self.allResults = [] } - + PendingTransactionFilter.prototype.validateUnique = function(tx){ const self = this return self.allResults.indexOf(tx) === -1 } - + PendingTransactionFilter.prototype.update = function(txs){ // console.log('PendingTransactionFilter - update') const self = this @@ -63124,49 +63124,49 @@ self.emit('data', validTxs) } } - + PendingTransactionFilter.prototype.getChanges = function(){ // console.log('PendingTransactionFilter - getChanges') const self = this var results = self.updates return results } - + PendingTransactionFilter.prototype.getAllResults = function(){ // console.log('PendingTransactionFilter - getAllResults') const self = this var results = self.allResults return results } - + PendingTransactionFilter.prototype.clearChanges = function(){ // console.log('PendingTransactionFilter - clearChanges') const self = this self.updates = [] } - + // util - + function normalizeHex(hexString) { return hexString.slice(0, 2) === '0x' ? hexString : '0x'+hexString } - + function intToHex(value) { return ethUtil.intToHex(value) } - + function hexToInt(hexString) { return Number(hexString) } - + function bufferToHex(buffer) { return '0x'+buffer.toString('hex') } - + function bufferToNumberHex(buffer) { return stripLeadingZero(buffer.toString('hex')) } - + function stripLeadingZero(hexNum) { let stripped = ethUtil.stripHexPrefix(hexNum) while (stripped[0] === '0') { @@ -63174,29 +63174,29 @@ } return `0x${stripped}` } - + function blockTagIsNumber(blockTag){ return blockTag && ['earliest', 'latest', 'pending'].indexOf(blockTag) === -1 } - + function valuesFor(obj){ return Object.keys(obj).map(function(key){ return obj[key] }) } - + },{"../util/stoplight.js":396,"./subprovider.js":387,"async":21,"ethereumjs-util":141,"events":157,"util":333}],380:[function(require,module,exports){ const inherits = require('util').inherits const Subprovider = require('./subprovider.js') - + module.exports = FixtureProvider - + inherits(FixtureProvider, Subprovider) - + function FixtureProvider(staticResponses){ const self = this staticResponses = staticResponses || {} self.staticResponses = staticResponses } - + FixtureProvider.prototype.handleRequest = function(payload, next, end){ const self = this var staticResponse = self.staticResponses[payload.method] @@ -63212,7 +63212,7 @@ next() } } - + },{"./subprovider.js":387,"util":333}],381:[function(require,module,exports){ /* * Emulate 'eth_accounts' / 'eth_sendTransaction' using 'eth_sendRawTransaction' @@ -63221,7 +63221,7 @@ * - getAccounts() -- array of addresses supported * - signTransaction(tx) -- sign a raw transaction object */ - + const waterfall = require('async/waterfall') const parallel = require('async/parallel') const inherits = require('util').inherits @@ -63232,9 +63232,9 @@ const Subprovider = require('./subprovider.js') const estimateGas = require('../util/estimate-gas.js') const hexRegex = /^[0-9A-Fa-f]+$/g - + module.exports = HookedWalletSubprovider - + // handles the following RPC methods: // eth_coinbase // eth_accounts @@ -63246,7 +63246,7 @@ // parity_postTransaction // parity_checkRequest // parity_defaultAccount - + // // Tx Signature Flow // @@ -63262,15 +63262,15 @@ // signTransaction (perform the signature) // publishTransaction (publish signed tx to network) // - - + + inherits(HookedWalletSubprovider, Subprovider) - + function HookedWalletSubprovider(opts){ const self = this // control flow self.nonceLock = Semaphore(1) - + // data lookup if (opts.getAccounts) self.getAccounts = opts.getAccounts // high level override @@ -63292,19 +63292,19 @@ // publish to network if (opts.publishTransaction) self.publishTransaction = opts.publishTransaction } - + HookedWalletSubprovider.prototype.handleRequest = function(payload, next, end){ const self = this self._parityRequests = {} self._parityRequestCount = 0 - + // switch statement is not block scoped // sp we cant repeat var declarations let txParams, msgParams, extraParams let message, address - + switch(payload.method) { - + case 'eth_coinbase': // process normally self.getAccounts(function(err, accounts){ @@ -63313,7 +63313,7 @@ end(null, result) }) return - + case 'eth_accounts': // process normally self.getAccounts(function(err, accounts){ @@ -63321,7 +63321,7 @@ end(null, accounts) }) return - + case 'eth_sendTransaction': txParams = payload.params[0] waterfall([ @@ -63329,7 +63329,7 @@ (cb) => self.processTransaction(txParams, cb), ], end) return - + case 'eth_signTransaction': txParams = payload.params[0] waterfall([ @@ -63337,7 +63337,7 @@ (cb) => self.processSignTransaction(txParams, cb), ], end) return - + case 'eth_sign': // process normally address = payload.params[0] @@ -63354,12 +63354,12 @@ (cb) => self.processMessage(msgParams, cb), ], end) return - + case 'personal_sign': // process normally const first = payload.params[0] const second = payload.params[1] - + // We initially incorrectly ordered these parameters. // To gracefully respect users who adopted this API early, // we are currently gracefully recovering from the wrong param order @@ -63373,14 +63373,14 @@ warning += `and has been corrected automatically. ` warning += `Please switch this param order for smooth behavior in the future.` console.warn(warning) - + address = payload.params[0] message = payload.params[1] } else { message = payload.params[0] address = payload.params[1] } - + // non-standard "extraParams" to be appended to our "msgParams" obj // good place for metadata extraParams = payload.params[2] || {} @@ -63393,7 +63393,7 @@ (cb) => self.processPersonalMessage(msgParams, cb), ], end) return - + case 'personal_ecRecover': message = payload.params[0] let signature = payload.params[1] @@ -63406,7 +63406,7 @@ }) self.recoverPersonalSignature(msgParams, end) return - + case 'eth_signTypedData': // process normally message = payload.params[0] @@ -63421,23 +63421,23 @@ (cb) => self.processTypedMessage(msgParams, cb), ], end) return - + case 'parity_postTransaction': txParams = payload.params[0] self.parityPostTransaction(txParams, end) return - + case 'parity_postSign': address = payload.params[0] message = payload.params[1] self.parityPostSign(address, message, end) return - + case 'parity_checkRequest': const requestId = payload.params[0] self.parityCheckRequest(requestId, end) return - + case 'parity_defaultAccount': self.getAccounts(function(err, accounts){ if (err) return end(err) @@ -63445,27 +63445,27 @@ end(null, account) }) return - + default: next() return - + } } - + // // data lookup // - + HookedWalletSubprovider.prototype.getAccounts = function(cb) { cb(null, []) } - - + + // // "process" high level flow // - + HookedWalletSubprovider.prototype.processTransaction = function(txParams, cb) { const self = this waterfall([ @@ -63474,8 +63474,8 @@ (cb) => self.finalizeAndSubmitTx(txParams, cb), ], cb) } - - + + HookedWalletSubprovider.prototype.processSignTransaction = function(txParams, cb) { const self = this waterfall([ @@ -63484,7 +63484,7 @@ (cb) => self.finalizeTx(txParams, cb), ], cb) } - + HookedWalletSubprovider.prototype.processMessage = function(msgParams, cb) { const self = this waterfall([ @@ -63493,7 +63493,7 @@ (cb) => self.signMessage(msgParams, cb), ], cb) } - + HookedWalletSubprovider.prototype.processPersonalMessage = function(msgParams, cb) { const self = this waterfall([ @@ -63502,7 +63502,7 @@ (cb) => self.signPersonalMessage(msgParams, cb), ], cb) } - + HookedWalletSubprovider.prototype.processTypedMessage = function(msgParams, cb) { const self = this waterfall([ @@ -63511,31 +63511,31 @@ (cb) => self.signTypedMessage(msgParams, cb), ], cb) } - + // // approval // - + HookedWalletSubprovider.prototype.autoApprove = function(txParams, cb) { cb(null, true) } - + HookedWalletSubprovider.prototype.checkApproval = function(type, didApprove, cb) { cb( didApprove ? null : new Error('User denied '+type+' signature.') ) } - + // // parity // - + HookedWalletSubprovider.prototype.parityPostTransaction = function(txParams, cb) { const self = this - + // get next id const count = self._parityRequestCount const reqId = `0x${count.toString(16)}` self._parityRequestCount++ - + self.emitPayload({ method: 'eth_sendTransaction', params: [txParams], @@ -63547,19 +63547,19 @@ const txHash = res.result self._parityRequests[reqId] = txHash }) - + cb(null, reqId) } - - + + HookedWalletSubprovider.prototype.parityPostSign = function(address, message, cb) { const self = this - + // get next id const count = self._parityRequestCount const reqId = `0x${count.toString(16)}` self._parityRequestCount++ - + self.emitPayload({ method: 'eth_sign', params: [address, message], @@ -63571,10 +63571,10 @@ const result = res.result self._parityRequests[reqId] = result }) - + cb(null, reqId) } - + HookedWalletSubprovider.prototype.parityCheckRequest = function(reqId, cb) { const self = this const result = self._parityRequests[reqId] || null @@ -63585,11 +63585,11 @@ // tx sent cb(null, result) } - + // // signature and recovery // - + HookedWalletSubprovider.prototype.recoverPersonalSignature = function(msgParams, cb) { let senderHex try { @@ -63599,11 +63599,11 @@ } cb(null, senderHex) } - + // // validation // - + HookedWalletSubprovider.prototype.validateTransaction = function(txParams, cb){ const self = this // shortcut: undefined sender is invalid @@ -63614,7 +63614,7 @@ cb() }) } - + HookedWalletSubprovider.prototype.validateMessage = function(msgParams, cb){ const self = this if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign message.`)) @@ -63624,7 +63624,7 @@ cb() }) } - + HookedWalletSubprovider.prototype.validatePersonalMessage = function(msgParams, cb){ const self = this if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign personal message.`)) @@ -63636,7 +63636,7 @@ cb() }) } - + HookedWalletSubprovider.prototype.validateTypedMessage = function(msgParams, cb){ if (msgParams.from === undefined) return cb(new Error(`Undefined address - from address required to sign typed data.`)) if (msgParams.data === undefined) return cb(new Error(`Undefined data - message required to sign typed data.`)) @@ -63646,7 +63646,7 @@ cb() }) } - + HookedWalletSubprovider.prototype.validateSender = function(senderAddress, cb){ const self = this // shortcut: undefined sender is invalid @@ -63657,11 +63657,11 @@ cb(null, senderIsValid) }) } - + // // tx helpers // - + HookedWalletSubprovider.prototype.finalizeAndSubmitTx = function(txParams, cb) { const self = this // can only allow one tx to pass through this flow at a time @@ -63678,7 +63678,7 @@ }) }) } - + HookedWalletSubprovider.prototype.finalizeTx = function(txParams, cb) { const self = this // can only allow one tx to pass through this flow at a time @@ -63694,7 +63694,7 @@ }) }) } - + HookedWalletSubprovider.prototype.publishTransaction = function(rawTx, cb) { const self = this self.emitPayload({ @@ -63705,44 +63705,44 @@ cb(null, res.result) }) } - + HookedWalletSubprovider.prototype.fillInTxExtras = function(txParams, cb){ const self = this const address = txParams.from // console.log('fillInTxExtras - address:', address) - + const reqs = {} - + if (txParams.gasPrice === undefined) { // console.log("need to get gasprice") reqs.gasPrice = self.emitPayload.bind(self, { method: 'eth_gasPrice', params: [] }) } - + if (txParams.nonce === undefined) { // console.log("need to get nonce") reqs.nonce = self.emitPayload.bind(self, { method: 'eth_getTransactionCount', params: [address, 'pending'] }) } - + if (txParams.gas === undefined) { // console.log("need to get gas") reqs.gas = estimateGas.bind(null, self.engine, cloneTxParams(txParams)) } - + parallel(reqs, function(err, result) { if (err) return cb(err) // console.log('fillInTxExtras - result:', result) - + const res = {} if (result.gasPrice) res.gasPrice = result.gasPrice.result if (result.nonce) res.nonce = result.nonce.result if (result.gas) res.gas = result.gas - + cb(null, extend(txParams, res)) }) } - + // util - + // we use this to clean any custom params from the txParams function cloneTxParams(txParams){ return { @@ -63755,17 +63755,17 @@ nonce: txParams.nonce, } } - + function toLowerCase(string){ return string.toLowerCase() } - + function resemblesAddress (string) { const fixed = ethUtil.addHexPrefix(string) const isValid = ethUtil.isValidAddress(fixed) return isValid } - + // Returns true if resembles hex data // but definitely not a valid address. function resemblesData (string) { @@ -63773,7 +63773,7 @@ const isValidAddress = ethUtil.isValidAddress(fixed) return !isValidAddress && isValidHex(string) } - + function isValidHex(data) { const isString = typeof data === 'string' if (!isString) return false @@ -63783,75 +63783,75 @@ const isValid = nonPrefixed.match(hexRegex) return isValid } - + function mustProvideInConstructor(methodName) { return function(params, cb) { cb(new Error('ProviderEngine - HookedWalletSubprovider - Must provide "' + methodName + '" fn in constructor options')) } } - + },{"../util/estimate-gas.js":392,"./subprovider.js":387,"async/parallel":42,"async/waterfall":44,"eth-sig-util":136,"ethereumjs-util":141,"semaphore":301,"util":333,"xtend":423}],382:[function(require,module,exports){ const cacheIdentifierForPayload = require('../util/rpc-cache-utils.js').cacheIdentifierForPayload const Subprovider = require('./subprovider.js') - - + + class InflightCacheSubprovider extends Subprovider { - + constructor (opts) { super() this.inflightRequests = {} } - + addEngine (engine) { this.engine = engine } - + handleRequest (req, next, end) { const cacheId = cacheIdentifierForPayload(req, { includeBlockRef: true }) - + // if not cacheable, skip if (!cacheId) return next() - + // check for matching requests let activeRequestHandlers = this.inflightRequests[cacheId] - + if (!activeRequestHandlers) { // create inflight cache for cacheId activeRequestHandlers = [] this.inflightRequests[cacheId] = activeRequestHandlers - + next((err, result, cb) => { // complete inflight for cacheId delete this.inflightRequests[cacheId] activeRequestHandlers.forEach((handler) => handler(err, result)) cb(err, result) }) - + } else { // hit inflight cache for cacheId // setup the response listener activeRequestHandlers.push(end) } - + } } - + module.exports = InflightCacheSubprovider - - + + },{"../util/rpc-cache-utils.js":394,"./subprovider.js":387}],383:[function(require,module,exports){ const createInfuraProvider = require('eth-json-rpc-infura/src/createProvider') const ProviderSubprovider = require('./provider.js') - + class InfuraSubprovider extends ProviderSubprovider { constructor(opts = {}) { const provider = createInfuraProvider(opts) super(provider) } } - + module.exports = InfuraSubprovider - + },{"./provider.js":385,"eth-json-rpc-infura/src/createProvider":129}],384:[function(require,module,exports){ (function (Buffer){ const inherits = require('util').inherits @@ -63859,28 +63859,28 @@ const ethUtil = require('ethereumjs-util') const Subprovider = require('./subprovider.js') const blockTagForPayload = require('../util/rpc-cache-utils').blockTagForPayload - + module.exports = NonceTrackerSubprovider - + // handles the following RPC methods: // eth_getTransactionCount (pending only) // observes the following RPC methods: // eth_sendRawTransaction - - + + inherits(NonceTrackerSubprovider, Subprovider) - + function NonceTrackerSubprovider(opts){ const self = this - + self.nonceCache = {} } - + NonceTrackerSubprovider.prototype.handleRequest = function(payload, next, end){ const self = this - + switch(payload.method) { - + case 'eth_getTransactionCount': var blockTag = blockTagForPayload(payload) var address = payload.params[0].toLowerCase() @@ -63904,7 +63904,7 @@ next() } return - + case 'eth_sendRawTransaction': // allow the request to continue normally next(function(err, result, cb){ @@ -63930,30 +63930,30 @@ cb() }) return - + default: next() return - + } } }).call(this,require("buffer").Buffer) },{"../util/rpc-cache-utils":394,"./subprovider.js":387,"buffer":84,"ethereumjs-tx":140,"ethereumjs-util":141,"util":333}],385:[function(require,module,exports){ const inherits = require('util').inherits const Subprovider = require('./subprovider.js') - + // wraps a provider in a subprovider interface - + module.exports = ProviderSubprovider - + inherits(ProviderSubprovider, Subprovider) - + function ProviderSubprovider(provider){ if (!provider) throw new Error('ProviderSubprovider - no provider specified') if (!provider.sendAsync) throw new Error('ProviderSubprovider - specified provider does not have a sendAsync method') this.provider = provider } - + ProviderSubprovider.prototype.handleRequest = function(payload, next, end){ this.provider.sendAsync(payload, function(err, response) { if (err) return end(err) @@ -63961,37 +63961,37 @@ end(null, response.result) }) } - + },{"./subprovider.js":387,"util":333}],386:[function(require,module,exports){ /* Sanitization Subprovider * For Parity compatibility * removes irregular keys */ - + const inherits = require('util').inherits const Subprovider = require('./subprovider.js') const extend = require('xtend') const ethUtil = require('ethereumjs-util') - + module.exports = SanitizerSubprovider - + inherits(SanitizerSubprovider, Subprovider) - + function SanitizerSubprovider(opts){ const self = this } - + SanitizerSubprovider.prototype.handleRequest = function(payload, next, end){ var txParams = payload.params[0] - + if (typeof txParams === 'object' && !Array.isArray(txParams)) { var sanitized = cloneTxParams(txParams) payload.params[0] = sanitized } - + next() } - + // we use this to clean any custom params from the txParams var permitted = [ 'from', @@ -64006,7 +64006,7 @@ 'address', 'topics', ] - + function cloneTxParams(txParams){ var sanitized = permitted.reduce(function(copy, permitted) { if (permitted in txParams) { @@ -64021,10 +64021,10 @@ } return copy }, {}) - + return sanitized } - + function sanitize(value) { switch (value) { case 'latest': @@ -64041,19 +64041,19 @@ } } } - + },{"./subprovider.js":387,"ethereumjs-util":141,"util":333,"xtend":423}],387:[function(require,module,exports){ const createPayload = require('../util/create-payload.js') - + module.exports = SubProvider - + // this is the base class for a subprovider -- mostly helpers - - + + function SubProvider() { - + } - + SubProvider.prototype.setEngine = function(engine) { const self = this self.engine = engine @@ -64061,11 +64061,11 @@ self.currentBlock = block }) } - + SubProvider.prototype.handleRequest = function(payload, next, end) { throw new Error('Subproviders should override `handleRequest`.') } - + SubProvider.prototype.emitPayload = function(payload, cb){ const self = this self.engine.sendAsync(createPayload(payload), cb) @@ -64076,36 +64076,36 @@ const from = require('../util/rpc-hex-encoding.js') const inherits = require('util').inherits const utils = require('ethereumjs-util') - + function SubscriptionSubprovider(opts) { const self = this - + opts = opts || {} - + EventEmitter.apply(this, Array.prototype.slice.call(arguments)) FilterSubprovider.apply(this, [opts]) - + this.subscriptions = {} } - + inherits(SubscriptionSubprovider, FilterSubprovider) - + // a cheap crack at multiple inheritance // I don't really care if `instanceof EventEmitter` passes... Object.assign(SubscriptionSubprovider.prototype, EventEmitter.prototype) - + // preserve our constructor, though SubscriptionSubprovider.prototype.constructor = SubscriptionSubprovider - + SubscriptionSubprovider.prototype.eth_subscribe = function(payload, cb) { const self = this let createSubscriptionFilter = () => {} let subscriptionType = payload.params[0] - + switch (subscriptionType) { case 'logs': let options = payload.params[1] - + createSubscriptionFilter = self.newLogFilter.bind(self, options) break case 'newPendingTransactions': @@ -64119,18 +64119,18 @@ cb(new Error('unsupported subscription type')) return } - + createSubscriptionFilter(function(err, hexId) { if (err) return cb(err) - + const id = Number.parseInt(hexId, 16) self.subscriptions[id] = subscriptionType - + self.filters[id].on('data', function(results) { if (!Array.isArray(results)) { results = [results] } - + var notificationHandler = self._notificationHandler.bind(self, hexId, subscriptionType) results.forEach(notificationHandler) self.filters[id].clearChanges() @@ -64141,7 +64141,7 @@ cb(null, hexId) }) } - + SubscriptionSubprovider.prototype.eth_unsubscribe = function(payload, cb) { const self = this let hexId = payload.params[0] @@ -64156,14 +64156,14 @@ }) } } - - + + SubscriptionSubprovider.prototype._notificationHandler = function (hexId, subscriptionType, result) { const self = this if (subscriptionType === 'newHeads') { result = self._notificationResultFromBlock(result) } - + // it seems that web3 doesn't expect there to be a separate error event // so we must emit null along with the result object self.emit('data', null, { @@ -64175,7 +64175,7 @@ }, }) } - + SubscriptionSubprovider.prototype._notificationResultFromBlock = function(block) { return { hash: utils.bufferToHex(block.hash), @@ -64196,7 +64196,7 @@ extraData: utils.bufferToHex(block.extraData) } } - + SubscriptionSubprovider.prototype.handleRequest = function(payload, next, end) { switch(payload.method){ case 'eth_subscribe': @@ -64209,9 +64209,9 @@ FilterSubprovider.prototype.handleRequest.apply(this, Array.prototype.slice.call(arguments)) } } - + module.exports = SubscriptionSubprovider - + },{"../util/rpc-hex-encoding.js":395,"./filters.js":379,"ethereumjs-util":141,"events":157,"util":333}],389:[function(require,module,exports){ (function (global){ const Backoff = require('backoff') @@ -64220,15 +64220,15 @@ const WebSocket = global.WebSocket || require('ws') const Subprovider = require('./subprovider') const createPayload = require('../util/create-payload') - + class WebsocketSubprovider extends Subprovider { constructor({ rpcUrl, debug, origin }) { super() - + // inherit from EventEmitter EventEmitter.call(this) - + Object.defineProperties(this, { _backoff: { value: Backoff.exponential({ @@ -64262,100 +64262,100 @@ value: rpcUrl } }) - + this._handleSocketClose = this._handleSocketClose.bind(this) this._handleSocketMessage = this._handleSocketMessage.bind(this) this._handleSocketOpen = this._handleSocketOpen.bind(this) - + // Called when a backoff timeout has finished. Time to try reconnecting. this._backoff.on('ready', () => { this._openSocket() }) - + this._openSocket() } - + handleRequest(payload, next, end) { if (!this._socket || this._socket.readyState !== WebSocket.OPEN) { this._unhandledRequests.push(Array.from(arguments)) this._log('Socket not open. Request queued.') return } - + this._pendingRequests.set(payload.id, [payload, end]) - + const newPayload = createPayload(payload) delete newPayload.origin - + this._socket.send(JSON.stringify(newPayload)) this._log(`Sent: ${newPayload.method} #${newPayload.id}`) } - + _handleSocketClose({ reason, code }) { this._log(`Socket closed, code ${code} (${reason || 'no reason'})`) // If the socket has been open for longer than 5 seconds, reset the backoff if (this._connectTime && Date.now() - this._connectTime > 5000) { this._backoff.reset() } - + this._socket.removeEventListener('close', this._handleSocketClose) this._socket.removeEventListener('message', this._handleSocketMessage) this._socket.removeEventListener('open', this._handleSocketOpen) - + this._socket = null this._backoff.backoff() } - + _handleSocketMessage(message) { let payload - + try { payload = JSON.parse(message.data) } catch (e) { this._log('Received a message that is not valid JSON:', payload) return } - + // check if server-sent notification if (payload.id === undefined) { return this.emit('data', null, payload) } - + // ignore if missing if (!this._pendingRequests.has(payload.id)) { return } - + // retrieve payload + arguments const [originalReq, end] = this._pendingRequests.get(payload.id) this._pendingRequests.delete(payload.id) - + this._log(`Received: ${originalReq.method} #${payload.id}`) - + // forward response if (payload.error) { return end(new Error(payload.error.message)) } end(null, payload.result) } - + _handleSocketOpen() { this._log('Socket open.') this._connectTime = Date.now() - + // Any pending requests need to be resent because our session was lost // and will not get responses for them in our new session. this._pendingRequests.forEach(([payload, end]) => { this._unhandledRequests.push([payload, null, end]) }) this._pendingRequests.clear() - + const unhandledRequests = this._unhandledRequests.splice(0, this._unhandledRequests.length) unhandledRequests.forEach(request => { this.handleRequest.apply(this, request) }) } - + _openSocket() { this._log('Opening socket...') this._socket = new WebSocket(this._url, null, {origin: this._origin}) @@ -64364,29 +64364,29 @@ this._socket.addEventListener('open', this._handleSocketOpen) } } - + // multiple inheritance Object.assign(WebsocketSubprovider.prototype, EventEmitter.prototype) - + module.exports = WebsocketSubprovider - + }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"../util/create-payload":391,"./subprovider":387,"backoff":45,"events":157,"util":333,"ws":55}],390:[function(require,module,exports){ module.exports = assert - + function assert(condition, message) { if (!condition) { throw message || "Assertion failed"; } } - + },{}],391:[function(require,module,exports){ const getRandomId = require('./random-id.js') const extend = require('xtend') - + module.exports = createPayload - - + + function createPayload(data){ return extend({ // defaults @@ -64396,19 +64396,19 @@ // user-specified }, data) } - + },{"./random-id.js":393,"xtend":423}],392:[function(require,module,exports){ const createPayload = require('./create-payload.js') - + module.exports = estimateGas - + /* - + This is a work around for https://github.com/ethereum/go-ethereum/issues/2577 - + */ - - + + function estimateGas(provider, txParams, cb) { provider.sendAsync(createPayload({ method: 'eth_estimateGas', @@ -64419,7 +64419,7 @@ if (err.message === 'no contract code at given address') { return cb(null, '0xcf08') } else { - return cb(err) + return cb(err) } } cb(null, res.result) @@ -64428,10 +64428,10 @@ },{"./create-payload.js":391}],393:[function(require,module,exports){ // gotta keep it within MAX_SAFE_INTEGER const extraDigits = 3 - + module.exports = createRandomId - - + + function createRandomId(){ // 13 time digits var datePart = new Date().getTime()*Math.pow(10, extraDigits) @@ -64442,7 +64442,7 @@ } },{}],394:[function(require,module,exports){ const stringify = require('json-stable-stringify') - + module.exports = { cacheIdentifierForPayload: cacheIdentifierForPayload, canCache: canCache, @@ -64451,45 +64451,45 @@ blockTagParamIndex: blockTagParamIndex, cacheTypeForPayload: cacheTypeForPayload, } - + function cacheIdentifierForPayload(payload, opts = {}){ if (!canCache(payload)) return null const { includeBlockRef } = opts const params = includeBlockRef ? payload.params : paramsWithoutBlockTag(payload) return payload.method + ':' + stringify(params) } - + function canCache(payload){ return cacheTypeForPayload(payload) !== 'never' } - + function blockTagForPayload(payload){ var index = blockTagParamIndex(payload); - + // Block tag param not passed. if (index >= payload.params.length) { return null; } - + return payload.params[index]; } - + function paramsWithoutBlockTag(payload){ var index = blockTagParamIndex(payload); - + // Block tag param not passed. if (index >= payload.params.length) { return payload.params; } - + // eth_getBlockByNumber has the block tag first, then the optional includeTx? param if (payload.method === 'eth_getBlockByNumber') { return payload.params.slice(1); } - + return payload.params.slice(0,index); } - + function blockTagParamIndex(payload){ switch(payload.method) { // blockTag is third param @@ -64510,7 +64510,7 @@ return undefined } } - + function cacheTypeForPayload(payload) { switch (payload.method) { // cache permanently @@ -64531,7 +64531,7 @@ case 'eth_compileSerpent': case 'shh_version': return 'perma' - + // cache until fork case 'eth_getBlockByNumber': case 'eth_getBlockTransactionCountByNumber': @@ -64539,7 +64539,7 @@ case 'eth_getTransactionByBlockNumberAndIndex': case 'eth_getUncleByBlockNumberAndIndex': return 'fork' - + // cache for block case 'eth_gasPrice': case 'eth_blockNumber': @@ -64552,7 +64552,7 @@ case 'eth_getLogs': case 'net_peerCount': return 'block' - + // never cache case 'net_version': case 'net_peerCount': @@ -64589,24 +64589,24 @@ return 'never' } } - + },{"json-stable-stringify":374}],395:[function(require,module,exports){ (function (Buffer){ const ethUtil = require('ethereumjs-util') const assert = require('./assert.js') - + module.exports = { intToQuantityHex: intToQuantityHex, quantityHexToInt: quantityHexToInt, } - + /* * As per https://github.com/ethereum/wiki/wiki/JSON-RPC#hex-value-encoding * Quanities should be represented by the most compact hex representation possible * This means that no leading zeroes are allowed. There helpers make it easy * to convert to and from integers and their compact hex representation */ - + function intToQuantityHex(n){ assert(typeof n === 'number' && n === Math.floor(n), 'intToQuantityHex arg must be an integer') var nHex = ethUtil.toBuffer(n).toString('hex') @@ -64615,7 +64615,7 @@ } return ethUtil.addHexPrefix(nHex) } - + function quantityHexToInt(prefixedQuantityHex) { assert(typeof prefixedQuantityHex === 'string', 'arg to quantityHexToInt must be a string') var quantityHex = ethUtil.stripHexPrefix(prefixedQuantityHex) @@ -64626,35 +64626,35 @@ var buf = new Buffer(quantityHex, 'hex') return ethUtil.bufferToInt(buf) } - + }).call(this,require("buffer").Buffer) },{"./assert.js":390,"buffer":84,"ethereumjs-util":141}],396:[function(require,module,exports){ const EventEmitter = require('events').EventEmitter const inherits = require('util').inherits - + module.exports = Stoplight - - + + inherits(Stoplight, EventEmitter) - + function Stoplight(){ const self = this EventEmitter.call(self) self.isLocked = true } - + Stoplight.prototype.go = function(){ const self = this self.isLocked = false self.emit('unlock') } - + Stoplight.prototype.stop = function(){ const self = this self.isLocked = true self.emit('lock') } - + Stoplight.prototype.await = function(fn){ const self = this if (self.isLocked) { @@ -64676,31 +64676,31 @@ const InfuraSubprovider = require('./subproviders/infura.js') const FetchSubprovider = require('./subproviders/fetch.js') const WebSocketSubprovider = require('./subproviders/websocket.js') - - + + module.exports = ZeroClientProvider - - + + function ZeroClientProvider(opts = {}){ const connectionType = getConnectionType(opts) - + const engine = new ProviderEngine(opts.engineParams) - + // static const staticSubprovider = new DefaultFixture(opts.static) engine.addProvider(staticSubprovider) - + // nonce tracker engine.addProvider(new NonceTrackerSubprovider()) - + // sanitization const sanitizer = new SanitizingSubprovider() engine.addProvider(sanitizer) - + // cache layer const cacheSubprovider = new CacheSubprovider() engine.addProvider(cacheSubprovider) - + // filters + subscriptions // for websockets, only polyfill filters if (connectionType === 'ws') { @@ -64715,11 +64715,11 @@ }) engine.addProvider(filterAndSubsSubprovider) } - + // inflight cache const inflightCache = new InflightCacheSubprovider() engine.addProvider(inflightCache) - + // id mgmt const idmgmtSubprovider = new HookedWalletSubprovider({ // accounts @@ -64744,7 +64744,7 @@ personalRecoverSigner: opts.personalRecoverSigner, }) engine.addProvider(idmgmtSubprovider) - + // data source const dataSubprovider = opts.dataSubprovider || createDataSubprovider(connectionType, opts) // for websockets, forward subscription events through provider @@ -64754,19 +64754,19 @@ }) } engine.addProvider(dataSubprovider) - + // start polling if (!opts.stopped) { engine.start() } - + return engine - + } - + function createDataSubprovider(connectionType, opts) { const { rpcUrl, debug } = opts - + // default to infura if (!connectionType) { return new InfuraSubprovider() @@ -64777,13 +64777,13 @@ if (connectionType === 'ws') { return new WebSocketSubprovider({ rpcUrl, debug }) } - + throw new Error(`ProviderEngine - unrecognized connectionType "${connectionType}"`) } - + function getConnectionType({ rpcUrl }) { if (!rpcUrl) return undefined - + const protocol = rpcUrl.split(':')[0].toLowerCase() switch (protocol) { case 'http': @@ -64796,21 +64796,21 @@ throw new Error(`ProviderEngine - unrecognized protocol in "${rpcUrl}"`) } } - + },{"./index.js":373,"./subproviders/cache.js":376,"./subproviders/default-fixture.js":377,"./subproviders/fetch.js":378,"./subproviders/filters.js":379,"./subproviders/hooked-wallet.js":381,"./subproviders/inflight-cache":382,"./subproviders/infura.js":383,"./subproviders/nonce-tracker.js":384,"./subproviders/sanitizer.js":386,"./subproviders/subscriptions":388,"./subproviders/websocket.js":389}],398:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -64821,13 +64821,13 @@ * Fabian Vogelsteller * @date 2015 */ - + var errors = require('web3-core-helpers').errors; var XHR2 = require('xhr2-cookies').XMLHttpRequest // jshint ignore: line var http = require('http'); var https = require('https'); - - + + /** * HttpProvider should be used to send rpc calls over http */ @@ -64843,28 +64843,28 @@ this.headers = options.headers; this.connected = false; }; - + HttpProvider.prototype._prepareRequest = function(){ var request = new XHR2(); request.nodejsSet({ httpsAgent:this.httpsAgent, httpAgent:this.httpAgent }); - + request.open('POST', this.host, true); request.setRequestHeader('Content-Type','application/json'); request.timeout = this.timeout && this.timeout !== 1 ? this.timeout : 0; request.withCredentials = true; - + if(this.headers) { this.headers.forEach(function(header) { request.setRequestHeader(header.name, header.value); }); } - + return request; }; - + /** * Should be used to make async request * @@ -64875,28 +64875,28 @@ HttpProvider.prototype.send = function (payload, callback) { var _this = this; var request = this._prepareRequest(); - + request.onreadystatechange = function() { if (request.readyState === 4 && request.timeout !== 1) { var result = request.responseText; var error = null; - + try { result = JSON.parse(result); } catch(e) { error = errors.InvalidResponse(request.responseText); } - + _this.connected = true; callback(error, result); } }; - + request.ontimeout = function() { _this.connected = false; callback(errors.ConnectionTimeout(this.timeout)); }; - + try { request.send(JSON.stringify(payload)); } catch(error) { @@ -64904,28 +64904,28 @@ callback(errors.InvalidConnection(this.host)); } }; - + HttpProvider.prototype.disconnect = function () { //NO OP }; - - + + module.exports = HttpProvider; - + },{"http":312,"https":175,"web3-core-helpers":338,"xhr2-cookies":418}],399:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -64934,31 +64934,31 @@ * Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var errors = require('web3-core-helpers').errors; var oboe = require('oboe'); - - + + var IpcProvider = function IpcProvider(path, net) { var _this = this; this.responseCallbacks = {}; this.notificationCallbacks = []; this.path = path; this.connected = false; - + this.connection = net.connect({path: this.path}); - + this.addDefaultEvents(); - + // LISTEN FOR CONNECTION RESPONSES var callback = function(result) { /*jshint maxcomplexity: 6 */ - + var id = null; - + // get the id which matches the returned id if(_.isArray(result)) { result.forEach(function(load){ @@ -64968,21 +64968,21 @@ } else { id = result.id; } - + // notification if(!id && result.method.indexOf('_subscription') !== -1) { _this.notificationCallbacks.forEach(function(callback){ if(_.isFunction(callback)) callback(result); }); - + // fire the callback } else if(_this.responseCallbacks[id]) { _this.responseCallbacks[id](null, result); delete _this.responseCallbacks[id]; } }; - + // use oboe.js for Sockets if (net.constructor.name === 'Socket') { oboe(this.connection) @@ -64993,49 +64993,49 @@ }); } }; - + /** Will add the error and end event to timeout existing calls - + @method addDefaultEvents */ IpcProvider.prototype.addDefaultEvents = function(){ var _this = this; - + this.connection.on('connect', function(){ _this.connected = true; }); - + this.connection.on('close', function(){ _this.connected = false; }); - + this.connection.on('error', function(){ _this._timeout(); }); - + this.connection.on('end', function(){ _this._timeout(); }); - + this.connection.on('timeout', function(){ _this._timeout(); }); }; - - + + /** Will parse the response and make an array out of it. - + NOTE, this exists for backwards compatibility reasons. - + @method _parseResponse @param {String} data */ IpcProvider.prototype._parseResponse = function(data) { var _this = this, returnValues = []; - + // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ @@ -65043,61 +65043,61 @@ .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ .split('|--|'); - + dechunkedData.forEach(function(data){ - + // prepend the last chunk if(_this.lastChunk) data = _this.lastChunk + data; - + var result = null; - + try { result = JSON.parse(data); - + } catch(e) { - + _this.lastChunk = data; - + // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function(){ _this._timeout(); throw errors.InvalidResponse(data); }, 1000 * 15); - + return; } - + // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; - + if(result) returnValues.push(result); }); - + return returnValues; }; - - + + /** Get the adds a callback to the responseCallbacks object, which will be called if a response matching the response Id will arrive. - + @method _addResponseCallback */ IpcProvider.prototype._addResponseCallback = function(payload, callback) { var id = payload.id || payload[0].id; var method = payload.method || payload[0].method; - + this.responseCallbacks[id] = callback; this.responseCallbacks[id].method = method; }; - + /** Timeout all requests when the end/error event is fired - + @method _timeout */ IpcProvider.prototype._timeout = function() { @@ -65108,76 +65108,76 @@ } } }; - + /** Try to reconnect - + @method reconnect */ IpcProvider.prototype.reconnect = function() { this.connection.connect({path: this.path}); }; - - + + IpcProvider.prototype.send = function (payload, callback) { // try reconnect, when connection is gone if(!this.connection.writable) this.connection.connect({path: this.path}); - - + + this.connection.write(JSON.stringify(payload)); this._addResponseCallback(payload, callback); }; - + /** Subscribes to provider events.provider - + @method on @param {String} type 'notification', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.on = function (type, callback) { - + if(typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); - + switch(type){ case 'data': this.notificationCallbacks.push(callback); break; - + // adds error, end, timeout, connect default: this.connection.on(type, callback); break; } }; - + /** Subscribes to provider events.provider - + @method on @param {String} type 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.once = function (type, callback) { - + if(typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); - + this.connection.once(type, callback); }; - + /** Removes event listener - + @method removeListener @param {String} type 'data', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ IpcProvider.prototype.removeListener = function (type, callback) { var _this = this; - + switch(type){ case 'data': this.notificationCallbacks.forEach(function(cb, index){ @@ -65185,16 +65185,16 @@ _this.notificationCallbacks.splice(index, 1); }); break; - + default: this.connection.removeListener(type, callback); break; } }; - + /** Removes all event listeners - + @method removeAllListeners @param {String} type 'data', 'connect', 'error', 'end' or 'data' */ @@ -65203,47 +65203,47 @@ case 'data': this.notificationCallbacks = []; break; - + default: this.connection.removeAllListeners(type); break; } }; - + /** Resets the providers, clears all callbacks - + @method reset */ IpcProvider.prototype.reset = function () { this._timeout(); this.notificationCallbacks = []; - + this.connection.removeAllListeners('error'); this.connection.removeAllListeners('end'); this.connection.removeAllListeners('timeout'); - + this.addDefaultEvents(); }; - + module.exports = IpcProvider; - - + + },{"oboe":239,"underscore":325,"web3-core-helpers":338}],400:[function(require,module,exports){ (function (Buffer){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -65252,12 +65252,12 @@ * Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var _ = require('underscore'); var errors = require('web3-core-helpers').errors; - + var Ws = null; var _btoa = null; var parseURL = null; @@ -65288,18 +65288,18 @@ } } // Default connection ws://localhost:8546 - - - - + + + + var WebsocketProvider = function WebsocketProvider(url, options) { var _this = this; this.responseCallbacks = {}; this.notificationCallbacks = []; - + options = options || {}; this._customTimeout = options.timeout; - + // The w3cwebsocket implementation does not support Basic Auth // username/password in the URL. So generate the basic auth header, and // pass through with any additional headers supplied in constructor @@ -65309,29 +65309,29 @@ if (parsedURL.username && parsedURL.password) { headers.authorization = 'Basic ' + _btoa(parsedURL.username + ':' + parsedURL.password); } - + // Allow a custom client configuration var clientConfig = options.clientConfig || undefined; - + // When all node core implementations that do not have the // WHATWG compatible URL parser go out of service this line can be removed. if (parsedURL.auth) { headers.authorization = 'Basic ' + _btoa(parsedURL.auth); } this.connection = new Ws(url, protocol, undefined, headers, undefined, clientConfig); - + this.addDefaultEvents(); - - + + // LISTEN FOR CONNECTION RESPONSES this.connection.onmessage = function(e) { /*jshint maxcomplexity: 6 */ var data = (typeof e.data === 'string') ? e.data : ''; - + _this._parseResponse(data).forEach(function(result){ - + var id = null; - + // get the id which matches the returned id if(_.isArray(result)) { result.forEach(function(load){ @@ -65341,14 +65341,14 @@ } else { id = result.id; } - + // notification if(!id && result && result.method && result.method.indexOf('_subscription') !== -1) { _this.notificationCallbacks.forEach(function(callback){ if(_.isFunction(callback)) callback(result); }); - + // fire the callback } else if(_this.responseCallbacks[id]) { _this.responseCallbacks[id](null, result); @@ -65356,7 +65356,7 @@ } }); }; - + // make property `connected` which will return the current connection status Object.defineProperty(this, 'connected', { get: function () { @@ -65365,41 +65365,41 @@ enumerable: true, }); }; - + /** Will add the error and end event to timeout existing calls - + @method addDefaultEvents */ WebsocketProvider.prototype.addDefaultEvents = function(){ var _this = this; - + this.connection.onerror = function(){ _this._timeout(); }; - + this.connection.onclose = function(){ _this._timeout(); - + // reset all requests and callbacks _this.reset(); }; - + // this.connection.on('timeout', function(){ // _this._timeout(); // }); }; - + /** Will parse the response and make an array out of it. - + @method _parseResponse @param {String} data */ WebsocketProvider.prototype._parseResponse = function(data) { var _this = this, returnValues = []; - + // DE-CHUNKER var dechunkedData = data .replace(/\}[\n\r]?\{/g,'}|--|{') // }{ @@ -65407,59 +65407,59 @@ .replace(/\}[\n\r]?\[\{/g,'}|--|[{') // }[{ .replace(/\}\][\n\r]?\{/g,'}]|--|{') // }]{ .split('|--|'); - + dechunkedData.forEach(function(data){ - + // prepend the last chunk if(_this.lastChunk) data = _this.lastChunk + data; - + var result = null; - + try { result = JSON.parse(data); - + } catch(e) { - + _this.lastChunk = data; - + // start timeout to cancel all requests clearTimeout(_this.lastChunkTimeout); _this.lastChunkTimeout = setTimeout(function(){ _this._timeout(); throw errors.InvalidResponse(data); }, 1000 * 15); - + return; } - + // cancel timeout and set chunk to null clearTimeout(_this.lastChunkTimeout); _this.lastChunk = null; - + if(result) returnValues.push(result); }); - + return returnValues; }; - - + + /** Adds a callback to the responseCallbacks object, which will be called if a response matching the response Id will arrive. - + @method _addResponseCallback */ WebsocketProvider.prototype._addResponseCallback = function(payload, callback) { var id = payload.id || payload[0].id; var method = payload.method || payload[0].method; - + this.responseCallbacks[id] = callback; this.responseCallbacks[id].method = method; - + var _this = this; - + // schedule triggering the error response if a custom timeout is set if (this._customTimeout) { setTimeout(function () { @@ -65470,10 +65470,10 @@ }, this._customTimeout); } }; - + /** Timeout all requests when the end/error event is fired - + @method _timeout */ WebsocketProvider.prototype._timeout = function() { @@ -65484,18 +65484,18 @@ } } }; - - + + WebsocketProvider.prototype.send = function (payload, callback) { var _this = this; - + if (this.connection.readyState === this.connection.CONNECTING) { setTimeout(function () { _this.send(payload, callback); }, 10); return; } - + // try reconnect, when connection is gone // if(!this.connection.writable) // this.connection.connect({url: this.url}); @@ -65509,58 +65509,58 @@ callback(new Error('connection not open')); return; } - + this.connection.send(JSON.stringify(payload)); this._addResponseCallback(payload, callback); }; - + /** Subscribes to provider events.provider - + @method on @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ WebsocketProvider.prototype.on = function (type, callback) { - + if(typeof callback !== 'function') throw new Error('The second parameter callback must be a function.'); - + switch(type){ case 'data': this.notificationCallbacks.push(callback); break; - + case 'connect': this.connection.onopen = callback; break; - + case 'end': this.connection.onclose = callback; break; - + case 'error': this.connection.onerror = callback; break; - + // default: // this.connection.on(type, callback); // break; } }; - + // TODO add once - + /** Removes event listener - + @method removeListener @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' @param {Function} callback the callback to call */ WebsocketProvider.prototype.removeListener = function (type, callback) { var _this = this; - + switch(type){ case 'data': this.notificationCallbacks.forEach(function(cb, index){ @@ -65568,18 +65568,18 @@ _this.notificationCallbacks.splice(index, 1); }); break; - + // TODO remvoving connect missing - + // default: // this.connection.removeListener(type, callback); // break; } }; - + /** Removes all event listeners - + @method removeAllListeners @param {String} type 'notifcation', 'connect', 'error', 'end' or 'data' */ @@ -65588,66 +65588,66 @@ case 'data': this.notificationCallbacks = []; break; - + // TODO remvoving connect properly missing - + case 'connect': this.connection.onopen = null; break; - + case 'end': this.connection.onclose = null; break; - + case 'error': this.connection.onerror = null; break; - + default: // this.connection.removeAllListeners(type); break; } }; - + /** Resets the providers, clears all callbacks - + @method reset */ WebsocketProvider.prototype.reset = function () { this._timeout(); this.notificationCallbacks = []; - + // this.connection.removeAllListeners('error'); // this.connection.removeAllListeners('end'); // this.connection.removeAllListeners('timeout'); - + this.addDefaultEvents(); }; - + WebsocketProvider.prototype.disconnect = function () { if (this.connection) { this.connection.close(); } }; - + module.exports = WebsocketProvider; - + }).call(this,require("buffer").Buffer) },{"buffer":84,"underscore":325,"url":327,"web3-core-helpers":338,"websocket":408}],401:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -65656,34 +65656,34 @@ * @author Fabian Vogelsteller * @date 2017 */ - + "use strict"; - + var core = require('web3-core'); var Subscriptions = require('web3-core-subscriptions').subscriptions; var Method = require('web3-core-method'); // var formatters = require('web3-core-helpers').formatters; var Net = require('web3-net'); - - + + var Shh = function Shh() { var _this = this; - + // sets _requestmanager core.packageInit(this, arguments); - + // overwrite setProvider var setProvider = this.setProvider; this.setProvider = function () { setProvider.apply(_this, arguments); _this.net.setProvider.apply(_this, arguments); }; - + this.clearSubscriptions = _this._requestManager.clearSubscriptions; - + this.net = new Net(this.currentProvider); - - + + [ new Subscriptions({ name: 'subscribe', @@ -65696,7 +65696,7 @@ } } }), - + new Method({ name: 'getVersion', call: 'shh_version', @@ -65782,7 +65782,7 @@ call: 'shh_deleteSymKey', params: 1 }), - + new Method({ name: 'newMessageFilter', call: 'shh_newMessageFilter', @@ -65798,14 +65798,14 @@ call: 'shh_deleteMessageFilter', params: 1 }), - + new Method({ name: 'post', call: 'shh_post', params: 1, inputFormatter: [null] }), - + new Method({ name: 'unsubscribe', call: 'shh_unsubscribe', @@ -65816,31 +65816,31 @@ method.setRequestManager(_this._requestManager); }); }; - + core.addProviders(Shh); - - - + + + module.exports = Shh; - - - + + + },{"web3-core":348,"web3-core-method":339,"web3-core-subscriptions":345,"web3-net":372}],402:[function(require,module,exports){ arguments[4][154][0].apply(exports,arguments) },{"dup":154}],403:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -65850,16 +65850,16 @@ * @author Fabian Vogelsteller * @date 2017 */ - - + + var _ = require('underscore'); var ethjsUnit = require('ethjs-unit'); var utils = require('./utils.js'); var soliditySha3 = require('./soliditySha3.js'); var randomHex = require('randomhex'); - - - + + + /** * Fires an error in an event emitter and callback and returns the eventemitter * @@ -65872,20 +65872,20 @@ */ var _fireError = function (error, emitter, reject, callback) { /*jshint maxcomplexity: 10 */ - + // add data if given if(_.isObject(error) && !(error instanceof Error) && error.data) { if(_.isObject(error.data) || _.isArray(error.data)) { error.data = JSON.stringify(error.data, null, 2); } - + error = error.message +"\n"+ error.data; } - + if(_.isString(error)) { error = new Error(error); } - + if (_.isFunction(callback)) { callback(error); } @@ -65902,7 +65902,7 @@ reject(error); }, 1); } - + if(emitter && _.isFunction(emitter.emit)) { // emit later, to be able to return emitter setTimeout(function () { @@ -65910,10 +65910,10 @@ emitter.removeAllListeners(); }, 1); } - + return emitter; }; - + /** * Should be used to create full function/event name from json abi * @@ -65925,11 +65925,11 @@ if (_.isObject(json) && json.name && json.name.indexOf('(') !== -1) { return json.name; } - + return json.name + '(' + _flattenTypes(false, json.inputs).join(',') + ')'; }; - - + + /** * Should be used to flatten json abi inputs/outputs into an array of type-representing-strings * @@ -65942,7 +65942,7 @@ { // console.log("entered _flattenTypes. inputs/outputs: " + puts) var types = []; - + puts.forEach(function(param) { if (typeof param.components === 'object') { if (param.type.substring(0, 5) !== 'tuple') { @@ -65970,11 +65970,11 @@ types.push(param.type); } }); - + return types; }; - - + + /** * Should be called to get ascii from it's hex representation * @@ -65985,7 +65985,7 @@ var hexToAscii = function(hex) { if (!utils.isHexStrict(hex)) throw new Error('The parameter must be a valid HEX string.'); - + var str = ""; var i = 0, l = hex.length; if (hex.substring(0, 2) === '0x') { @@ -65995,10 +65995,10 @@ 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 ascii string * @@ -66015,12 +66015,12 @@ var n = code.toString(16); hex += n.length < 2 ? '0' + n : n; } - + return "0x" + hex; }; - - - + + + /** * Returns value of unit in Wei * @@ -66036,7 +66036,7 @@ } return unit; }; - + /** * Takes a number of wei and converts it to any other ether unit. * @@ -66060,14 +66060,14 @@ */ var fromWei = function(number, unit) { unit = getUnitValue(unit); - + if(!utils.isBN(number) && !_.isString(number)) { throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.'); } - + return utils.isBN(number) ? ethjsUnit.fromWei(number, unit) : ethjsUnit.fromWei(number, unit).toString(10); }; - + /** * Takes a number of a unit and converts it to wei. * @@ -66092,17 +66092,17 @@ */ var toWei = function(number, unit) { unit = getUnitValue(unit); - + if(!utils.isBN(number) && !_.isString(number)) { throw new Error('Please pass numbers as strings or BigNumber objects to avoid precision errors.'); } - + return utils.isBN(number) ? ethjsUnit.toWei(number, unit) : ethjsUnit.toWei(number, unit).toString(10); }; - - - - + + + + /** * Converts to a checksum address * @@ -66112,16 +66112,16 @@ */ var toChecksumAddress = function (address) { if (typeof address === 'undefined') return ''; - + if(!/^(0x)?[0-9a-f]{40}$/i.test(address)) throw new Error('Given address "'+ address +'" is not a valid Ethereum address.'); - - - + + + address = address.toLowerCase().replace(/^0x/i,''); var addressHash = utils.sha3(address).replace(/^0x/i,''); var checksumAddress = '0x'; - + for (var i = 0; i < address.length; i++ ) { // If ith character is 9 to f then make it uppercase if (parseInt(addressHash[i], 16) > 7) { @@ -66132,9 +66132,9 @@ } return checksumAddress; }; - - - + + + module.exports = { _fireError: _fireError, _jsonInterfaceMethodToString: _jsonInterfaceMethodToString, @@ -66156,57 +66156,57 @@ toChecksumAddress: toChecksumAddress, toHex: utils.toHex, toBN: utils.toBN, - + bytesToHex: utils.bytesToHex, hexToBytes: utils.hexToBytes, - + hexToNumberString: utils.hexToNumberString, - + hexToNumber: utils.hexToNumber, toDecimal: utils.hexToNumber, // alias - + numberToHex: utils.numberToHex, fromDecimal: utils.numberToHex, // alias - + hexToUtf8: utils.hexToUtf8, hexToString: utils.hexToUtf8, toUtf8: utils.hexToUtf8, - + utf8ToHex: utils.utf8ToHex, stringToHex: utils.utf8ToHex, fromUtf8: utils.utf8ToHex, - + hexToAscii: hexToAscii, toAscii: hexToAscii, asciiToHex: asciiToHex, fromAscii: asciiToHex, - + unitMap: ethjsUnit.unitMap, toWei: toWei, fromWei: fromWei, - + padLeft: utils.leftPad, leftPad: utils.leftPad, padRight: utils.rightPad, rightPad: utils.rightPad, toTwosComplement: utils.toTwosComplement }; - - + + },{"./soliditySha3.js":404,"./utils.js":405,"ethjs-unit":153,"randomhex":274,"underscore":325}],404:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -66215,15 +66215,15 @@ * @author Fabian Vogelsteller * @date 2017 */ - + var _ = require('underscore'); var BN = require('bn.js'); var utils = require('./utils.js'); - - + + var _elementaryName = function (name) { /*jshint maxcomplexity:false */ - + if (name.startsWith('int[')) { return 'int256' + name.slice(3); } else if (name === 'int') { @@ -66243,19 +66243,19 @@ } return name; }; - + // Parse N from type var _parseTypeN = function (type) { var typesize = /^\D+(\d+).*$/.exec(type); return typesize ? parseInt(typesize[1], 10) : null; }; - + // Parse N from type[] var _parseTypeNArray = function (type) { var arraySize = /^\D+\d*\[(\d+)\]$/.exec(type); return arraySize ? parseInt(arraySize[1], 10) : null; }; - + var _parseNumber = function (arg) { var type = typeof arg; if (type === 'string') { @@ -66274,20 +66274,20 @@ throw new Error(arg +' is not a number'); } }; - + var _solidityPack = function (type, value, arraySize) { /*jshint maxcomplexity:false */ - + var size, num; type = _elementaryName(type); - - + + if (type === 'bytes') { - + if (value.replace(/^0x/i,'').length % 2 !== 0) { throw new Error('Invalid bytes characters '+ value.length); } - + return value; } else if (type === 'string') { return utils.utf8ToHex(value); @@ -66299,102 +66299,102 @@ } else { size = 40; } - + if(!utils.isAddress(value)) { throw new Error(value +' is not a valid address, or the checksum is invalid.'); } - + return utils.leftPad(value.toLowerCase(), size); } - + size = _parseTypeN(type); - + if (type.startsWith('bytes')) { - + if(!size) { throw new Error('bytes[] not yet supported in solidity'); } - + // must be 32 byte slices when in an array if(arraySize) { size = 32; } - + if (size < 1 || size > 32 || size < value.replace(/^0x/i,'').length / 2 ) { throw new Error('Invalid bytes' + size +' for '+ value); } - + return utils.rightPad(value, size * 2); } else if (type.startsWith('uint')) { - + if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid uint'+size+' size'); } - + num = _parseNumber(value); if (num.bitLength() > size) { throw new Error('Supplied uint exceeds width: ' + size + ' vs ' + num.bitLength()); } - + if(num.lt(new BN(0))) { throw new Error('Supplied uint '+ num.toString() +' is negative'); } - + return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; } else if (type.startsWith('int')) { - + if ((size % 8) || (size < 8) || (size > 256)) { throw new Error('Invalid int'+size+' size'); } - + num = _parseNumber(value); if (num.bitLength() > size) { throw new Error('Supplied int exceeds width: ' + size + ' vs ' + num.bitLength()); } - + if(num.lt(new BN(0))) { return num.toTwos(size).toString('hex'); } else { return size ? utils.leftPad(num.toString('hex'), size/8 * 2) : num; } - + } else { // FIXME: support all other types throw new Error('Unsupported or invalid type: ' + type); } }; - - + + var _processSoliditySha3Args = function (arg) { /*jshint maxcomplexity:false */ - + if(_.isArray(arg)) { throw new Error('Autodetection of array types is not supported.'); } - + var type, value = ''; var hexArg, arraySize; - + // if type is given if (_.isObject(arg) && (arg.hasOwnProperty('v') || arg.hasOwnProperty('t') || arg.hasOwnProperty('value') || arg.hasOwnProperty('type'))) { type = arg.hasOwnProperty('t') ? arg.t : arg.type; value = arg.hasOwnProperty('v') ? arg.v : arg.value; - + // otherwise try to guess the type } else { - + type = utils.toHex(arg, true); value = utils.toHex(arg); - + if (!type.startsWith('int') && !type.startsWith('uint')) { type = 'bytes'; } } - + if ((type.startsWith('int') || type.startsWith('uint')) && typeof value === 'string' && !/^(-)?0x/i.test(value)) { value = new BN(value); } - + // get the array size if(_.isArray(value)) { arraySize = _parseTypeNArray(type); @@ -66404,8 +66404,8 @@ arraySize = value.length; } } - - + + if (_.isArray(value)) { hexArg = value.map(function (val) { return _solidityPack(type, val, arraySize).toString('hex').replace('0x',''); @@ -66415,9 +66415,9 @@ hexArg = _solidityPack(type, value, arraySize); return hexArg.toString('hex').replace('0x',''); } - + }; - + /** * Hashes solidity values to a sha3 hash using keccak 256 * @@ -66426,34 +66426,34 @@ */ var soliditySha3 = function () { /*jshint maxcomplexity:false */ - + var args = Array.prototype.slice.call(arguments); - + var hexArgs = _.map(args, _processSoliditySha3Args); - + // console.log(args, hexArgs); // console.log('0x'+ hexArgs.join('')); - + return utils.sha3('0x'+ hexArgs.join('')); }; - - + + module.exports = soliditySha3; - + },{"./utils.js":405,"bn.js":402,"underscore":325}],405:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -66462,14 +66462,14 @@ * @author Fabian Vogelsteller * @date 2017 */ - + var _ = require('underscore'); var BN = require('bn.js'); var numberToBN = require('number-to-bn'); var utf8 = require('utf8'); var Hash = require("eth-lib/lib/hash"); - - + + /** * Returns true if object is BN, otherwise false * @@ -66481,7 +66481,7 @@ return object instanceof BN || (object && object.constructor && object.constructor.name === 'BN'); }; - + /** * Returns true if object is BigNumber, otherwise false * @@ -66492,7 +66492,7 @@ var isBigNumber = function (object) { return object && object.constructor && object.constructor.name === 'BigNumber'; }; - + /** * Takes an input and transforms it into an BN * @@ -66507,8 +66507,8 @@ throw new Error(e + ' Given value: "'+ number +'"'); } }; - - + + /** * Takes and input transforms it into BN and if it is negative value, into two's complement * @@ -66519,7 +66519,7 @@ var toTwosComplement = function (number) { return '0x'+ toBN(number).toTwos(256).toString(16, 64); }; - + /** * Checks if the given string is an address * @@ -66539,9 +66539,9 @@ return checkAddressChecksum(address); } }; - - - + + + /** * Checks if the given string is a checksummed address * @@ -66553,7 +66553,7 @@ // Check each case address = address.replace(/^0x/i,''); var addressHash = sha3(address.toLowerCase()).replace(/^0x/i,''); - + for (var i = 0; i < 40; i++ ) { // the nth letter should be uppercase if the nth digit of casemap is 1 if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) { @@ -66562,7 +66562,7 @@ } return true; }; - + /** * Should be called to pad string to expected length * @@ -66575,12 +66575,12 @@ var leftPad = function (string, chars, sign) { var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; string = string.toString(16).replace(/^0x/i,''); - + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; - + return (hasPrefix ? '0x' : '') + new Array(padding).join(sign ? sign : "0") + string; }; - + /** * Should be called to pad string to expected length * @@ -66593,13 +66593,13 @@ var rightPad = function (string, chars, sign) { var hasPrefix = /^0x/i.test(string) || typeof string === 'number'; string = string.toString(16).replace(/^0x/i,''); - + var padding = (chars - string.length + 1 >= 0) ? chars - string.length + 1 : 0; - + return (hasPrefix ? '0x' : '') + string + (new Array(padding).join(sign ? sign : "0")); }; - - + + /** * Should be called to get hex representation (prefixed by 0x) of utf8 string * @@ -66610,13 +66610,13 @@ var utf8ToHex = function(str) { str = utf8.encode(str); var hex = ""; - + // remove \u0000 padding from either side str = str.replace(/^(?:\u0000)*/,''); str = str.split("").reverse().join(""); str = str.replace(/^(?:\u0000)*/,''); str = str.split("").reverse().join(""); - + for(var i = 0; i < str.length; i++) { var code = str.charCodeAt(i); // if (code !== 0) { @@ -66624,10 +66624,10 @@ hex += n.length < 2 ? '0' + n : n; // } } - + return "0x" + hex; }; - + /** * Should be called to get utf8 from it's hex representation * @@ -66638,30 +66638,30 @@ var hexToUtf8 = function(hex) { if (!isHexStrict(hex)) throw new Error('The parameter "'+ hex +'" must be a valid HEX string.'); - + var str = ""; var code = 0; hex = hex.replace(/^0x/i,''); - + // remove 00 padding from either side hex = hex.replace(/^(?:00)*/,''); hex = hex.split("").reverse().join(""); hex = hex.replace(/^(?:00)*/,''); hex = hex.split("").reverse().join(""); - + var l = hex.length; - + for (var i=0; i < l; i+=2) { code = parseInt(hex.substr(i, 2), 16); // if (code !== 0) { str += String.fromCharCode(code); // } } - + return utf8.decode(str); }; - - + + /** * Converts value to it's number representation * @@ -66673,10 +66673,10 @@ if (!value) { return value; } - + return toBN(value).toNumber(); }; - + /** * Converts value to it's decimal representation in string * @@ -66686,11 +66686,11 @@ */ var hexToNumberString = function (value) { if (!value) return value; - + return toBN(value).toString(10); }; - - + + /** * Converts value to it's hex representation * @@ -66702,18 +66702,18 @@ if (_.isNull(value) || _.isUndefined(value)) { return value; } - + if (!isFinite(value) && !isHexStrict(value)) { throw new Error('Given input "'+value+'" is not a number.'); } - + var number = toBN(value); var result = number.toString(16); - + return number.lt(new BN(0)) ? '-0x' + result.substr(1) : '0x' + result; }; - - + + /** * Convert a byte array to a hex string * @@ -66732,7 +66732,7 @@ } return '0x'+ hex.join(""); }; - + /** * Convert a hex string to a byte array * @@ -66744,18 +66744,18 @@ */ var hexToBytes = function(hex) { hex = hex.toString(16); - + if (!isHexStrict(hex)) { throw new Error('Given value "'+ hex +'" is not a valid hex string.'); } - + hex = hex.replace(/^0x/i,''); - + for (var bytes = [], c = 0; c < hex.length; c += 2) bytes.push(parseInt(hex.substr(c, 2), 16)); return bytes; }; - + /** * Auto converts any given value into it's hex representation. * @@ -66768,20 +66768,20 @@ */ var toHex = function (value, returnType) { /*jshint maxcomplexity: false */ - + if (isAddress(value)) { return returnType ? 'address' : '0x'+ value.toLowerCase().replace(/^0x/i,''); } - + if (_.isBoolean(value)) { return returnType ? 'bool' : value ? '0x01' : '0x00'; } - - + + if (_.isObject(value) && !isBigNumber(value) && !isBN(value)) { return returnType ? 'string' : utf8ToHex(JSON.stringify(value)); } - + // if its a negative number, pass it through numberToHex if (_.isString(value)) { if (value.indexOf('-0x') === 0 || value.indexOf('-0X') === 0) { @@ -66792,11 +66792,11 @@ return returnType ? 'string' : utf8ToHex(value); } } - + return returnType ? (value < 0 ? 'int256' : 'uint256') : numberToHex(value); }; - - + + /** * Check if string is HEX, requires a 0x in front * @@ -66807,7 +66807,7 @@ var isHexStrict = function (hex) { return ((_.isString(hex) || _.isNumber(hex)) && /^(-)?0x[0-9a-f]*$/i.test(hex)); }; - + /** * Check if string is HEX * @@ -66818,8 +66818,8 @@ var isHex = function (hex) { return ((_.isString(hex) || _.isNumber(hex)) && /^(-0x|0x)?[0-9a-f]*$/i.test(hex)); }; - - + + /** * Returns true if given string is a valid Ethereum block header bloom. * @@ -66837,7 +66837,7 @@ } return false; }; - + /** * Returns true if given string is a valid log topic. * @@ -66855,8 +66855,8 @@ } return false; }; - - + + /** * Hashes values to a sha3 hash using keccak 256 * @@ -66866,14 +66866,14 @@ * @return {String} the sha3 string */ var SHA3_NULL_S = '0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; - + var sha3 = function (value) { if (isHexStrict(value) && /^0x/i.test((value).toString())) { value = hexToBytes(value); } - + var returnValue = Hash.keccak256(value); // jshint ignore:line - + if(returnValue === SHA3_NULL_S) { return null; } else { @@ -66882,8 +66882,8 @@ }; // expose the under the hood keccak256 sha3._Hash = Hash; - - + + module.exports = { BN: BN, isBN: isBN, @@ -66908,7 +66908,7 @@ toTwosComplement: toTwosComplement, sha3: sha3 }; - + },{"bn.js":402,"eth-lib/lib/hash":134,"number-to-bn":237,"underscore":325,"utf8":329}],406:[function(require,module,exports){ module.exports={ "_from": "web3@1.0.0-beta.36", @@ -66994,21 +66994,21 @@ }, "version": "1.0.0-beta.36" } - + },{}],407:[function(require,module,exports){ /* This file is part of web3.js. - + web3.js is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. - + web3.js is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. - + You should have received a copy of the GNU Lesser General Public License along with web3.js. If not, see . */ @@ -67022,10 +67022,10 @@ * Marian Oancea * @date 2017 */ - + "use strict"; - - + + var version = require('../package.json').version; var core = require('web3-core'); var Eth = require('web3-eth'); @@ -67034,33 +67034,33 @@ var Shh = require('web3-shh'); var Bzz = require('web3-bzz'); var utils = require('web3-utils'); - + var Web3 = function Web3() { var _this = this; - + // sets _requestmanager etc core.packageInit(this, arguments); - + this.version = version; this.utils = utils; - + this.eth = new Eth(this); this.shh = new Shh(this); this.bzz = new Bzz(this); - + // overwrite package setProvider var setProvider = this.setProvider; this.setProvider = function (provider, net) { setProvider.apply(_this, arguments); - + this.eth.setProvider(provider, net); this.shh.setProvider(provider, net); this.bzz.setProvider(provider); - + return true; }; }; - + Web3.version = version; Web3.utils = utils; Web3.modules = { @@ -67070,31 +67070,31 @@ Shh: Shh, Bzz: Bzz }; - + core.addProviders(Web3); - + module.exports = Web3; - - + + },{"../package.json":406,"web3-bzz":335,"web3-core":348,"web3-eth":371,"web3-eth-personal":369,"web3-net":372,"web3-shh":401,"web3-utils":403}],408:[function(require,module,exports){ var _global = (function() { return this || {}; })(); var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; var websocket_version = require('./version'); - - + + /** * Expose a W3C WebSocket class with just one or two arguments. */ function W3CWebSocket(uri, protocols) { var native_instance; - + if (protocols) { native_instance = new NativeWebSocket(uri, protocols); } else { native_instance = new NativeWebSocket(uri); } - + /** * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket * class). Since it is an Object it will be returned as it is when creating an @@ -67111,7 +67111,7 @@ }); }); } - + /** * Module exports. */ @@ -67119,10 +67119,10 @@ 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, 'version' : websocket_version }; - + },{"./version":409}],409:[function(require,module,exports){ module.exports = require('../package.json').version; - + },{"../package.json":410}],410:[function(require,module,exports){ module.exports={ "_from": "git://github.com/frozeman/WebSocket-Node.git#browserifyCompatible", @@ -67217,10 +67217,10 @@ }, "version": "1.0.26" } - + },{}],411:[function(require,module,exports){ var request = require('xhr-request') - + module.exports = function (url, options) { return new Promise(function (resolve, reject) { request(url, options, function (err, data) { @@ -67229,19 +67229,19 @@ }); }); }; - + },{"xhr-request":412}],412:[function(require,module,exports){ var queryString = require('query-string') var setQuery = require('url-set-query') var assign = require('object-assign') var ensureHeader = require('./lib/ensure-header.js') - + // this is replaced in the browser var request = require('./lib/request.js') - + var mimeTypeJson = 'application/json' var noop = function () {} - + module.exports = xhrRequest function xhrRequest (url, opt, cb) { if (!url || typeof url !== 'string') { @@ -67254,13 +67254,13 @@ if (cb && typeof cb !== 'function') { throw new TypeError('expected cb to be undefined or a function') } - + cb = cb || noop opt = opt || {} - + var defaultResponse = opt.json ? 'json' : 'text' opt = assign({ responseType: defaultResponse }, opt) - + var headers = opt.headers || {} var method = (opt.method || 'GET').toUpperCase() var query = opt.query @@ -67270,27 +67270,27 @@ } url = setQuery(url, query) } - + // allow json response if (opt.responseType === 'json') { ensureHeader(headers, 'Accept', mimeTypeJson) } - + // if body content is json if (opt.json && method !== 'GET' && method !== 'HEAD') { ensureHeader(headers, 'Content-Type', mimeTypeJson) opt.body = JSON.stringify(opt.body) } - + opt.method = method opt.url = url opt.headers = headers delete opt.query delete opt.json - + return request(opt, cb) } - + },{"./lib/ensure-header.js":413,"./lib/request.js":415,"object-assign":238,"query-string":266,"url-set-query":326}],413:[function(require,module,exports){ module.exports = ensureHeader function ensureHeader (headers, key, value) { @@ -67299,7 +67299,7 @@ headers[key] = value } } - + },{}],414:[function(require,module,exports){ module.exports = getResponse function getResponse (opt, resp) { @@ -67313,23 +67313,23 @@ rawRequest: resp.rawRequest ? resp.rawRequest : resp } } - + },{}],415:[function(require,module,exports){ var xhr = require('xhr') var normalize = require('./normalize-response') var noop = function () {} - + module.exports = xhrRequest function xhrRequest (opt, cb) { delete opt.uri - + // for better JSON.parse error handling than xhr module var useJson = false if (opt.responseType === 'json') { opt.responseType = 'text' useJson = true } - + var req = xhr(opt, function xhrRequestResult (err, resp, body) { if (useJson && !err) { try { @@ -67339,13 +67339,13 @@ err = e } } - + resp = normalize(opt, resp) if (err) cb(err, null, resp) else cb(err, body, resp) cb = noop }) - + // Patch abort() so that it also calls the callback, but with an error var onabort = req.onabort req.onabort = function () { @@ -67354,23 +67354,23 @@ cb = noop return ret } - + return req } - + },{"./normalize-response":414,"xhr":416}],416:[function(require,module,exports){ "use strict"; var window = require("global/window") var isFunction = require("is-function") var parseHeaders = require("parse-headers") var xtend = require("xtend") - + module.exports = createXHR // Allow use of default import syntax in TypeScript module.exports.default = createXHR; createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest - + forEachArray(["get", "put", "post", "patch", "head", "delete"], function(method) { createXHR[method === "delete" ? "del" : method] = function(uri, options, callback) { options = initParams(uri, options, callback) @@ -67378,23 +67378,23 @@ return _createXHR(options) } }) - + function forEachArray(array, iterator) { for (var i = 0; i < array.length; i++) { iterator(array[i]) } } - + function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } - + function initParams(uri, options, callback) { var params = uri - + if (isFunction(options)) { callback = options if (typeof uri === "string") { @@ -67403,21 +67403,21 @@ } else { params = xtend(options, {uri: uri}) } - + params.callback = callback return params } - + function createXHR(uri, options, callback) { options = initParams(uri, options, callback) return _createXHR(options) } - + function _createXHR(options) { if(typeof options.callback === "undefined"){ throw new Error("callback argument missing") } - + var called = false var callback = function cbOnce(err, response, body){ if(!called){ @@ -67425,32 +67425,32 @@ options.callback(err, response, body) } } - + function readystatechange() { if (xhr.readyState === 4) { setTimeout(loadFunc, 0) } } - + function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined - + if (xhr.response) { body = xhr.response } else { body = xhr.responseText || getXml(xhr) } - + if (isJson) { try { body = JSON.parse(body) } catch (e) {} } - + return body } - + function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ @@ -67459,7 +67459,7 @@ evt.statusCode = 0 return callback(evt, failureResponse) } - + // will load the data & process the response in a special response object function loadFunc() { if (aborted) return @@ -67473,7 +67473,7 @@ } var response = failureResponse var err = null - + if (status !== 0){ response = { body: getBody(), @@ -67491,9 +67491,9 @@ } return callback(err, response, response.body) } - + var xhr = options.xhr || null - + if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() @@ -67501,7 +67501,7 @@ xhr = new createXHR.XMLHttpRequest() } } - + var key var aborted var uri = xhr.url = options.uri || options.url @@ -67519,7 +67519,7 @@ url: uri, rawRequest: xhr } - + if ("json" in options && options.json !== false) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user @@ -67528,7 +67528,7 @@ body = JSON.stringify(options.json === true ? body : options.json) } } - + xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc @@ -67558,7 +67558,7 @@ errorFunc(e) }, options.timeout ) } - + if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ @@ -67568,27 +67568,27 @@ } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } - + if ("responseType" in options) { xhr.responseType = options.responseType } - + if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } - + // Microsoft Edge browser sends "undefined" when send is called with undefined value. // XMLHttpRequest spec says to pass null as body to indicate no body // See https://github.com/naugtur/xhr/issues/100. xhr.send(body || null) - + return xhr - - + + } - + function getXml(xhr) { // xhr.responseXML will throw Exception "InvalidStateError" or "DOMException" // See https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseXML. @@ -67601,12 +67601,12 @@ return xhr.responseXML } } catch (e) {} - + return null } - + function noop() {} - + },{"global/window":160,"is-function":184,"parse-headers":246,"xtend":423}],417:[function(require,module,exports){ "use strict"; var __extends = (this && this.__extends) || (function () { @@ -67652,7 +67652,7 @@ return SyntaxError; }(Error)); exports.SyntaxError = SyntaxError; - + },{}],418:[function(require,module,exports){ "use strict"; function __export(m) { @@ -67662,7 +67662,7 @@ __export(require("./xml-http-request")); var xml_http_request_event_target_1 = require("./xml-http-request-event-target"); exports.XMLHttpRequestEventTarget = xml_http_request_event_target_1.XMLHttpRequestEventTarget; - + },{"./xml-http-request":422,"./xml-http-request-event-target":420}],419:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); @@ -67678,7 +67678,7 @@ return ProgressEvent; }()); exports.ProgressEvent = ProgressEvent; - + },{}],420:[function(require,module,exports){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); @@ -67720,7 +67720,7 @@ return XMLHttpRequestEventTarget; }()); exports.XMLHttpRequestEventTarget = XMLHttpRequestEventTarget; - + },{}],421:[function(require,module,exports){ (function (Buffer){ "use strict"; @@ -67800,7 +67800,7 @@ return XMLHttpRequestUpload; }(xml_http_request_event_target_1.XMLHttpRequestEventTarget)); exports.XMLHttpRequestUpload = XMLHttpRequestUpload; - + }).call(this,require("buffer").Buffer) },{"./xml-http-request-event-target":420,"buffer":84}],422:[function(require,module,exports){ (function (process,Buffer){ @@ -68250,29 +68250,29 @@ XMLHttpRequest.prototype.nodejsHttpAgent = http.globalAgent; XMLHttpRequest.prototype.nodejsHttpsAgent = https.globalAgent; XMLHttpRequest.prototype.nodejsBaseUrl = null; - + }).call(this,require('_process'),require("buffer").Buffer) },{"./errors":417,"./progress-event":419,"./xml-http-request-event-target":420,"./xml-http-request-upload":421,"_process":257,"buffer":84,"cookiejar":88,"http":312,"https":175,"os":240,"url":327}],423:[function(require,module,exports){ module.exports = extend - + var hasOwnProperty = Object.prototype.hasOwnProperty; - + function extend() { var target = {} - + for (var i = 0; i < arguments.length; i++) { var source = arguments[i] - + for (var key in source) { if (hasOwnProperty.call(source, key)) { target[key] = source[key] } } } - + return target } - + },{}],424:[function(require,module,exports){ "use strict"; (function() { @@ -68345,6 +68345,6 @@ }; }(); }()); - + //# sourceURL=/Users/alexvlasov/Blockchain/web3swift/web3swiftJSProxy/wk.bridge.js },{}]},{},[1]); diff --git a/Sources/web3swift/EthereumAPICalls/Ethereum/IEth+Defaults.swift b/Sources/web3swift/EthereumAPICalls/Ethereum/IEth+Defaults.swift index 6c5424689..c2732c66e 100644 --- a/Sources/web3swift/EthereumAPICalls/Ethereum/IEth+Defaults.swift +++ b/Sources/web3swift/EthereumAPICalls/Ethereum/IEth+Defaults.swift @@ -19,7 +19,7 @@ public extension IEth { func estimateGas(for transaction: CodableTransaction) async throws -> BigUInt { try await estimateGas(for: transaction, onBlock: .latest) } - + func estimateGas(for transaction: CodableTransaction, onBlock: BlockNumber) async throws -> BigUInt { let request = APIRequest.estimateGas(transaction, onBlock) return try await APIRequest.sendRequest(with: provider, for: request).result diff --git a/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift b/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift index 46b64c006..c903a6af4 100755 --- a/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift +++ b/Sources/web3swift/HookedFunctions/Web3+BrowserFunctions.swift @@ -19,8 +19,8 @@ extension Web3.BrowserFunctions { } public func getCoinbase() async -> String? { - guard let addresses = await self.getAccounts() else {return nil} - guard addresses.count > 0 else {return nil} + guard let addresses = await self.getAccounts() else { return nil } + guard addresses.count > 0 else { return nil } return addresses[0] } @@ -29,15 +29,15 @@ extension Web3.BrowserFunctions { } public func sign(_ personalMessage: String, account: String, password: String ) -> String? { - guard let data = Data.fromHex(personalMessage) else {return nil} + guard let data = Data.fromHex(personalMessage) else { return nil } return self.sign(data, account: account, password: password) } public func sign(_ personalMessage: Data, account: String, password: String ) -> String? { do { - guard let keystoreManager = self.web3.provider.attachedKeystoreManager else {return nil} - guard let from = EthereumAddress(account, ignoreChecksum: true) else {return nil} - guard let signature = try Web3Signer.signPersonalMessage(personalMessage, keystore: keystoreManager, account: from, password: password) else {return nil} + guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { return nil } + guard let from = EthereumAddress(account, ignoreChecksum: true) else { return nil } + guard let signature = try Web3Signer.signPersonalMessage(personalMessage, keystore: keystoreManager, account: from, password: password) else { return nil } return signature.toHexString().addHexPrefix() } catch { print(error) @@ -46,13 +46,13 @@ extension Web3.BrowserFunctions { } public func personalECRecover(_ personalMessage: String, signature: String) -> String? { - guard let data = Data.fromHex(personalMessage) else {return nil} - guard let sig = Data.fromHex(signature) else {return nil} + guard let data = Data.fromHex(personalMessage) else { return nil } + guard let sig = Data.fromHex(signature) else { return nil } return self.personalECRecover(data, signature: sig) } public func personalECRecover(_ personalMessage: Data, signature: Data) -> String? { - if signature.count != 65 { return nil} + if signature.count != 65 { return nil } let rData = signature[0..<32].bytes let sData = signature[32..<64].bytes var vData = signature[64] @@ -63,9 +63,9 @@ extension Web3.BrowserFunctions { } else if vData >= 35 && vData <= 38 { vData -= 35 } - guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else {return nil} - guard let hash = Utilities.hashPersonalMessage(personalMessage) else {return nil} - guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else {return nil} + guard let signatureData = SECP256K1.marshalSignature(v: vData, r: rData, s: sData) else { return nil } + guard let hash = Utilities.hashPersonalMessage(personalMessage) else { return nil } + guard let publicKey = SECP256K1.recoverPublicKey(hash: hash, signature: signatureData) else { return nil } return Utilities.publicToAddressString(publicKey) } @@ -167,11 +167,11 @@ extension Web3.BrowserFunctions { // public func signTransaction(_ trans: EthereumTransaction, transaction: TransactionOptions, password: String ) async -> String? { // do { // var transaction = trans -// guard let from = transaction.from else {return nil} -// guard let keystoreManager = self.web3.provider.attachedKeystoreManager else {return nil} -// guard let gasPricePolicy = transaction.gasPrice else {return nil} -// guard let gasLimitPolicy = transaction.gasLimit else {return nil} -// guard let noncePolicy = transaction.nonce else {return nil} +// guard let from = transaction.from else { return nil } +// guard let keystoreManager = self.web3.provider.attachedKeystoreManager else { return nil } +// guard let gasPricePolicy = transaction.gasPrice else { return nil } +// guard let gasLimitPolicy = transaction.gasLimit else { return nil } +// guard let noncePolicy = transaction.nonce else { return nil } // switch gasPricePolicy { // case .manual(let gasPrice): // transaction.parameters.gasPrice = gasPrice @@ -200,7 +200,7 @@ extension Web3.BrowserFunctions { // transaction.chainID = self.web3.provider.network?.chainID // } // -// guard let keystore = keystoreManager.walletForAddress(from) else {return nil} +// guard let keystore = keystoreManager.walletForAddress(from) else { return nil } // try Web3Signer.signTX(transaction: &transaction, keystore: keystore, account: from, password: password) // print(transaction) // let signedData = transaction.encode(for: .transaction)?.toHexString().addHexPrefix() diff --git a/Sources/web3swift/Operations/WriteOperation.swift b/Sources/web3swift/Operations/WriteOperation.swift index f1fa366aa..10fd972cb 100755 --- a/Sources/web3swift/Operations/WriteOperation.swift +++ b/Sources/web3swift/Operations/WriteOperation.swift @@ -13,9 +13,9 @@ public class WriteOperation: ReadOperation { // FIXME: Rewrite this to CodableTransaction /// Sends signed or unsigned transaction for write operation. /// - Parameters: - /// - password: Password for the private key in the keystore manager attached to the provider + /// - password: Password for the private key in the keystore manager attached to the provider /// you set to `web3` passed in the initializer. - /// - policies: Determining the behaviour of how transaction attributes like gas limit and + /// - policies: Determining the behaviour of how transaction attributes like gas limit and /// nonce are resolved. Default value is ``Policies/auto``. /// - sendRaw: If set to `true` transaction will be signed and sent using `eth_sendRawTransaction`. /// Otherwise, no signing attempts will take place and the `eth_sendTransaction` RPC will be used instead. diff --git a/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift b/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift index 9c2d5ed01..c00606e59 100644 --- a/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift +++ b/Sources/web3swift/Tokens/ERC1155/Web3+ERC1155.swift @@ -41,9 +41,11 @@ public class ERC1155: IERC1155 { public var abi: String lazy var contract: Web3.Contract = { + // swiftlint:disable force_unwrapping let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) precondition(contract != nil) return contract! + // swiftlint:enable force_unwrapping }() public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1155ABI, transaction: CodableTransaction = .emptyTransaction) { @@ -67,11 +69,11 @@ public class ERC1155: IERC1155 { if self._hasReadProperties { return } - guard contract.contract.address != nil else {return} + guard contract.contract.address != nil else { return } - guard let tokenIdPromise = try await contract.createReadOperation("id")?.callContractMethod() else {return} + guard let tokenIdPromise = try await contract.createReadOperation("id")?.callContractMethod() else { return } - guard let tokenId = tokenIdPromise["0"] as? BigUInt else {return} + guard let tokenId = tokenIdPromise["0"] as? BigUInt else { return } self._tokenId = tokenId self._hasReadProperties = true @@ -94,7 +96,7 @@ public class ERC1155: IERC1155 { let result = try await contract .createReadOperation("balanceOf", parameters: [account, id])! .callContractMethod() - guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let res = result["0"] as? BigUInt else { throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node") } return res } @@ -107,14 +109,14 @@ public class ERC1155: IERC1155 { public func isApprovedForAll(owner: EthereumAddress, operator user: EthereumAddress, scope: Data) async throws -> Bool { let result = try await contract.createReadOperation("isApprovedForAll", parameters: [owner, user, scope])!.callContractMethod() - guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let res = result["0"] as? Bool else { throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node") } return res } public func supportsInterface(interfaceID: String) async throws -> Bool { let result = try await contract.createReadOperation("supportsInterface", parameters: [interfaceID])!.callContractMethod() - guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} + guard let res = result["0"] as? Bool else { throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node") } return res } } diff --git a/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift b/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift index 80a4f796b..91fa18f31 100644 --- a/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift +++ b/Sources/web3swift/Tokens/ERC1376/Web3+ERC1376.swift @@ -365,4 +365,3 @@ extension ERC1376 { } } - diff --git a/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift b/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift index df0874a93..b800f70bd 100644 --- a/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift +++ b/Sources/web3swift/Tokens/ERC1400/Web3+ERC1400.swift @@ -10,49 +10,49 @@ import Web3Core // Security Token Standard protocol IERC1400: IERC20 { - + // Document Management func getDocument(name: Data) async throws -> (String, Data) func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) async throws -> WriteOperation - + // Token Information func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) async throws -> BigUInt func partitionsOf(tokenHolder: EthereumAddress) async throws -> [Data] - + // Transfers func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation - + // Partition Token Transfers func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation - + // Controller Operation func isControllable() async throws -> Bool func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation - + // Operator Management func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) async throws -> WriteOperation func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) async throws -> WriteOperation func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) async throws -> WriteOperation func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) async throws -> WriteOperation - + // Operator Information func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool - + // Token Issuance func isIssuable() async throws -> Bool func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation - + // Token Redemption func redeem(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> WriteOperation func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) async throws -> WriteOperation - + // Transfer Validity func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) @@ -70,9 +70,9 @@ public class ERC1400: IERC1400, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1400ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -84,21 +84,21 @@ public class ERC1400: IERC1400, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -108,16 +108,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -127,16 +127,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -146,23 +146,23 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -172,44 +172,44 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + // ERC1400 methods public func getDocument(name: Data) async throws -> (String, Data) { let result = try await contract.createReadOperation("getDocument", parameters: [name])!.callContractMethod() - + guard let res = result["0"] as? (String, Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setDocument", parameters: [name, uri, documentHash])! return tx } - + public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOfByPartition", parameters: [partition, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func partitionsOf(tokenHolder: EthereumAddress) async throws -> [Data] { let result = try await contract.createReadOperation("partitionsOf", parameters: [tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? [Data] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -219,16 +219,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferWithData", parameters: [to, value, data])! return tx } - + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -238,16 +238,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFromWithData", parameters: [originalOwner, to, value, data])! return tx } - + public func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -257,16 +257,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferByPartition", parameters: [partition, to, value, data])! return tx } - + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -276,23 +276,23 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData])! return tx } - + public func isControllable() async throws -> Bool { let result = try await contract.createReadOperation("isControllable")!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -302,16 +302,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData])! return tx } - + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -321,61 +321,61 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("controllerRedeem", parameters: [tokenHolder, value, data, operatorData])! return tx } - + public func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperator", parameters: [user])! return tx } - + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperator", parameters: [user])! return tx } - + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperatorByPartition", parameters: [partition, user])! return tx } - + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperatorByPartition", parameters: [partition, user])! return tx } - + public func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperator", parameters: [user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperatorForPartition", parameters: [partition, user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func isIssuable() async throws -> Bool { let result = try await contract.createReadOperation("isIssuable")!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -385,16 +385,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("issue", parameters: [tokenHolder, value, data])! return tx } - + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -404,16 +404,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("issueByPartition", parameters: [partition, tokenHolder, value, data])! return tx } - + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -423,16 +423,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeem", parameters: [value, data])! return tx } - + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -442,16 +442,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeemFrom", parameters: [tokenHolder, value, data])! return tx } - + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -461,16 +461,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeemByPartition", parameters: [partition, value, data])! return tx } - + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -480,16 +480,16 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData])! return tx } - + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -497,18 +497,18 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [to, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -516,18 +516,18 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [originalOwner, to, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> ([UInt8], Data, Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -535,14 +535,14 @@ public class ERC1400: IERC1400, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [originalOwner, to, partition, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data, Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } @@ -551,85 +551,85 @@ public class ERC1400: IERC1400, ERC20BaseProperties { extension ERC1400: IERC777 { public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) async throws -> Data { let result = try await contract.createReadOperation("canImplementInterfaceForAddress", parameters: [interfaceHash, addr])!.callContractMethod() - + guard let res = result["0"] as? Data else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getInterfaceImplementer(addr: EthereumAddress, interfaceHash: Data) async throws -> EthereumAddress { let result = try await contract.createReadOperation("getInterfaceImplementer", parameters: [addr, interfaceHash])!.callContractMethod() - + guard let res = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func setInterfaceImplementer(from: EthereumAddress, addr: EthereumAddress, interfaceHash: Data, implementer: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer])! return tx } - + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setManager", parameters: [addr, newManager])! return tx } - + public func interfaceHash(interfaceName: String) async throws -> Data { let result = try await contract.createReadOperation("interfaceHash", parameters: [interfaceName])!.callContractMethod() - + guard let res = result["0"] as? Data else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func updateERC165Cache(from: EthereumAddress, contract: EthereumAddress, interfaceId: [UInt8]) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = self.contract.createWriteOperation("updateERC165Cache", parameters: [contract, interfaceId])! return tx } - + public func supportsInterface(interfaceID: String) async throws -> Bool { let result = try await contract.createReadOperation("supportsInterface", parameters: [interfaceID])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getGranularity() async throws -> BigUInt { let result = try await contract.createReadOperation("granularity")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getDefaultOperators() async throws -> [EthereumAddress] { let result = try await contract.createReadOperation("defaultOperators")!.callContractMethod() - + guard let res = result["0"] as? [EthereumAddress] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperator", parameters: [user])! return tx } - + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperator", parameters: [user])! return tx } - + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperatorFor", parameters: [user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func send(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -639,16 +639,16 @@ extension ERC1400: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("send", parameters: [to, value, data])! return tx } - + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -658,16 +658,16 @@ extension ERC1400: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorSend", parameters: [originalOwner, to, value, data, operatorData])! return tx } - + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -677,16 +677,16 @@ extension ERC1400: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("burn", parameters: [value, data])! return tx } - + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -696,12 +696,12 @@ extension ERC1400: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("burn", parameters: [originalOwner, value, data, operatorData])! return tx } @@ -710,11 +710,11 @@ extension ERC1400: IERC777 { // MARK: - Private extension ERC1400 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift b/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift index ed947f435..ad4ae54b0 100644 --- a/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift +++ b/Sources/web3swift/Tokens/ERC1410/Web3+ERC1410.swift @@ -11,33 +11,33 @@ import Web3Core // Partially Fungible Token Standard protocol IERC1410: IERC20 { - + // Token Information func getBalance(account: EthereumAddress) async throws -> BigUInt func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) async throws -> BigUInt func partitionsOf(tokenHolder: EthereumAddress) async throws -> [Data] func totalSupply() async throws -> BigUInt - + // Token Transfers func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> ([UInt8], Data, Data) - + // Operator Information func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool - + // Operator Management func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) async throws -> WriteOperation func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) async throws -> WriteOperation func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) async throws -> WriteOperation func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) async throws -> WriteOperation - + // Issuance / Redemption func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> WriteOperation func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) async throws -> WriteOperation - + } // FIXME: Rewrite this to CodableTransaction @@ -48,9 +48,9 @@ public class ERC1410: IERC1410, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1410ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -62,21 +62,21 @@ public class ERC1410: IERC1410, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -86,16 +86,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -105,16 +105,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -124,23 +124,23 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -150,31 +150,31 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + // ERC1410 methods public func balanceOfByPartition(partition: Data, tokenHolder: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOfByPartition", parameters: [partition, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func partitionsOf(tokenHolder: EthereumAddress) async throws -> [Data] { let result = try await contract.createReadOperation("partitionsOf", parameters: [tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? [Data] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -184,16 +184,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferByPartition", parameters: [partition, to, value, data])! return tx } - + public func operatorTransferByPartition(partition: Data, from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -203,16 +203,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorTransferByPartition", parameters: [partition, originalOwner, to, value, data, operatorData])! return tx } - + public func canTransferByPartition(originalOwner: EthereumAddress, to: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> ([UInt8], Data, Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -220,56 +220,56 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [originalOwner, to, partition, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data, Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func isOperator(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperator", parameters: [user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func isOperatorForPartition(partition: Data, operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperatorForPartition", parameters: [partition, user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func authorizeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperator", parameters: [user])! return tx } - + public func revokeOperator(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperator", parameters: [user])! return tx } - + public func authorizeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperatorByPartition", parameters: [partition, user])! return tx } - + public func revokeOperatorByPartition(from: EthereumAddress, partition: Data, operator user: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperatorByPartition", parameters: [partition, user])! return tx } - + public func issueByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -279,16 +279,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("issueByPartition", parameters: [partition, tokenHolder, value, data])! return tx } - + public func redeemByPartition(from: EthereumAddress, partition: Data, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -298,16 +298,16 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeemByPartition", parameters: [partition, value, data])! return tx } - + public func operatorRedeemByPartition(from: EthereumAddress, partition: Data, tokenHolder: EthereumAddress, amount: String, operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -317,12 +317,12 @@ public class ERC1410: IERC1410, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorRedeemByPartition", parameters: [partition, tokenHolder, value, operatorData])! return tx } @@ -331,72 +331,72 @@ public class ERC1410: IERC1410, ERC20BaseProperties { extension ERC1410: IERC777 { public func canImplementInterfaceForAddress(interfaceHash: Data, addr: EthereumAddress) async throws -> Data { let result = try await contract.createReadOperation("canImplementInterfaceForAddress", parameters: [interfaceHash, addr])!.callContractMethod() - + guard let res = result["0"] as? Data else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getInterfaceImplementer(addr: EthereumAddress, interfaceHash: Data) async throws -> EthereumAddress { let result = try await contract.createReadOperation("getInterfaceImplementer", parameters: [addr, interfaceHash])!.callContractMethod() - + guard let res = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func setInterfaceImplementer(from: EthereumAddress, addr: EthereumAddress, interfaceHash: Data, implementer: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setInterfaceImplementer", parameters: [addr, interfaceHash, implementer])! return tx } - + public func setManager(from: EthereumAddress, addr: EthereumAddress, newManager: EthereumAddress) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setManager", parameters: [addr, newManager])! return tx } - + public func interfaceHash(interfaceName: String) async throws -> Data { let result = try await contract.createReadOperation("interfaceHash", parameters: [interfaceName])!.callContractMethod() - + guard let res = result["0"] as? Data else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func updateERC165Cache(from: EthereumAddress, contract: EthereumAddress, interfaceId: [UInt8]) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = self.contract.createWriteOperation("updateERC165Cache", parameters: [contract, interfaceId])! return tx } - + public func supportsInterface(interfaceID: String) async throws -> Bool { transaction.callOnBlock = .latest let result = try await contract.createReadOperation("supportsInterface", parameters: [interfaceID])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func authorize(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("authorizeOperator", parameters: [user])! return tx } - + public func revoke(from: EthereumAddress, operator user: EthereumAddress) throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("revokeOperator", parameters: [user])! return tx } - + public func isOperatorFor(operator user: EthereumAddress, tokenHolder: EthereumAddress) async throws -> Bool { let result = try await contract.createReadOperation("isOperatorFor", parameters: [user, tokenHolder])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func send(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -406,16 +406,16 @@ extension ERC1410: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("send", parameters: [to, value, data])! return tx } - + public func operatorSend(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -425,16 +425,16 @@ extension ERC1410: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("operatorSend", parameters: [originalOwner, to, value, data, operatorData])! return tx } - + public func burn(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -444,16 +444,16 @@ extension ERC1410: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("burn", parameters: [value, data])! return tx } - + public func operatorBurn(from: EthereumAddress, amount: String, originalOwner: EthereumAddress, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -463,26 +463,26 @@ extension ERC1410: IERC777 { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("burn", parameters: [originalOwner, value, data, operatorData])! return tx } - + public func getGranularity() async throws -> BigUInt { let result = try await contract.createReadOperation("granularity")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getDefaultOperators() async throws -> [EthereumAddress] { let result = try await contract.createReadOperation("defaultOperators")!.callContractMethod() - + guard let res = result["0"] as? [EthereumAddress] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } @@ -491,11 +491,11 @@ extension ERC1410: IERC777 { // MARK: - Private extension ERC1410 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift b/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift index 3e83074d8..07dba9fc7 100644 --- a/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift +++ b/Sources/web3swift/Tokens/ERC1594/Web3+ERC1594.swift @@ -11,23 +11,23 @@ import Web3Core // Core Security Token Standard protocol IERC1594: IERC20 { - + // Transfers func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation - + // Token Issuance func isIssuable() async throws -> Bool func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation - + // Token Redemption func redeem(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation - + // Transfer Validity func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) - + } // FIXME: Rewrite this to CodableTransaction @@ -38,9 +38,9 @@ public class ERC1594: IERC1594, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1594ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -52,21 +52,21 @@ public class ERC1594: IERC1594, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { updateTransactionAndContract(from: from) // get the decimals manually @@ -75,16 +75,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -94,16 +94,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -113,23 +113,23 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -139,16 +139,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + // ERC1594 public func transferWithData(from: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest @@ -159,16 +159,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferWithData", parameters: [to, value, data])! return tx } - + public func transferFromWithData(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -178,23 +178,23 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFromWithData", parameters: [originalOwner, to, value, data])! return tx } - + public func isIssuable() async throws -> Bool { let result = try await contract.createReadOperation("isIssuable")!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func issue(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -204,16 +204,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("issue", parameters: [tokenHolder, value, data])! return tx } - + public func redeem(from: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -223,16 +223,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeem", parameters: [value, data])! return tx } - + public func redeemFrom(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -242,16 +242,16 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("redeemFrom", parameters: [tokenHolder, value, data])! return tx } - + public func canTransfer(to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -259,18 +259,18 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [to, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func canTransferFrom(originalOwner: EthereumAddress, to: EthereumAddress, amount: String, data: [UInt8]) async throws -> ([UInt8], Data) { // get the decimals manually let callResult = try await contract.createReadOperation("decimals")!.callContractMethod() @@ -278,14 +278,14 @@ public class ERC1594: IERC1594, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let result = try await contract.createReadOperation("canTransfer", parameters: [originalOwner, to, value, data])!.callContractMethod() - + guard let res = result["0"] as? ([UInt8], Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } @@ -294,11 +294,11 @@ public class ERC1594: IERC1594, ERC20BaseProperties { // MARK: - Private extension ERC1594 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift b/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift index e7551fce1..dfc2ed271 100644 --- a/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift +++ b/Sources/web3swift/Tokens/ERC1633/Web3+ERC1633.swift @@ -12,10 +12,10 @@ import Web3Core // Re-Fungible Token Standard (RFT) // FIXME: Rewrite this to CodableTransaction protocol IERC1633: IERC20, IERC165 { - + func parentToken() async throws -> EthereumAddress func parentTokenId() async throws -> BigUInt - + } public class ERC1633: IERC1633, ERC20BaseProperties { @@ -25,9 +25,9 @@ public class ERC1633: IERC1633, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1633ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -39,21 +39,21 @@ public class ERC1633: IERC1633, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -63,16 +63,16 @@ public class ERC1633: IERC1633, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -82,16 +82,16 @@ public class ERC1633: IERC1633, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -101,23 +101,23 @@ public class ERC1633: IERC1633, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -127,47 +127,47 @@ public class ERC1633: IERC1633, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + func parentToken() async throws -> EthereumAddress { let result = try await contract.createReadOperation("parentToken")!.callContractMethod() - + guard let res = result["0"] as? EthereumAddress else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + func parentTokenId() async throws -> BigUInt { let result = try await contract.createReadOperation("parentTokenId")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func supportsInterface(interfaceID: String) async throws -> Bool { let result = try await contract.createReadOperation("supportsInterface", parameters: [interfaceID])!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + } // MARK: - Private extension ERC1633 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift b/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift index 9e0c3fdec..c70ae346d 100644 --- a/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift +++ b/Sources/web3swift/Tokens/ERC1643/Web3+ERC1643.swift @@ -11,13 +11,13 @@ import Web3Core // Document Management Standard protocol IERC1643: IERC20 { - + // Document Management func getDocument(name: Data) async throws -> (String, Data) func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) async throws -> WriteOperation func removeDocument(from: EthereumAddress, name: Data) async throws -> WriteOperation func getAllDocuments() async throws -> [Data] - + } // FIXME: Rewrite this to CodableTransaction @@ -28,9 +28,9 @@ public class ERC1643: IERC1643, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1643ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -42,21 +42,21 @@ public class ERC1643: IERC1643, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -66,16 +66,16 @@ public class ERC1643: IERC1643, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -85,16 +85,16 @@ public class ERC1643: IERC1643, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -104,23 +104,23 @@ public class ERC1643: IERC1643, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -130,39 +130,39 @@ public class ERC1643: IERC1643, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + // ERC1643 methods public func getDocument(name: Data) async throws -> (String, Data) { let result = try await contract.createReadOperation("getDocument", parameters: [name])!.callContractMethod() - + guard let res = result["0"] as? (String, Data) else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func setDocument(from: EthereumAddress, name: Data, uri: String, documentHash: Data) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("setDocument", parameters: [name, uri, documentHash])! return tx } - + public func removeDocument(from: EthereumAddress, name: Data) throws -> WriteOperation { updateTransactionAndContract(from: from) let tx = contract.createWriteOperation("removeDocument", parameters: [name])! return tx } - + public func getAllDocuments() async throws -> [Data] { let result = try await contract.createReadOperation("getAllDocuments")!.callContractMethod() - + guard let res = result["0"] as? [Data] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } @@ -171,12 +171,11 @@ public class ERC1643: IERC1643, ERC20BaseProperties { // MARK: - Private extension ERC1643 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - -} +} diff --git a/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift b/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift index 1acaf69a1..31e5795d8 100644 --- a/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift +++ b/Sources/web3swift/Tokens/ERC1644/Web3+ERC1644.swift @@ -11,12 +11,12 @@ import Web3Core // Controller Token Operation Standard protocol IERC1644: IERC20 { - + // Controller Operation func isControllable() async throws -> Bool func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation - + } // FIXME: Rewrite this to CodableTransaction @@ -27,9 +27,9 @@ public class ERC1644: IERC1644, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc1644ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -41,21 +41,21 @@ public class ERC1644: IERC1644, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -65,16 +65,16 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -84,16 +84,16 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -103,23 +103,23 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -129,24 +129,24 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + // ERC1644 public func isControllable() async throws -> Bool { let result = try await contract.createReadOperation("isControllable")!.callContractMethod() - + guard let res = result["0"] as? Bool else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func controllerTransfer(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -156,16 +156,16 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("controllerTransfer", parameters: [originalOwner, to, value, data, operatorData])! return tx } - + public func controllerRedeem(from: EthereumAddress, tokenHolder: EthereumAddress, amount: String, data: [UInt8], operatorData: [UInt8]) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -175,12 +175,12 @@ public class ERC1644: IERC1644, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("controllerRedeem", parameters: [tokenHolder, value, data, operatorData])! return tx } @@ -189,11 +189,11 @@ public class ERC1644: IERC1644, ERC20BaseProperties { // MARK: - Private extension ERC1644 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Tokens/ERC20/ERC20BaseProperties.swift b/Sources/web3swift/Tokens/ERC20/ERC20BaseProperties.swift index 806a038ee..0d7323ed9 100644 --- a/Sources/web3swift/Tokens/ERC20/ERC20BaseProperties.swift +++ b/Sources/web3swift/Tokens/ERC20/ERC20BaseProperties.swift @@ -1,6 +1,6 @@ // // ERC20BaseProperties.swift -// +// // // Created by Jann Driessen on 21.11.22. // diff --git a/Sources/web3swift/Tokens/ERC20/ERC20BasePropertiesProvider.swift b/Sources/web3swift/Tokens/ERC20/ERC20BasePropertiesProvider.swift index d26e517e5..e786e1517 100644 --- a/Sources/web3swift/Tokens/ERC20/ERC20BasePropertiesProvider.swift +++ b/Sources/web3swift/Tokens/ERC20/ERC20BasePropertiesProvider.swift @@ -1,6 +1,6 @@ // // ERC20BasePropertiesProvider.swift -// +// // // Created by Jann Driessen on 21.11.22. // @@ -8,7 +8,7 @@ import BigInt import Foundation -/// The default implementation of access of common [ERC-20](https://eips.ethereum.org/EIPS/eip-20#methods) properties `name`, `symbol` and `decimals`. +/// The default implementation of access of common [ERC-20](https://eips.ethereum.org/EIPS/eip-20#methods) properties `name`, `symbol` and `decimals`. public final class ERC20BasePropertiesProvider { var name: String? var symbol: String? @@ -21,8 +21,7 @@ public final class ERC20BasePropertiesProvider { } public func readProperties() async throws { - guard !hasReadProperties else { return } - guard contract.contract.address != nil else {return} + guard !hasReadProperties && contract.contract.address != nil else { return } name = try await contract .createReadOperation("name")? .callContractMethod()["0"] as? String diff --git a/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift b/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift index f7db95dd7..db72d3784 100644 --- a/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift +++ b/Sources/web3swift/Tokens/ERC721/Web3+ERC721.swift @@ -63,9 +63,11 @@ public class ERC721: IERC721 { public var address: EthereumAddress lazy var contract: Web3.Contract = { + // swiftlint:disable force_unwrapping let contract = self.web3.contract(Web3.Utils.erc721ABI, at: self.address, abiVersion: 2) precondition(contract != nil) return contract! + // swiftlint:enable force_unwrapping }() public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, transaction: CodableTransaction = .emptyTransaction) { @@ -88,12 +90,12 @@ public class ERC721: IERC721 { if self._hasReadProperties { return } - guard contract.contract.address != nil else {return} + guard contract.contract.address != nil else { return } async let tokenIdPromise = contract.createReadOperation("tokenId")?.callContractMethod() - guard let tokenIdResult = try await tokenIdPromise else {return} - guard let tokenId = tokenIdResult["0"] as? BigUInt else {return} + guard let tokenIdResult = try await tokenIdPromise else { return } + guard let tokenId = tokenIdResult["0"] as? BigUInt else { return } self._tokenId = tokenId self._hasReadProperties = true diff --git a/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift b/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift index bce547e12..8407e446a 100644 --- a/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift +++ b/Sources/web3swift/Tokens/ERC721x/Web3+ERC721x.swift @@ -47,9 +47,11 @@ public class ERC721x: IERC721x { public var abi: String lazy var contract: Web3.Contract = { + // swiftlint:disable force_unwrapping let contract = self.web3.contract(self.abi, at: self.address, abiVersion: 2) precondition(contract != nil) return contract! + // swiftlint:enable force_unwrapping }() public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.erc721xABI, transaction: CodableTransaction = .emptyTransaction) { @@ -73,12 +75,12 @@ public class ERC721x: IERC721x { if self._hasReadProperties { return } - guard contract.contract.address != nil else {return} + guard contract.contract.address != nil else { return } transaction.callOnBlock = .latest - guard let tokenIdPromise = try await contract.createReadOperation("tokenId")?.callContractMethod() else {return} + guard let tokenIdPromise = try await contract.createReadOperation("tokenId")?.callContractMethod() else { return } - guard let tokenId = tokenIdPromise["0"] as? BigUInt else {return} + guard let tokenId = tokenIdPromise["0"] as? BigUInt else { return } self._tokenId = tokenId self._hasReadProperties = true diff --git a/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift b/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift index f7360d913..c5a428c53 100644 --- a/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift +++ b/Sources/web3swift/Tokens/ERC777/Web3+ERC777.swift @@ -318,4 +318,3 @@ extension ERC777 { } } - diff --git a/Sources/web3swift/Tokens/ST20/Web3+ST20.swift b/Sources/web3swift/Tokens/ST20/Web3+ST20.swift index 52f603380..b3688bd9e 100644 --- a/Sources/web3swift/Tokens/ST20/Web3+ST20.swift +++ b/Sources/web3swift/Tokens/ST20/Web3+ST20.swift @@ -13,13 +13,13 @@ import Web3Core protocol IST20: IERC20 { // off-chain hash func tokenDetails() async throws -> [UInt32] - + // transfer, transferFrom must respect the result of verifyTransfer func verifyTransfer(from: EthereumAddress, originalOwner: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation - + // used to create tokens func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) async throws -> WriteOperation - + // Burn function used to burn the securityToken func burn(from: EthereumAddress, amount: String) async throws -> WriteOperation } @@ -34,9 +34,9 @@ public class ST20: IST20, ERC20BaseProperties { public var provider: Web3Provider public var address: EthereumAddress public var abi: String - + public let contract: Web3.Contract - + public init(web3: Web3, provider: Web3Provider, address: EthereumAddress, abi: String = Web3.Utils.st20ABI, transaction: CodableTransaction = .emptyTransaction) { self.web3 = web3 self.provider = provider @@ -48,14 +48,14 @@ public class ST20: IST20, ERC20BaseProperties { contract = web3.contract(abi, at: address)! basePropertiesProvider = ERC20BasePropertiesProvider(contract: contract) } - + func tokenDetails() async throws -> [UInt32] { let result = try await contract.createReadOperation("tokenDetails")!.callContractMethod() - + guard let res = result["0"] as? [UInt32] else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + func verifyTransfer(from: EthereumAddress, originalOwner: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -65,16 +65,16 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("verifyTransfer", parameters: [originalOwner, to, value])! return tx } - + func mint(from: EthereumAddress, investor: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -84,16 +84,16 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("mint", parameters: [investor, value])! return tx } - + public func burn(from: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -103,30 +103,30 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("burn", parameters: [value])! return tx } - + public func getBalance(account: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("balanceOf", parameters: [account])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func getAllowance(originalOwner: EthereumAddress, delegate: EthereumAddress) async throws -> BigUInt { let result = try await contract.createReadOperation("allowance", parameters: [originalOwner, delegate])!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + public func transfer(from: EthereumAddress, to: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -136,16 +136,16 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transfer", parameters: [to, value])! return tx } - + public func transferFrom(from: EthereumAddress, to: EthereumAddress, originalOwner: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -155,16 +155,16 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("transferFrom", parameters: [originalOwner, to, value])! return tx } - + public func setAllowance(from: EthereumAddress, to: EthereumAddress, newAmount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -174,16 +174,16 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(newAmount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("setAllowance", parameters: [to, value])! return tx } - + public func approve(from: EthereumAddress, spender: EthereumAddress, amount: String) async throws -> WriteOperation { transaction.callOnBlock = .latest updateTransactionAndContract(from: from) @@ -193,33 +193,33 @@ public class ST20: IST20, ERC20BaseProperties { guard let dec = callResult["0"], let decTyped = dec as? BigUInt else { throw Web3Error.inputError(desc: "Contract may be not ERC20 compatible, can not get decimals")} decimals = decTyped - + let intDecimals = Int(decimals) guard let value = Utilities.parseToBigUInt(amount, decimals: intDecimals) else { throw Web3Error.inputError(desc: "Can not parse inputted amount") } - + let tx = contract.createWriteOperation("approve", parameters: [spender, value])! return tx } - + public func totalSupply() async throws -> BigUInt { let result = try await contract.createReadOperation("totalSupply")!.callContractMethod() - + guard let res = result["0"] as? BigUInt else {throw Web3Error.processingError(desc: "Failed to get result of expected type from the Ethereum node")} return res } - + } // MARK: - Private extension ST20 { - + private func updateTransactionAndContract(from: EthereumAddress) { transaction.from = from transaction.to = address contract.transaction = transaction } - + } diff --git a/Sources/web3swift/Utils/EIP/EIP4361.swift b/Sources/web3swift/Utils/EIP/EIP4361.swift index 5e445d5eb..0fa9c0161 100644 --- a/Sources/web3swift/Utils/EIP/EIP4361.swift +++ b/Sources/web3swift/Utils/EIP/EIP4361.swift @@ -46,18 +46,18 @@ private let uriPattern = "(([^:?#\\s]+):)?(([^?#\\s]*))?([^?#\\s]*)(\\?([^#\\s]* public final class EIP4361 { public enum EIP4361Field: String { - case domain = "domain" - case address = "address" - case statement = "statement" - case uri = "uri" - case version = "version" - case chainId = "chainId" - case nonce = "nonce" - case issuedAt = "issuedAt" - case expirationTime = "expirationTime" - case notBefore = "notBefore" - case requestId = "requestId" - case resources = "resources" + case domain + case address + case statement + case uri + case version + case chainId + case nonce + case issuedAt + case expirationTime + case notBefore + case requestId + case resources } private static let domain = "(?<\(EIP4361Field.domain.rawValue)>([^?#]*)) wants you to sign in with your Ethereum account:" @@ -77,9 +77,9 @@ public final class EIP4361 { "^\(domain)\(address)\(statementParagraph)\(uri)\(version)\(chainId)\(nonce)\(issuedAt)\(expirationTime)\(notBefore)\(requestId)\(resourcesParagraph)$" } - private static var _eip4361OptionalPattern: String! + private static var _eip4361OptionalPattern: String? private static var eip4361OptionalPattern: String { - guard _eip4361OptionalPattern == nil else { return _eip4361OptionalPattern! } + if let _eip4361OptionalPattern = _eip4361OptionalPattern { return _eip4361OptionalPattern } let domain = "(?<\(EIP4361Field.domain.rawValue)>(.*)) wants you to sign in with your Ethereum account:" let address = "\\n(?<\(EIP4361Field.address.rawValue)>.*)\\n\\n" @@ -106,20 +106,27 @@ public final class EIP4361 { "\(requestId)", "\(resourcesParagraph)$"] - _eip4361OptionalPattern = patternParts.joined() - return _eip4361OptionalPattern! + let eip4361OptionalPattern = patternParts.joined() + _eip4361OptionalPattern = eip4361OptionalPattern + return eip4361OptionalPattern } public static func validate(_ message: String) -> EIP4361ValidationResponse { + // swiftlint:disable force_try let siweConstantMessageRegex = try! NSRegularExpression(pattern: "^\(domain)\\n") guard siweConstantMessageRegex.firstMatch(in: message, range: message.fullNSRange) != nil else { return EIP4361ValidationResponse(isEIP4361: false, eip4361: nil, capturedFields: [:]) } let eip4361Regex = try! NSRegularExpression(pattern: eip4361OptionalPattern) + // swiftlint:enable force_try var capturedFields: [EIP4361Field: String] = [:] for (key, value) in eip4361Regex.captureGroups(string: message) { + /// We are using EIP4361Field.rawValue to create regular expression. + /// These values must decode back from raw representation always. + // swiftlint:disable force_unwrapping capturedFields[.init(rawValue: key)!] = value + // swiftlint:enable force_unwrapping } return EIP4361ValidationResponse(isEIP4361: true, eip4361: EIP4361(message), @@ -153,7 +160,9 @@ public final class EIP4361 { public let resources: [URL]? public init?(_ message: String) { + // swiftlint:disable force_try let eip4361Regex = try! NSRegularExpression(pattern: EIP4361.eip4361Pattern) + // swiftlint:enable force_try let groups = eip4361Regex.captureGroups(string: message) let dateFormatter = ISO8601DateFormatter() dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds] diff --git a/Sources/web3swift/Utils/EIP/EIP67Code.swift b/Sources/web3swift/Utils/EIP/EIP67Code.swift index 38e95b112..9bc7aa013 100755 --- a/Sources/web3swift/Utils/EIP/EIP67Code.swift +++ b/Sources/web3swift/Utils/EIP/EIP67Code.swift @@ -25,7 +25,7 @@ extension Web3 { public var parameters: [(ABI.Element.ParameterType, Any)] public func toString() -> String? { - let encoding = method + "(" + parameters.map({ el -> String in + let encoding = method + "(" + parameters.map { el -> String in if let string = el.1 as? String { return el.0.abiRepresentation + " " + string } else if let number = el.1 as? BigUInt { @@ -36,7 +36,7 @@ extension Web3 { return el.0.abiRepresentation + " " + data.toHexString().addHexPrefix() } return "" - }).joined(separator: ", ") + ")" + }.joined(separator: ", ") + ")" return encoding } } @@ -46,7 +46,7 @@ extension Web3 { } public init? (address: String) { - guard let addr = EthereumAddress(address) else {return nil} + guard let addr = EthereumAddress(address) else { return nil } self.address = addr } @@ -97,32 +97,34 @@ extension Web3 { public struct EIP67CodeParser { public static func parse(_ data: Data) -> EIP67Code? { - guard let string = String(data: data, encoding: .utf8) else {return nil} + guard let string = String(data: data, encoding: .utf8) else { return nil } return parse(string) } public static func parse(_ string: String) -> EIP67Code? { - guard string.hasPrefix("ethereum:") else {return nil} + guard string.hasPrefix("ethereum:") else { return nil } let striped = string.components(separatedBy: "ethereum:") - guard striped.count == 2 else {return nil} - guard let encoding = striped[1].removingPercentEncoding else {return nil} - guard let url = URL.init(string: encoding) else {return nil} - guard let address = EthereumAddress(url.lastPathComponent) else {return nil} + guard striped.count == 2, + let encoding = striped[1].removingPercentEncoding, + let url = URL.init(string: encoding), + let address = EthereumAddress(url.lastPathComponent) else { return nil } var code = EIP67Code(address: address) - guard let components = URLComponents(string: encoding)?.queryItems else {return code} + parseEncodingComponents(&code, encoding) + return code + } + + private static func parseEncodingComponents(_ code: inout EIP67Code, _ encoding: String) { + guard let components = URLComponents(string: encoding)?.queryItems else { return } for comp in components { switch comp.name { case "value": - guard let value = comp.value else {return nil} - guard let val = BigUInt(value, radix: 10) else {return nil} + guard let value = comp.value, let val = BigUInt(value, radix: 10) else { return } code.amount = val case "gas": - guard let value = comp.value else {return nil} - guard let val = BigUInt(value, radix: 10) else {return nil} + guard let value = comp.value, let val = BigUInt(value, radix: 10) else { return } code.gasLimit = val case "data": - guard let value = comp.value else {return nil} - guard let data = Data.fromHex(value) else {return nil} + guard let value = comp.value, let data = Data.fromHex(value) else { return } code.data = EIP67Code.DataType.data(data) case "function": continue @@ -130,7 +132,6 @@ extension Web3 { continue } } - return code } } } diff --git a/Sources/web3swift/Utils/EIP/EIP712.swift b/Sources/web3swift/Utils/EIP/EIP712.swift index 3d7606ebe..e3a4bcb87 100644 --- a/Sources/web3swift/Utils/EIP/EIP712.swift +++ b/Sources/web3swift/Utils/EIP/EIP712.swift @@ -27,7 +27,9 @@ public struct EIP712Domain: EIP712Hashable { public extension EIP712.Address { static var zero: Self { + // swiftlint:disable force_unwrapping EthereumAddress(Data(count: 20))! + // swiftlint:enable force_unwrapping } } diff --git a/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift b/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift index dfcff58f6..f78e0d457 100644 --- a/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift +++ b/Sources/web3swift/Utils/ENS/ENSReverseRegistrar.swift @@ -15,9 +15,11 @@ public extension ENS { public let address: EthereumAddress lazy var contract: Web3.Contract = { + // swiftlint:disable force_unwrapping let contract = self.web3.contract(Web3.Utils.reverseRegistrarABI, at: self.address, abiVersion: 2) precondition(contract != nil) return contract! + // swiftlint:enable force_unwrapping }() lazy var defaultTransaction: CodableTransaction = { @@ -53,7 +55,7 @@ public extension ENS { public func getReverseRecordName(address: EthereumAddress) async throws -> Data { guard let transaction = self.contract.createReadOperation("node", parameters: [address]) else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let name = result["0"] as? Data else { throw Web3Error.processingError(desc: "Can't get answer") } return name } @@ -61,7 +63,7 @@ public extension ENS { public func getDefaultResolver() async throws -> EthereumAddress { guard let transaction = self.contract.createReadOperation("defaultResolver") else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let address = result["0"] as? EthereumAddress else { throw Web3Error.processingError(desc: "Can't get answer") } return address } diff --git a/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift b/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift index 8802d5c33..4c7ef3471 100644 --- a/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift +++ b/Sources/web3swift/Utils/ENS/ETHRegistrarController.swift @@ -13,75 +13,77 @@ public extension ENS { class ETHRegistrarController { public let web3: Web3 public let address: EthereumAddress - + lazy var contract: Web3.Contract = { + // swiftlint:disable force_unwrapping let contract = self.web3.contract(Web3.Utils.ethRegistrarControllerABI, at: self.address, abiVersion: 2) precondition(contract != nil) return contract! + // swiftlint:enable force_unwrapping }() lazy var defaultTransaction: CodableTransaction = { return CodableTransaction.emptyTransaction }() - + public init(web3: Web3, address: EthereumAddress) { self.web3 = web3 self.address = address } - + public func getRentPrice(name: String, duration: UInt) async throws -> BigUInt { guard let transaction = self.contract.createReadOperation("rentPrice", parameters: [name, duration]) else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let price = result["0"] as? BigUInt else { throw Web3Error.processingError(desc: "Can't get answer") } return price } - + public func checkNameValidity(name: String) async throws -> Bool { guard let transaction = self.contract.createReadOperation("valid", parameters: [name]) else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let valid = result["0"] as? Bool else { throw Web3Error.processingError(desc: "Can't get answer") } return valid } - + public func isNameAvailable(name: String) async throws -> Bool { guard let transaction = self.contract.createReadOperation("available", parameters: [name]) else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let available = result["0"] as? Bool else { throw Web3Error.processingError(desc: "Can't get answer") } return available } - + public func calculateCommitmentHash(name: String, owner: EthereumAddress, secret: String) async throws -> Data { guard let transaction = self.contract.createReadOperation("makeCommitment", parameters: [name, owner.address, secret]) else { throw Web3Error.transactionSerializationError } - guard let result = try? await transaction.callContractMethod() else {throw Web3Error.processingError(desc: "Can't call transaction")} + guard let result = try? await transaction.callContractMethod() else { throw Web3Error.processingError(desc: "Can't call transaction") } guard let hash = result["0"] as? Data else { throw Web3Error.processingError(desc: "Can't get answer") } return hash } - + public func sumbitCommitment(from: EthereumAddress, commitment: Data) throws -> WriteOperation { defaultTransaction.from = from defaultTransaction.to = self.address guard let transaction = self.contract.createWriteOperation("commit", parameters: [commitment]) else { throw Web3Error.transactionSerializationError } return transaction } - + public func registerName(from: EthereumAddress, name: String, owner: EthereumAddress, duration: UInt, secret: String, price: String) throws -> WriteOperation { - guard let amount = Utilities.parseToBigUInt(price, units: .ether) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + guard let amount = Utilities.parseToBigUInt(price, units: .ether) else { throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units") } defaultTransaction.value = amount defaultTransaction.from = from defaultTransaction.to = self.address guard let transaction = self.contract.createWriteOperation("register", parameters: [name, owner.address, duration, secret]) else { throw Web3Error.transactionSerializationError } return transaction } - + public func extendNameRegistration(from: EthereumAddress, name: String, duration: UInt32, price: String) throws -> WriteOperation { - guard let amount = Utilities.parseToBigUInt(price, units: .ether) else {throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units")} + guard let amount = Utilities.parseToBigUInt(price, units: .ether) else { throw Web3Error.inputError(desc: "Wrong price: no way for parsing to ether units") } defaultTransaction.value = amount defaultTransaction.from = from defaultTransaction.to = self.address guard let transaction = self.contract.createWriteOperation("renew", parameters: [name, duration]) else { throw Web3Error.transactionSerializationError } return transaction } - + @available(*, message: "Available for only owner") public func withdraw(from: EthereumAddress) throws -> WriteOperation { defaultTransaction.from = from diff --git a/Sources/web3swift/Utils/ENS/NameHash.swift b/Sources/web3swift/Utils/ENS/NameHash.swift index c6e58412e..9c6654a58 100755 --- a/Sources/web3swift/Utils/ENS/NameHash.swift +++ b/Sources/web3swift/Utils/ENS/NameHash.swift @@ -14,12 +14,12 @@ public struct NameHash { } public static func nameHash(_ domain: String) -> Data? { - guard let normalized = NameHash.normalizeDomainName(domain) else {return nil} + guard let normalized = NameHash.normalizeDomainName(domain) else { return nil } return namehash(normalized) } static func namehash(_ name: String) -> Data? { - if name == "" { + if name.isEmpty { return Data(repeating: 0, count: 32) } let parts = name.split(separator: ".") diff --git a/Sources/web3swift/Web3/Web3+Contract.swift b/Sources/web3swift/Web3/Web3+Contract.swift index 7ac561d66..7bf192710 100755 --- a/Sources/web3swift/Web3/Web3+Contract.swift +++ b/Sources/web3swift/Web3/Web3+Contract.swift @@ -33,7 +33,7 @@ extension Web3 { return nil case 2: // TODO: should throw - guard let contract = try? EthereumContract(abiString, at: at) else {return nil} + guard let contract = try? EthereumContract(abiString, at: at) else { return nil } self.contract = contract default: return nil diff --git a/Sources/web3swift/Web3/Web3+EIP1559.swift b/Sources/web3swift/Web3/Web3+EIP1559.swift index 9e0e9de8b..b7a5237f5 100644 --- a/Sources/web3swift/Web3/Web3+EIP1559.swift +++ b/Sources/web3swift/Web3/Web3+EIP1559.swift @@ -140,13 +140,13 @@ public extension Web3 { var mainNetFisrtBlockNumber: BigUInt { switch self { - case .Byzantium: return 4_370_000 - case .Constantinople: return 7_280_000 - case .Istanbul: return 9_069_000 - case .MuirGlacier: return 9_200_000 - case .Berlin: return 12_244_000 - case .London: return 12_965_000 - case .ArrowGlacier: return 13_773_000 + case .Byzantium: return 4_370_000 + case .Constantinople: return 7_280_000 + case .Istanbul: return 9_069_000 + case .MuirGlacier: return 9_200_000 + case .Berlin: return 12_244_000 + case .London: return 12_965_000 + case .ArrowGlacier: return 13_773_000 } } } @@ -156,7 +156,7 @@ public extension Web3 { // to get the block's ChainVersion. if block < MainChainVersion.Constantinople.mainNetFisrtBlockNumber { return .Byzantium - // ~= means included in a given range + // ~= means included in a given range } else if MainChainVersion.Constantinople.mainNetFisrtBlockNumber.. Bool { return lhs.mainNetFisrtBlockNumber < rhs.mainNetFisrtBlockNumber } - } +} extension Block { /// Returns chain version of mainnet block with such number diff --git a/Sources/web3swift/Web3/Web3+EventParser.swift b/Sources/web3swift/Web3/Web3+EventParser.swift index cc4eaa285..8053ec765 100755 --- a/Sources/web3swift/Web3/Web3+EventParser.swift +++ b/Sources/web3swift/Web3/Web3+EventParser.swift @@ -205,7 +205,7 @@ import Web3Core // // let decodedLogs = response.result.compactMap { (log) -> EventParserResult? in // let (n, d) = self.contract.parseEvent(log) -// guard let evName = n, let evData = d else {return nil} +// guard let evName = n, let evData = d else { return nil } // var res = EventParserResult(eventName: evName, transactionReceipt: nil, contractAddress: log.address, decodedResult: evData) // res.eventLog = log // return res diff --git a/Sources/web3swift/Web3/Web3+Eventloop.swift b/Sources/web3swift/Web3/Web3+Eventloop.swift index 258dc97b7..0dffdaa48 100755 --- a/Sources/web3swift/Web3/Web3+Eventloop.swift +++ b/Sources/web3swift/Web3/Web3+Eventloop.swift @@ -9,22 +9,15 @@ extension Web3.Eventloop { // @available(iOS 10.0, *) public func start(_ timeInterval: TimeInterval) { - if self.timer != nil { - self.timer!.suspend() - self.timer = nil - } - - self.timer = RepeatingTimer(timeInterval: timeInterval) - self.timer?.eventHandler = self.runnable - self.timer?.resume() - + timer?.suspend() + timer = RepeatingTimer(timeInterval: timeInterval) + timer?.eventHandler = self.runnable + timer?.resume() } public func stop() { - if self.timer != nil { - self.timer!.suspend() - self.timer = nil - } + timer?.suspend() + timer = nil } func runnable() { @@ -56,9 +49,9 @@ class RepeatingTimer { private lazy var timer: DispatchSourceTimer = { let t = DispatchSource.makeTimerSource() t.schedule(deadline: .now() + self.timeInterval, repeating: self.timeInterval) - t.setEventHandler(handler: { [weak self] in + t.setEventHandler { [weak self] in self?.eventHandler?() - }) + } return t }() diff --git a/Sources/web3swift/Web3/Web3+HttpProvider.swift b/Sources/web3swift/Web3/Web3+HttpProvider.swift index e56243740..a6411552d 100755 --- a/Sources/web3swift/Web3/Web3+HttpProvider.swift +++ b/Sources/web3swift/Web3/Web3+HttpProvider.swift @@ -18,9 +18,18 @@ public class Web3HttpProvider: Web3Provider { let urlSession = URLSession(configuration: config) return urlSession }() - public init?(_ httpProviderURL: URL, network net: Networks?, keystoreManager manager: KeystoreManager? = nil) async { - guard httpProviderURL.scheme == "http" || httpProviderURL.scheme == "https" else { return nil } - url = httpProviderURL + + @available(*, deprecated, message: "Will be removed in Web3Swift v4. Please use `init(url: URL, network: Networks?, keystoreManager: KeystoreManager?)` instead as it will throw an error instead of returning `nil` value.") + public convenience init?(_ httpProviderURL: URL, network net: Networks?, keystoreManager manager: KeystoreManager? = nil) async { + try? await self.init(url: httpProviderURL, network: net, keystoreManager: manager) + } + + public init(url: URL, network net: Networks?, keystoreManager manager: KeystoreManager? = nil) async throws { + guard url.scheme == "http" || url.scheme == "https" else { + throw Web3Error.inputError(desc: "Web3HttpProvider endpoint must have scheme http or https. Given scheme \(url.scheme ?? "none"). \(url.absoluteString)") + } + + self.url = url if let net = net { network = net } else { @@ -29,17 +38,12 @@ public class Web3HttpProvider: Web3Provider { urlRequest.setValue("application/json", forHTTPHeaderField: "Accept") urlRequest.httpMethod = APIRequest.getNetwork.call urlRequest.httpBody = APIRequest.getNetwork.encodedBody - do { - let response: APIResponse = try await APIRequest.send(uRLRequest: urlRequest, with: session) - let network = Networks.fromInt(response.result) - self.network = network - } catch { - return nil - } + let response: APIResponse = try await APIRequest.send(uRLRequest: urlRequest, with: session) + self.network = Networks.fromInt(response.result) } attachedKeystoreManager = manager } - + public init(url: URL, network: Networks, keystoreManager: KeystoreManager? = nil) { self.url = url self.network = network diff --git a/Sources/web3swift/Web3/Web3+InfuraProviders.swift b/Sources/web3swift/Web3/Web3+InfuraProviders.swift index 493d6bc65..7d3d5040f 100755 --- a/Sources/web3swift/Web3/Web3+InfuraProviders.swift +++ b/Sources/web3swift/Web3/Web3+InfuraProviders.swift @@ -8,10 +8,18 @@ import Web3Core /// Custom Web3 HTTP provider of Infura nodes. public final class InfuraProvider: Web3HttpProvider { - public init?(_ net: Networks, accessToken token: String? = nil, keystoreManager manager: KeystoreManager? = nil) async { + + @available(*, deprecated, message: "Will be removed in Web3Swift v4. Please use `init(net: Networks, accessToken: String?, keystoreManager: KeystoreManager?)` instead as it will throw an error instead of returning `nil`.") + public convenience init?(_ net: Networks, accessToken token: String? = nil, keystoreManager manager: KeystoreManager? = nil) async { + try? await self.init(net: net, accessToken: token, keystoreManager: manager) + } + + public init(net: Networks, accessToken token: String? = nil, keystoreManager manager: KeystoreManager? = nil) async throws { var requestURLstring = "https://" + net.name + Constants.infuraHttpScheme requestURLstring += token ?? Constants.infuraToken - let providerURL = URL(string: requestURLstring) - await super.init(providerURL!, network: net, keystoreManager: manager) + guard let providerURL = URL(string: requestURLstring) else { + throw Web3Error.inputError(desc: "URL created with token \(token ?? "Default token - \(Constants.infuraToken)") is not a valid URL: \(requestURLstring)") + } + try await super.init(url: providerURL, network: net, keystoreManager: manager) } } diff --git a/Sources/web3swift/Web3/Web3+Instance.swift b/Sources/web3swift/Web3/Web3+Instance.swift index 5fdd99217..a098e2255 100755 --- a/Sources/web3swift/Web3/Web3+Instance.swift +++ b/Sources/web3swift/Web3/Web3+Instance.swift @@ -27,11 +27,9 @@ public class Web3 { /// Public web3.eth.* namespace. public var eth: IEth { - if ethInstance != nil { - return ethInstance! - } - ethInstance = Web3.Eth(provider: provider) - return ethInstance! + let ethInstance = ethInstance ?? Web3.Eth(provider: provider) + self.ethInstance = ethInstance + return ethInstance } // FIXME: Rewrite this to CodableTransaction @@ -47,11 +45,9 @@ public class Web3 { /// Public web3.personal.* namespace. public var personal: Web3.Personal { - if self.personalInstance != nil { - return self.personalInstance! - } - self.personalInstance = Web3.Personal(provider: self.provider, web3: self) - return self.personalInstance! + let personalInstance = personalInstance ?? Web3.Personal(provider: provider, web3: self) + self.personalInstance = personalInstance + return personalInstance } // FIXME: Rewrite this to CodableTransaction @@ -69,11 +65,9 @@ public class Web3 { /// Public web3.personal.* namespace. public var txPool: Web3.TxPool { - if self.txPoolInstance != nil { - return self.txPoolInstance! - } - self.txPoolInstance = Web3.TxPool(provider: self.provider, web3: self) - return self.txPoolInstance! + let txPoolInstance = txPoolInstance ?? Web3.TxPool(provider: provider, web3: self) + self.txPoolInstance = txPoolInstance + return txPoolInstance } // FIXME: Rewrite this to CodableTransaction @@ -91,11 +85,9 @@ public class Web3 { /// Public web3.wallet.* namespace. public var wallet: Web3.Web3Wallet { - if self.walletInstance != nil { - return self.walletInstance! - } - self.walletInstance = Web3.Web3Wallet(provider: self.provider, web3: self) - return self.walletInstance! + let walletInstance = walletInstance ?? Web3.Web3Wallet(provider: provider, web3: self) + self.walletInstance = walletInstance + return walletInstance } public class Web3Wallet { @@ -112,11 +104,9 @@ public class Web3 { /// Public web3.browserFunctions.* namespace. public var browserFunctions: Web3.BrowserFunctions { - if self.browserFunctionsInstance != nil { - return self.browserFunctionsInstance! - } - self.browserFunctionsInstance = Web3.BrowserFunctions(provider: self.provider, web3: self) - return self.browserFunctionsInstance! + let browserFunctionsInstance = browserFunctionsInstance ?? Web3.BrowserFunctions(provider: provider, web3: self) + self.browserFunctionsInstance = browserFunctionsInstance + return browserFunctionsInstance } // FIXME: Rewrite this to CodableTransaction @@ -134,11 +124,9 @@ public class Web3 { /// Public web3.browserFunctions.* namespace. public var eventLoop: Web3.Eventloop { - if self.eventLoopInstance != nil { - return self.eventLoopInstance! - } - self.eventLoopInstance = Web3.Eventloop(provider: self.provider, web3: self) - return self.eventLoopInstance! + let eventLoopInstance = eventLoopInstance ?? Web3.Eventloop(provider: provider, web3: self) + self.eventLoopInstance = eventLoopInstance + return eventLoopInstance } // FIXME: Rewrite this to CodableTransaction @@ -158,7 +146,6 @@ public class Web3 { var timer: RepeatingTimer? public var monitoredProperties: [MonitoredProperty] = [MonitoredProperty]() - // public var monitoredContracts: [MonitoredContract] = [MonitoredContract]() public var monitoredUserFunctions: [EventLoopRunnableProtocol] = [EventLoopRunnableProtocol]() public init(provider prov: Web3Provider, web3 web3instance: Web3) { provider = prov @@ -166,28 +153,12 @@ public class Web3 { } } -// public typealias AssemblyHookFunction = ((inout CodableTransaction, EthereumContract)) -> Bool -// -// public typealias SubmissionHookFunction = (inout CodableTransaction) -> Bool - public typealias SubmissionResultHookFunction = (TransactionSendingResult) -> Void -// public struct AssemblyHook { -// public var function: AssemblyHookFunction -// } - -// public struct SubmissionHook { -// public var function: SubmissionHookFunction -// } - public struct SubmissionResultHook { public var function: SubmissionResultHookFunction } -// public var preAssemblyHooks: [AssemblyHook] = [AssemblyHook]() -// public var postAssemblyHooks: [AssemblyHook] = [AssemblyHook]() -// -// public var preSubmissionHooks: [SubmissionHook] = [SubmissionHook]() public var postSubmissionHooks: [SubmissionResultHook] = [SubmissionResultHook]() } diff --git a/Sources/web3swift/Web3/Web3+Personal.swift b/Sources/web3swift/Web3/Web3+Personal.swift index f83d328b8..42e21f6f6 100755 --- a/Sources/web3swift/Web3/Web3+Personal.swift +++ b/Sources/web3swift/Web3/Web3+Personal.swift @@ -9,77 +9,64 @@ import Web3Core extension Web3.Personal { - /** - *Locally or remotely sign a message (arbitrary data) with the private key. To avoid potential signing of a transaction the message is first prepended by a special header and then hashed.* - - - parameters: - - message: Message Data - - from: Use a private key that corresponds to this account - - password: Password for account if signing locally - - - returns: - - Result object - - - important: This call is synchronous - - */ + /// Locally or remotely sign a message (arbitrary data) with the private key. + /// To avoid potential signing of a transaction the message is first prepended by a special header and then hashed. + /// - Parameters: + /// - message: raw message as bytes (e.g. UTF-8 bytes of a string); + /// - from: an account whose private key will be used; + /// - password: password to extract private key; + /// - Returns: signed personal message public func signPersonalMessage(message: Data, from: EthereumAddress, password: String) async throws -> Data { - let result = try await self.signPersonal(message: message, from: from, password: password) + let result = try await signPersonal(message: message, from: from, password: password) return result } - /** - *Unlock an account on the remote node to be able to send transactions and sign messages.* - - - parameters: - - account: EthereumAddress of the account to unlock - - password: Password to use for the account - - seconds: Time interval before automatic account lock by Ethereum node - - - returns: - - Result object - - - important: This call is synchronous. Does nothing if private keys are stored locally. - - */ + /// Unlock an account on the remote node to be able to send transactions and sign messages. + /// - Parameters: + /// - account: EthereumAddress of the account to unlock + /// - password: Password for the account + /// - seconds: Time interval before automatic account lock by Ethereum node. Default 300 + /// - Returns: `true` if account was unlocked. public func unlockAccount(account: EthereumAddress, password: String, seconds: UInt = 300) async throws -> Bool { - let result = try await self.unlock(account: account, password: password) + let result = try await unlock(account: account, password: password) return result } - /** - *Recovers a signer of some message. Message is first prepended by special prefix (check the "signPersonalMessage" method description) and then hashed.* - - - parameters: - - personalMessage: Message Data - - signature: Serialized signature, 65 bytes - - - returns: - - Result object + /// Recovers a signer of some personal message. Message will be first prepended by special prefix + /// (check the "signPersonalMessage" method description) and then hashed before the recovery attempt. + /// + /// If you have a hash instead of a message use ``Web3/Personal/recoverAddress(hash:signature:)`` + /// + /// - Parameters: + /// - message: raw personal message as bytes (e.g. UTF-8 bytes of a string); + /// - signature: signature that is the result of signing the `personalMessage`; + /// - Returns: address of the signer or `nil`. + public func recoverAddress(message: Data, signature: Data) -> EthereumAddress? { + Utilities.personalECRecover(message, signature: signature) + } - */ + @available(*, deprecated, message: "Will be removed in Web3Swift v4. Please, use `func recoverAddress(message: Data, signature: Data) -> EthereumAddress?` instead.") public func ecrecover(personalMessage: Data, signature: Data) throws -> EthereumAddress { - guard let recovered = Utilities.personalECRecover(personalMessage, signature: signature) else { - throw Web3Error.dataError + if let address = recoverAddress(message: personalMessage, signature: signature) { + return address } - return recovered + throw Web3Error.dataError } - /** - *Recovers a signer of some hash. Checking what is under this hash is on behalf of the user.* - - - parameters: - - hash: Signed hash - - signature: Serialized signature, 65 bytes - - - returns: - - Result object + /// Recovers a signer of some hash. + /// - Parameters: + /// - hash: some hash, e.g. hashed personal message; + /// - signature: 65 bytes serialized signature; + /// - Returns: address of the signer or `nil`. + public func recoverAddress(hash: Data, signature: Data) -> EthereumAddress? { + Utilities.hashECRecover(hash: hash, signature: signature) + } - */ + @available(*, deprecated, message: "Will be removed in Web3Swift v4. Please, use `func recoverAddress(hash: Data, signature: Data) -> EthereumAddress?` instead.") public func ecrecover(hash: Data, signature: Data) throws -> EthereumAddress { - guard let recovered = Utilities.hashECRecover(hash: hash, signature: signature) else { - throw Web3Error.dataError + if let address = recoverAddress(hash: hash, signature: signature) { + return address } - return recovered + throw Web3Error.dataError } } diff --git a/Sources/web3swift/Web3/Web3+Resolver.swift b/Sources/web3swift/Web3/Web3+Resolver.swift index c2eb0b481..1fa3d6299 100644 --- a/Sources/web3swift/Web3/Web3+Resolver.swift +++ b/Sources/web3swift/Web3/Web3+Resolver.swift @@ -1,6 +1,6 @@ // // Web3+Resolver.swift -// +// // // Created by Jann Driessen on 01.11.22. // diff --git a/Sources/web3swift/Web3/Web3+Signing.swift b/Sources/web3swift/Web3/Web3+Signing.swift index d1b57f270..2e135c6c0 100755 --- a/Sources/web3swift/Web3/Web3+Signing.swift +++ b/Sources/web3swift/Web3/Web3+Signing.swift @@ -18,7 +18,7 @@ public struct Web3Signer { defer { Data.zero(&privateKey) } try transaction.sign(privateKey: privateKey, useExtraEntropy: useExtraEntropy) } - + public static func signPersonalMessage(_ personalMessage: Data, keystore: T, account: EthereumAddress, @@ -32,14 +32,14 @@ public struct Web3Signer { useExtraEntropy: useExtraEntropy) return compressedSignature } - + public static func signEIP712(_ eip712Hashable: EIP712Hashable, keystore: BIP32Keystore, verifyingContract: EthereumAddress, account: EthereumAddress, password: String? = nil, chainId: BigUInt? = nil) throws -> Data { - + let domainSeparator: EIP712Hashable = EIP712Domain(chainId: chainId, verifyingContract: verifyingContract) let hash = try eip712encode(domainSeparator: domainSeparator, message: eip712Hashable) guard let signature = try Web3Signer.signPersonalMessage(hash, diff --git a/Sources/web3swift/Web3/Web3+Utils.swift b/Sources/web3swift/Web3/Web3+Utils.swift index a5a3310b9..666e642a7 100755 --- a/Sources/web3swift/Web3/Web3+Utils.swift +++ b/Sources/web3swift/Web3/Web3+Utils.swift @@ -17,20 +17,13 @@ extension Web3 { } } +// swiftlint:disable file_length +// swiftlint:disable line_length extension Web3.Utils { - // /// Calculate address of deployed contract deterministically based on the address of the deploying Ethereum address - // /// and the nonce of this address - // public static func calculateContractAddress(from: EthereumAddress, nonce: BigUInt) -> EthereumAddress? { - // guard let normalizedAddress = from.addressData.setLengthLeft(32) else {return nil} - // guard let data = RLP.encode([normalizedAddress, nonce]) else {return nil} - // guard let contractAddressData = Utilities.sha3(data)?[12..<32] else {return nil} - // guard let contractAddress = EthereumAddress(Data(contractAddressData)) else {return nil} - // return contractAddress - // } - /// Various units used in Ethereum ecosystem public enum Units { + // swiftlint:disable identifier_name case eth case wei case Kwei @@ -40,23 +33,21 @@ extension Web3.Utils { case Finney var decimals: Int { - get { - switch self { - case .eth: - return 18 - case .wei: - return 0 - case .Kwei: - return 3 - case .Mwei: - return 6 - case .Gwei: - return 9 - case .Microether: - return 12 - case .Finney: - return 15 - } + switch self { + case .eth: + return 18 + case .wei: + return 0 + case .Kwei: + return 3 + case .Mwei: + return 6 + case .Gwei: + return 9 + case .Microether: + return 12 + case .Finney: + return 15 } } } diff --git a/Sources/web3swift/Web3/Web3.swift b/Sources/web3swift/Web3/Web3.swift index e8b1a72df..8b5dfc792 100755 --- a/Sources/web3swift/Web3/Web3.swift +++ b/Sources/web3swift/Web3/Web3.swift @@ -13,43 +13,40 @@ extension Web3 { /// Initialized provider-bound Web3 instance using a provider's URL. Under the hood it performs a synchronous call to get /// the Network ID for EIP155 purposes public static func new(_ providerURL: URL, network: Networks = .Mainnet) async throws -> Web3 { - // FIXME: Change this hardcoded value to dynamically fethed from a Node - guard let provider = await Web3HttpProvider(providerURL, network: network) else { - throw Web3Error.inputError(desc: "Wrong provider - should be Web3HttpProvider with endpoint scheme http or https") - } + let provider = try await Web3HttpProvider(url: providerURL, network: network) return Web3(provider: provider) } /// Initialized Web3 instance bound to Infura's mainnet provider. - public static func InfuraMainnetWeb3(accessToken: String? = nil) async -> Web3 { - let infura = await InfuraProvider(Networks.Mainnet, accessToken: accessToken)! + public static func InfuraMainnetWeb3(accessToken: String? = nil) async throws -> Web3 { + let infura = try await InfuraProvider(net: Networks.Mainnet, accessToken: accessToken) return Web3(provider: infura) } /// Initialized Web3 instance bound to Infura's goerli provider. - public static func InfuraGoerliWeb3(accessToken: String? = nil) async -> Web3 { - let infura = await InfuraProvider(Networks.Goerli, accessToken: accessToken)! + public static func InfuraGoerliWeb3(accessToken: String? = nil) async throws -> Web3 { + let infura = try await InfuraProvider(net: Networks.Goerli, accessToken: accessToken) return Web3(provider: infura) } /// Initialized Web3 instance bound to Infura's rinkeby provider. @available(*, deprecated, message: "This network support was deprecated by Infura") - public static func InfuraRinkebyWeb3(accessToken: String? = nil) async -> Web3 { - let infura = await InfuraProvider(Networks.Rinkeby, accessToken: accessToken)! + public static func InfuraRinkebyWeb3(accessToken: String? = nil) async throws -> Web3 { + let infura = try await InfuraProvider(net: Networks.Rinkeby, accessToken: accessToken) return Web3(provider: infura) } /// Initialized Web3 instance bound to Infura's ropsten provider. @available(*, deprecated, message: "This network support was deprecated by Infura") - public static func InfuraRopstenWeb3(accessToken: String? = nil) async -> Web3 { - let infura = await InfuraProvider(Networks.Ropsten, accessToken: accessToken)! + public static func InfuraRopstenWeb3(accessToken: String? = nil) async throws -> Web3 { + let infura = try await InfuraProvider(net: Networks.Ropsten, accessToken: accessToken) return Web3(provider: infura) } /// Initialized Web3 instance bound to Infura's kovan provider. @available(*, deprecated, message: "This network support was deprecated by Infura") - public static func InfuraKovanWeb3(accessToken: String? = nil) async -> Web3 { - let infura = await InfuraProvider(Networks.Kovan, accessToken: accessToken)! + public static func InfuraKovanWeb3(accessToken: String? = nil) async throws -> Web3 { + let infura = try await InfuraProvider(net: Networks.Kovan, accessToken: accessToken) return Web3(provider: infura) } diff --git a/TestToken/Helpers/TokenBasics/ERC20.sol b/TestToken/Helpers/TokenBasics/ERC20.sol index 7ecea0073..87593bfdf 100755 --- a/TestToken/Helpers/TokenBasics/ERC20.sol +++ b/TestToken/Helpers/TokenBasics/ERC20.sol @@ -202,4 +202,4 @@ contract ERC20 is IERC20 { amount); _burn(account, amount); } -} \ No newline at end of file +} diff --git a/TestToken/Helpers/TokenBasics/IERC20.sol b/TestToken/Helpers/TokenBasics/IERC20.sol index 6e322fe03..37e5a447c 100755 --- a/TestToken/Helpers/TokenBasics/IERC20.sol +++ b/TestToken/Helpers/TokenBasics/IERC20.sol @@ -31,4 +31,4 @@ interface IERC20 { address indexed spender, uint256 value ); -} \ No newline at end of file +} diff --git a/TestToken/Token/Web3SwiftToken.sol b/TestToken/Token/Web3SwiftToken.sol index 6f3fab8fd..3d4e91ded 100755 --- a/TestToken/Token/Web3SwiftToken.sol +++ b/TestToken/Token/Web3SwiftToken.sol @@ -16,4 +16,3 @@ contract web3swift is ERC20 { constructor() public { _mint(msg.sender, INITIAL_SUPPLY); } - diff --git a/Tests/web3swiftTests/localTests/ABIElementErrorDecodingTest.swift b/Tests/web3swiftTests/localTests/ABIElementErrorDecodingTest.swift index 9c7d238f9..181337d19 100644 --- a/Tests/web3swiftTests/localTests/ABIElementErrorDecodingTest.swift +++ b/Tests/web3swiftTests/localTests/ABIElementErrorDecodingTest.swift @@ -51,7 +51,7 @@ class ABIElementErrorDecodingTest: XCTestCase { .init(name: "rand_bytes", type: .bytes(length: 123)), .init(name: "", type: .dynamicBytes), .init(name: "arrarrarray123", type: .array(type: .bool, length: 0)), - .init(name: "error_message_maybe", type: .string), + .init(name: "error_message_maybe", type: .string) ] XCTAssertEqual(EthError(name: "VeryCustomErrorName", inputs: allTypesNamedAndNot).errorDeclaration, @@ -113,7 +113,7 @@ class ABIElementErrorDecodingTest: XCTestCase { /// 82b42900 - Unauthorized() function selector /// 00000000000000000000000000000000000000000000000000000000 - padding bytes let errorResponse = Data.fromHex("82b4290000000000000000000000000000000000000000000000000000000000")! - let errors: [String: EthError] = ["82b42900" : .init(name: "Unauthorized", inputs: [])] + let errors: [String: EthError] = ["82b42900": .init(name: "Unauthorized", inputs: [])] guard let errorData = emptyFunction.decodeErrorResponse(errorResponse, errors: errors) else { XCTFail("Data must be decoded as a `revert(\"Not enough Ether provided.\")` or `require(false, \"Not enough Ether provided.\")` but decoding failed completely.") return @@ -136,7 +136,7 @@ class ABIElementErrorDecodingTest: XCTestCase { /// 82b42900 - Unauthorized() function selector /// 00000000000000000000000000000000000000000000000000000000 - padding bytes let errorResponse = Data.fromHex("82b4290000000000000000000000000000000000000000000000000000000000")! - let errors: [String: EthError] = ["82b42900" : .init(name: "Unauthorized", inputs: [.init(name: "", type: .string)])] + let errors: [String: EthError] = ["82b42900": .init(name: "Unauthorized", inputs: [.init(name: "", type: .string)])] guard let errorData = emptyFunction.decodeErrorResponse(errorResponse, errors: errors) else { XCTFail("Data must be decoded as a `revert(\"Not enough Ether provided.\")` or `require(false, \"Not enough Ether provided.\")` but decoding failed completely.") return @@ -164,7 +164,7 @@ class ABIElementErrorDecodingTest: XCTestCase { /// 526561736f6e0000000000000000000000000000000000000000000000000000 - first custom argument bytes + 0 bytes padding /// 0000... - some more 0 bytes padding to make the number of bytes match 32 bytes chunks let errorResponse = Data.fromHex("973d02cb00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000006526561736f6e000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")! - let errors: [String: EthError] = ["973d02cb" : .init(name: "Unauthorized", inputs: [.init(name: "message_arg", type: .string)])] + let errors: [String: EthError] = ["973d02cb": .init(name: "Unauthorized", inputs: [.init(name: "message_arg", type: .string)])] guard let errorData = emptyFunction.decodeErrorResponse(errorResponse, errors: errors) else { XCTFail("Data must be decoded as a `revert(\"Not enough Ether provided.\")` or `require(false, \"Not enough Ether provided.\")` but decoding failed completely.") return diff --git a/Tests/web3swiftTests/localTests/ABIEncoderTest.swift b/Tests/web3swiftTests/localTests/ABIEncoderTest.swift index c6e6057f7..2e13e4334 100644 --- a/Tests/web3swiftTests/localTests/ABIEncoderTest.swift +++ b/Tests/web3swiftTests/localTests/ABIEncoderTest.swift @@ -200,12 +200,12 @@ class ABIEncoderTest: XCTestCase { var hexData = ABIEncoder.encode(types: [.string], values: ["test"])?.toHexString() XCTAssertEqual(hexData?[0..<64], "0000000000000000000000000000000000000000000000000000000000000020") XCTAssertEqual(hexData, "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000047465737400000000000000000000000000000000000000000000000000000000") - hexData = ABIEncoder.encode(types: [.array(type: .uint(bits: 8), length: 0)], values: [[1,2,3,4]])?.toHexString() + hexData = ABIEncoder.encode(types: [.array(type: .uint(bits: 8), length: 0)], values: [[1, 2, 3, 4]])?.toHexString() XCTAssertEqual(hexData?[0..<64], "0000000000000000000000000000000000000000000000000000000000000020") XCTAssertEqual(hexData, "000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004") // This one shouldn't have data offset - hexData = ABIEncoder.encode(types: [.array(type: .uint(bits: 8), length: 4)], values: [[1,2,3,4]])?.toHexString() + hexData = ABIEncoder.encode(types: [.array(type: .uint(bits: 8), length: 4)], values: [[1, 2, 3, 4]])?.toHexString() // First 32 bytes are the first value from the array XCTAssertEqual(hexData?[0..<64], "0000000000000000000000000000000000000000000000000000000000000001") XCTAssertEqual(hexData, "0000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004") @@ -214,7 +214,7 @@ class ABIEncoderTest: XCTestCase { .bool, .array(type: .uint(bits: 8), length: 0), .bytes(length: 2)] - let values: [Any] = [10, false, [1,2,3,4], Data(count: 2)] + let values: [Any] = [10, false, [1, 2, 3, 4], Data(count: 2)] hexData = ABIEncoder.encode(types: types, values: values)?.toHexString() XCTAssertEqual(hexData?[128..<192], "0000000000000000000000000000000000000000000000000000000000000080") XCTAssertEqual(hexData, "000000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000030000000000000000000000000000000000000000000000000000000000000004") @@ -230,7 +230,7 @@ class ABIEncoderTest: XCTestCase { encodedValue = ABIEncoder.encode(types: [.dynamicBytes], values: [Data.fromHex("fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff1")!])!.toHexString() XCTAssertEqual(encodedValue, "0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000009ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff100") - + encodedValue = ABIEncoder.encode(types: [.dynamicBytes], values: [Data.fromHex("c3a40000c3a4")!])!.toHexString() XCTAssertEqual(encodedValue, "00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000006c3a40000c3a40000000000000000000000000000000000000000000000000000") diff --git a/Tests/web3swiftTests/localTests/AdvancedABIv2Tests.swift b/Tests/web3swiftTests/localTests/AdvancedABIv2Tests.swift index 7f174b784..066a1b7a8 100755 --- a/Tests/web3swiftTests/localTests/AdvancedABIv2Tests.swift +++ b/Tests/web3swiftTests/localTests/AdvancedABIv2Tests.swift @@ -31,7 +31,6 @@ class AdvancedABIv2Tests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(Data.fromHex(txHash)!) - switch receipt.status { case .notYetProcessed: @@ -44,7 +43,7 @@ class AdvancedABIv2Tests: LocalTestCase { // MARK: Read data from ABI flow // MARK: - Encoding ABI Data flow let tx = contract.createReadOperation("testSingle") - let _ = try await tx!.callContractMethod() + _ = try await tx!.callContractMethod() } func testAdvancedABIv2staticArray() async throws { @@ -66,7 +65,6 @@ class AdvancedABIv2Tests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(Data.fromHex(txHash)!) - switch receipt.status { case .notYetProcessed: @@ -79,7 +77,7 @@ class AdvancedABIv2Tests: LocalTestCase { // MARK: Read data from ABI flow // MARK: - Encoding ABI Data flow let tx = contract.createReadOperation("testStaticArray") - let _ = try await tx!.callContractMethod() + _ = try await tx!.callContractMethod() } func testAdvancedABIv2dynamicArray() async throws { @@ -101,7 +99,6 @@ class AdvancedABIv2Tests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(Data.fromHex(txHash)!) - switch receipt.status { case .notYetProcessed: @@ -113,7 +110,7 @@ class AdvancedABIv2Tests: LocalTestCase { contract = web3.contract(abiString, at: receipt.contractAddress, abiVersion: 2)! let tx = contract.createReadOperation("testDynArray") - let _ = try await tx!.callContractMethod() + _ = try await tx!.callContractMethod() } func testAdvancedABIv2dynamicArrayOfStrings() async throws { @@ -135,7 +132,6 @@ class AdvancedABIv2Tests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(Data.fromHex(txHash)!) - switch receipt.status { case .notYetProcessed: @@ -148,7 +144,7 @@ class AdvancedABIv2Tests: LocalTestCase { // MARK: Read data from ABI flow // MARK: - Encoding ABI Data flow let tx = contract.createReadOperation("testDynOfDyn") - let _ = try await tx!.callContractMethod() + _ = try await tx!.callContractMethod() } func testAdvancedABIv2staticArrayOfStrings() async throws { @@ -170,7 +166,6 @@ class AdvancedABIv2Tests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(Data.fromHex(txHash)!) - switch receipt.status { case .notYetProcessed: @@ -183,7 +178,7 @@ class AdvancedABIv2Tests: LocalTestCase { // MARK: Read data from ABI flow // MARK: - Encoding ABI Data flow let tx = contract.createReadOperation("testStOfDyn") - let _ = try await tx!.callContractMethod() + _ = try await tx!.callContractMethod() } func testEmptyArrayDecoding() async throws { diff --git a/Tests/web3swiftTests/localTests/BasicLocalNodeTests.swift b/Tests/web3swiftTests/localTests/BasicLocalNodeTests.swift index 4ad43fc53..822d90c9b 100755 --- a/Tests/web3swiftTests/localTests/BasicLocalNodeTests.swift +++ b/Tests/web3swiftTests/localTests/BasicLocalNodeTests.swift @@ -57,8 +57,6 @@ class BasicLocalNodeTests: LocalTestCase { let balanceBeforeTo = try await web3.eth.getBalance(for: sendToAddress) let balanceBeforeFrom = try await web3.eth.getBalance(for: allAddresses[0]) - - let result = try await sendTx.writeToChain(password: "web3swift", sendRaw: false) let txHash = Data.fromHex(result.hash.stripHexPrefix())! @@ -66,7 +64,6 @@ class BasicLocalNodeTests: LocalTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(txHash) - switch receipt.status { case .notYetProcessed: @@ -76,12 +73,9 @@ class BasicLocalNodeTests: LocalTestCase { } let details = try await web3.eth.transactionDetails(txHash) - let balanceAfterTo = try await web3.eth.getBalance(for: sendToAddress) let balanceAfterFrom = try await web3.eth.getBalance(for: allAddresses[0]) - - XCTAssertEqual(balanceAfterTo - balanceBeforeTo, valueToSend) let txnGasPrice = details.transaction.meta?.gasPrice ?? 0 diff --git a/Tests/web3swiftTests/localTests/DataConversionTests.swift b/Tests/web3swiftTests/localTests/DataConversionTests.swift index 62211ec88..bba7db52d 100644 --- a/Tests/web3swiftTests/localTests/DataConversionTests.swift +++ b/Tests/web3swiftTests/localTests/DataConversionTests.swift @@ -22,15 +22,12 @@ class DataConversionTests: LocalTestCase { func testBase58() throws { let vector = "" - guard let resultDecoded = vector.base58DecodedData else { return XCTFail("base58 decode unexpectedly returned nil") } XCTAssert(resultDecoded.count == 0) - let resultEncoded1 = vector.base58EncodedString XCTAssert(resultEncoded1 == vector) - let arr = resultDecoded.withUnsafeBytes { Array($0) } let resultEncoded2 = arr.base58EncodedString XCTAssert(resultEncoded2 == vector) @@ -41,13 +38,11 @@ class DataConversionTests: LocalTestCase { let vector = "2NEpo7TZRRrLZSi2U" let expected = "Hello World!" - guard let resultDecoded = vector.base58DecodedData else { return XCTFail("base58 decode unexpectedly returned nil") } let arr = resultDecoded.withUnsafeBytes { Array($0) } let str = String(bytes: arr, encoding: .utf8) XCTAssert(str == expected) - let resultEncoded = expected.base58EncodedString XCTAssert(resultEncoded == vector) } @@ -57,13 +52,11 @@ class DataConversionTests: LocalTestCase { let vector = "USm3fpXnKG5EUBx2ndxBDMPVciP5hGey2Jh4NDv6gmeo1LkMeiKrLJUUBk6Z" let expected = "The quick brown fox jumps over the lazy dog." - guard let resultDecoded = vector.base58DecodedData else { return XCTFail("base58 decode unexpectedly returned nil") } let arr = resultDecoded.withUnsafeBytes { Array($0) } let str = String(bytes: arr, encoding: .utf8) XCTAssert(str == expected) - let resultEncoded = expected.base58EncodedString XCTAssert(resultEncoded == vector) } @@ -73,12 +66,10 @@ class DataConversionTests: LocalTestCase { let vector = "111233QC4" let expected = "0x000000287fb4cd" - guard let resultDecoded = vector.base58DecodedData else { return XCTFail("base58 decode unexpectedly returned nil") } let str = resultDecoded.toHexString().addHexPrefix() XCTAssert(str == expected) - let arr = resultDecoded.withUnsafeBytes { Array($0) } let resultEncoded = arr.base58EncodedString XCTAssert(resultEncoded == vector) @@ -89,12 +80,10 @@ class DataConversionTests: LocalTestCase { let vector = "11111111111111111111111111111111" let expected = "0x0000000000000000000000000000000000000000000000000000000000000000" - guard let resultDecoded = vector.base58DecodedData else { return XCTFail("base58 decode unexpectedly returned nil") } let str = resultDecoded.toHexString().addHexPrefix() XCTAssert(str == expected) - let arr = resultDecoded.withUnsafeBytes { Array($0) } let resultEncoded = arr.base58EncodedString XCTAssert(resultEncoded == vector) diff --git a/Tests/web3swiftTests/localTests/EIP67Tests.swift b/Tests/web3swiftTests/localTests/EIP67Tests.swift index 9a105e5b5..de9f694d1 100755 --- a/Tests/web3swiftTests/localTests/EIP67Tests.swift +++ b/Tests/web3swiftTests/localTests/EIP67Tests.swift @@ -18,7 +18,7 @@ class EIP67Tests: LocalTestCase { eip67Data.amount = BigUInt("1000000000000000000") // eip67Data.data = let encoding = eip67Data.toString() - + } func testEIP67codeGeneration() throws { diff --git a/Tests/web3swiftTests/localTests/EthereumAddressTest.swift b/Tests/web3swiftTests/localTests/EthereumAddressTest.swift new file mode 100644 index 000000000..9cf812ba0 --- /dev/null +++ b/Tests/web3swiftTests/localTests/EthereumAddressTest.swift @@ -0,0 +1,48 @@ +// +// EthereumAddressTest.swift +// +// +// Created by JeneaVranceanu on 03.02.2023. +// + +import Foundation +import XCTest + +@testable import Web3Core + +class EthereumAddressTest: XCTestCase { + + func testZeroAddress() { + XCTAssertNotNil(EthereumAddress(Data(count: 20))) + } + + func testAddress() { + let rawAddress = "0x200eb5ccda1c35b0f5bf82552fdd65a8aee98e79" + let ethereumAddress = EthereumAddress(rawAddress) + XCTAssertNotNil(ethereumAddress) + XCTAssertEqual(ethereumAddress?.address.lowercased(), rawAddress) + } + + func testInvalidAddress() { + var rawAddress = "0x200eb5ccda1c35b0f5bf82552e98e79" + var ethereumAddress = EthereumAddress(rawAddress) + XCTAssertNil(ethereumAddress) + rawAddress = "0x200eb5ccDA1c35b0f5bf82552fdd65a8aeeabcde" + ethereumAddress = EthereumAddress(rawAddress) + XCTAssertNil(ethereumAddress) + rawAddress = "0x200eb5ccda1c35b0f5bf82552fdd65a8aeeabcdef" + ethereumAddress = EthereumAddress(rawAddress) + XCTAssertNil(ethereumAddress) + } + + func testDescription() async throws { + let rawAddress = "0x200eb5ccda1c35b0f5bf82552fdd65a8aee98e79" + let ethereumAddress = EthereumAddress(rawAddress) + + let sut = String(describing: ethereumAddress) + + XCTAssertTrue(sut.contains("EthereumAddress\n")) + XCTAssertTrue(sut.contains("type: normal\n")) + XCTAssertTrue(sut.contains("address: 0x200EB5cCdA1c35B0F5Bf82552FDD65a8AEe98E79")) + } +} diff --git a/Tests/web3swiftTests/localTests/EventloopTests.swift b/Tests/web3swiftTests/localTests/EventloopTests.swift index 923aaf774..2e8b0df25 100755 --- a/Tests/web3swiftTests/localTests/EventloopTests.swift +++ b/Tests/web3swiftTests/localTests/EventloopTests.swift @@ -21,7 +21,7 @@ class EventloopTests: XCTestCase { expectation.fulfill() } } catch { - + } } diff --git a/Tests/web3swiftTests/localTests/KeystoresTests.swift b/Tests/web3swiftTests/localTests/KeystoresTests.swift index 3348ac9c9..cab2dae5f 100755 --- a/Tests/web3swiftTests/localTests/KeystoresTests.swift +++ b/Tests/web3swiftTests/localTests/KeystoresTests.swift @@ -81,7 +81,7 @@ class KeystoresTests: LocalTestCase { let keystore = try! EthereumKeystoreV3(password: "") XCTAssertNotNil(keystore) let account = keystore!.addresses![0] - + let data = try! keystore!.serialize() let key = try! keystore!.UNSAFE_getPrivateKeyData(password: "", account: account) XCTAssertNotNil(key) @@ -172,7 +172,7 @@ class KeystoresTests: LocalTestCase { let account = keystore!.addresses![1] let key = try! keystore!.UNSAFE_getPrivateKeyData(password: "", account: account) XCTAssertNotNil(key) - + } func testByBIP32keystoreSaveAndDeriva() throws { @@ -186,10 +186,7 @@ class KeystoresTests: LocalTestCase { let recreatedStore = BIP32Keystore.init(data!) XCTAssert(keystore?.addresses?.count == recreatedStore?.addresses?.count) XCTAssert(keystore?.rootPrefix == recreatedStore?.rootPrefix) - - - - + XCTAssert(keystore?.addresses![0] == recreatedStore?.addresses![0]) XCTAssert(keystore?.addresses![1] == recreatedStore?.addresses![1]) } diff --git a/Tests/web3swiftTests/localTests/NumberFormattingUtilTests.swift b/Tests/web3swiftTests/localTests/NumberFormattingUtilTests.swift index e8a95463d..9929130a9 100755 --- a/Tests/web3swiftTests/localTests/NumberFormattingUtilTests.swift +++ b/Tests/web3swiftTests/localTests/NumberFormattingUtilTests.swift @@ -15,57 +15,57 @@ class NumberFormattingUtilTests: LocalTestCase { func testNumberFormattingUtil() throws { let balance = BigInt("-1000000000000000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",") - XCTAssert(formatted == "-1") + XCTAssertEqual(formatted, "-1") } func testNumberFormattingUtil2() throws { let balance = BigInt("-1000000000000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",") - XCTAssert(formatted == "-0,0010") + XCTAssertEqual(formatted, "-0,0010") } func testNumberFormattingUtil3() throws { let balance = BigInt("-1000000000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",") - XCTAssert(formatted == "-0,0000") + XCTAssertEqual(formatted, "-0,0000") } func testNumberFormattingUtil4() throws { let balance = BigInt("-1000000000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 9, decimalSeparator: ",") - XCTAssert(formatted == "-0,000001000") + XCTAssertEqual(formatted, "-0,000001000") } func testNumberFormattingUtil5() throws { let balance = BigInt("-1") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 9, decimalSeparator: ",", fallbackToScientific: true) - XCTAssert(formatted == "-1e-18") + XCTAssertEqual(formatted, "-1e-18") } func testNumberFormattingUtil6() throws { let balance = BigInt("0") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 9, decimalSeparator: ",") - XCTAssert(formatted == "0") + XCTAssertEqual(formatted, "0") } func testNumberFormattingUtil7() throws { let balance = BigInt("-1100000000000000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",") - XCTAssert(formatted == "-1,1000") + XCTAssertEqual(formatted, "-1,1000") } func testNumberFormattingUtil8() throws { let balance = BigInt("100") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",", fallbackToScientific: true) - XCTAssert(formatted == "1,00e-16") + XCTAssertEqual(formatted, "1,00e-16") } func testNumberFormattingUtil9() throws { let balance = BigInt("1000000") let formatted = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 4, decimalSeparator: ",", fallbackToScientific: true) - XCTAssert(formatted == "1,0000e-12") + XCTAssertEqual(formatted, "1,0000e-12") } - + func testFormatPreccissionFallbacksToUnitsDecimals() throws { let bInt = BigInt(1_700_000_000_000_000_000) let result = Utilities.formatToPrecision(bInt, units: .ether, formattingDecimals: Utilities.Units.ether.decimals + 1, decimalSeparator: ",") diff --git a/Tests/web3swiftTests/localTests/PersonalSignatureTests.swift b/Tests/web3swiftTests/localTests/PersonalSignatureTests.swift index 407115b08..e8cd5e1ff 100755 --- a/Tests/web3swiftTests/localTests/PersonalSignatureTests.swift +++ b/Tests/web3swiftTests/localTests/PersonalSignatureTests.swift @@ -19,10 +19,10 @@ class PersonalSignatureTests: XCTestCase { web3.addKeystoreManager(keystoreManager) let message = "Hello World" let expectedAddress = keystoreManager.addresses![0] - + let signature = try await web3.personal.signPersonalMessage(message: message.data(using: .utf8)!, from: expectedAddress, password: "") let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: signature)! - let signer = try web3.personal.ecrecover(personalMessage: message.data(using: .utf8)!, signature: signature) + let signer = web3.personal.recoverAddress(message: message.data(using: .utf8)!, signature: signature) XCTAssert(expectedAddress == signer, "Failed to sign personal message") } @@ -44,7 +44,7 @@ class PersonalSignatureTests: XCTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(txHash) - + switch receipt.status { case .notYetProcessed: return @@ -58,7 +58,7 @@ class PersonalSignatureTests: XCTestCase { web3.addKeystoreManager(keystoreManager) let message = "Hello World" let expectedAddress = keystoreManager.addresses![0] - + let signature = try await web3.personal.signPersonalMessage(message: message.data(using: .utf8)!, from: expectedAddress, password: "") let unmarshalledSignature = SECP256K1.unmarshalSignature(signatureData: signature)! diff --git a/Tests/web3swiftTests/localTests/PromisesTests.swift b/Tests/web3swiftTests/localTests/PromisesTests.swift index 434c6389c..eb9bd3509 100755 --- a/Tests/web3swiftTests/localTests/PromisesTests.swift +++ b/Tests/web3swiftTests/localTests/PromisesTests.swift @@ -15,7 +15,7 @@ // func testGetBalancePromise() async throws { // let web3 = try await Web3.new(LocalTestCase.url) // let balance = try await web3.eth.getBalance(for: EthereumAddress("0xe22b8979739D724343bd002F9f432F5990879901")!) -// +// // } // // func testEstimateGasPromise() async throws { @@ -29,7 +29,7 @@ // writeTX.transaction.from = tempKeystore!.addresses?.first // writeTX.transaction.value = BigUInt("1.0", Utilities.Units.eth)! // let estimate = try await writeTX.estimateGas(with: nil) -// +// // XCTAssertEqual(estimate, 21000) // } // @@ -47,12 +47,12 @@ // deployTx.transaction.gasLimitPolicy = .manual(3000000) // let result = try await deployTx.send(password: "web3swift") // let txHash = result.hash -// +// // // Thread.sleep(forTimeInterval: 1.0) // // let receipt = try await web3.eth.transactionReceipt(txHash) -// +// // // switch receipt.status { // case .notYetProcessed: @@ -87,7 +87,7 @@ // } // // MARK: Writing Data flow // let estimate1 = try await tx1.estimateGas(with: nil) -// +// // // let amount2 = Utilities.parseToBigUInt("0.00000005", units: .eth) // 50 gwei // @@ -100,7 +100,7 @@ // } // // MARK: Writing Data flow // let estimate2 = try await tx2.estimateGas(with: nil) -// +// // XCTAssertLessThanOrEqual(estimate2 - estimate1, 22000) // } // // FIXME: Temporary deleted method `sendETH` should be restored. @@ -113,7 +113,7 @@ // // writeTX.transaction.from = allAddresses[0] // // writeTX.transaction.gasPricePolicy = .manual(gasPricePolicy) // // let result = try await writeTX.send() -// // +// // // // } // // // func testERC20tokenBalancePromise() async throws { diff --git a/Tests/web3swiftTests/localTests/RLPTests.swift b/Tests/web3swiftTests/localTests/RLPTests.swift index a17e41300..e6fa28cc9 100755 --- a/Tests/web3swiftTests/localTests/RLPTests.swift +++ b/Tests/web3swiftTests/localTests/RLPTests.swift @@ -14,6 +14,6 @@ class RLPTests: LocalTestCase { func testRLPdecodeTransaction() throws { let input = Data.fromHex("0xf90890558504e3b292008309153a8080b9083d6060604052336000806101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff160217905550341561004f57600080fd5b60405160208061081d83398101604052808051906020019091905050600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff16141515156100a757600080fd5b80600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050610725806100f86000396000f300606060405260043610610062576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680638da5cb5b14610067578063b2b2c008146100bc578063d59ba0df146101eb578063d8ffdcc414610247575b600080fd5b341561007257600080fd5b61007a61029c565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b34156100c757600080fd5b61019460048080359060200190820180359060200190808060200260200160405190810160405280939291908181526020018383602002808284378201915050505050509190803590602001908201803590602001908080602002602001604051908101604052809392919081815260200183836020028082843782019150505050505091908035906020019082018035906020019080806020026020016040519081016040528093929190818152602001838360200280828437820191505050505050919050506102c1565b6040518080602001828103825283818151815260200191508051906020019060200280838360005b838110156101d75780820151818401526020810190506101bc565b505050509050019250505060405180910390f35b34156101f657600080fd5b61022d600480803573ffffffffffffffffffffffffffffffffffffffff169060200190919080351515906020019091905050610601565b604051808215151515815260200191505060405180910390f35b341561025257600080fd5b61025a6106bf565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b6000809054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6102c96106e5565b6102d16106e5565b6000806000600260003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900460ff16151561032e57600080fd5b8651885114151561033e57600080fd5b875160405180591061034d5750595b9080825280602002602001820160405250935060009250600091505b87518210156105f357600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166323b872dd87848151811015156103be57fe5b906020019060200201518a858151811015156103d657fe5b906020019060200201518a868151811015156103ee57fe5b906020019060200201516000604051602001526040518463ffffffff167c0100000000000000000000000000000000000000000000000000000000028152600401808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018281526020019350505050602060405180830381600087803b15156104b857600080fd5b6102c65a03f115156104c957600080fd5b50505060405180519050905080156105e65787828151811015156104e957fe5b90602001906020020151848481518110151561050157fe5b9060200190602002019073ffffffffffffffffffffffffffffffffffffffff16908173ffffffffffffffffffffffffffffffffffffffff16815250508280600101935050868281518110151561055357fe5b90602001906020020151888381518110151561056b57fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff16878481518110151561059957fe5b9060200190602002015173ffffffffffffffffffffffffffffffffffffffff167f334b3b1d4ad406523ee8e24beb689f5adbe99883a662c37d43275de52389da1460405160405180910390a45b8180600101925050610369565b839450505050509392505050565b60008060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561065e57600080fd5b81600260008573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548160ff0219169083151502179055506001905092915050565b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6020604051908101604052806000815250905600a165627a7a723058200618093d895b780d4616f24638637da0e0f9767e6d3675a9525fee1d6ed7f431002900000000000000000000000045245bc59219eeaaf6cd3f382e078a461ff9de7b25a0d1efc3c97d1aa9053aa0f59bf148d73f59764343bf3cae576c8769a14866948da0613d0265634fddd436397bc858e2672653833b57a05cfc8b93c14a6c05166e4a")! let transaction = CodableTransaction(rawValue: input) - + } } diff --git a/Tests/web3swiftTests/localTests/ST20AndSecurityTokenTests.swift b/Tests/web3swiftTests/localTests/ST20AndSecurityTokenTests.swift index 285b2641f..ebf9193a1 100644 --- a/Tests/web3swiftTests/localTests/ST20AndSecurityTokenTests.swift +++ b/Tests/web3swiftTests/localTests/ST20AndSecurityTokenTests.swift @@ -18,7 +18,7 @@ class ST20AndSecurityTokenTests: XCTestCase { var securityToken: SecurityToken! override func setUp() async throws { - web3 = await Web3.InfuraGoerliWeb3(accessToken: Constants.infuraToken) + web3 = try await Web3.InfuraGoerliWeb3(accessToken: Constants.infuraToken) ethMock = Web3EthMock(provider: web3.provider) web3.ethInstance = ethMock st20token = ST20.init(web3: web3, provider: web3.provider, address: .contractDeploymentAddress()) @@ -111,7 +111,7 @@ class ST20AndSecurityTokenTests: XCTestCase { func testSecurityTokenGranularity() async throws { let expectedGranularity = BigUInt.randomInteger(lessThan: BigUInt(10000000000)) - + ethMock.onCallTransaction = { transaction in guard let function = self.securityToken.contract.contract.getFunctionCalled(transaction.data) else { XCTFail("Failed to decode function call to determine what shall be returned") diff --git a/Tests/web3swiftTests/localTests/TestHelpers.swift b/Tests/web3swiftTests/localTests/TestHelpers.swift index ce049fce4..9f3a49860 100644 --- a/Tests/web3swiftTests/localTests/TestHelpers.swift +++ b/Tests/web3swiftTests/localTests/TestHelpers.swift @@ -39,7 +39,6 @@ class TestHelpers { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(txHash) - switch receipt.status { case .notYetProcessed: diff --git a/Tests/web3swiftTests/localTests/TransactionsTests.swift b/Tests/web3swiftTests/localTests/TransactionsTests.swift old mode 100755 new mode 100644 index 1a39e3bf3..255c5a731 --- a/Tests/web3swiftTests/localTests/TransactionsTests.swift +++ b/Tests/web3swiftTests/localTests/TransactionsTests.swift @@ -195,7 +195,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -243,7 +243,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -264,7 +264,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -312,7 +312,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -333,7 +333,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -381,7 +381,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -402,7 +402,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -450,7 +450,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -518,7 +518,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -539,7 +539,7 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } @@ -587,11 +587,23 @@ class TransactionsTests: XCTestCase { // check that we recovered the address correctly XCTAssertEqual(jsonTxn.sender!.address, expectedAddress.address, "Recovered Address Mismatch") } catch { - + return XCTFail(String(describing: error)) } } + func testDescription() async throws { + let vector = testVector[TestCase.eip1559.rawValue] + let jsonData = try XCTUnwrap(vector.JSON.data(using: .utf8)) + let txn = try JSONDecoder().decode(CodableTransaction.self, from: jsonData) + + let sut = String(describing: txn) + + XCTAssertTrue(sut.contains("Transaction")) + XCTAssertTrue(sut.contains("from: Optional(EthereumAddress\ntype: normal\naddress: 0x9d8A62f656a8d1615C1294fd71e9CFb3E4855A4F\n)\n")) + XCTAssertTrue(sut.contains(#"hash: Optional("0x41dc0cd9b133e0d4e47e269988b0109c966db5220d57e2a7f3cdc6c2f8de6a72")"#)) + } + // ***** Legacy Tests ***** // TODO: Replace `XCTAssert` with more explicit `XCTAssertEqual`, where Applicable @@ -611,16 +623,16 @@ class TransactionsTests: XCTestCase { let publicKey = Utilities.privateToPublic(privateKeyData, compressed: false) let sender = Utilities.publicToAddress(publicKey!) transaction.chainID = 1 - + let hash = transaction.hashForSignature() let expectedHash = "0xdaf5a779ae972f972197303d7b574746c7ef83eadac0f2791ad23db92e4c8e53".stripHexPrefix() XCTAssertEqual(hash!.toHexString(), expectedHash, "Transaction signature failed") try transaction.sign(privateKey: privateKeyData, useExtraEntropy: false) - + XCTAssertEqual(transaction.v, 37, "Transaction signature failed") XCTAssertEqual(sender, transaction.sender) } catch { - + XCTFail() } } @@ -639,12 +651,11 @@ class TransactionsTests: XCTestCase { let policies = Policies(gasLimitPolicy: .manual(78423)) let result = try await writeTX.writeToChain(password: "", policies: policies, sendRaw: false) let txHash = Data.fromHex(result.hash.stripHexPrefix())! - Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(txHash) - + XCTAssert(receipt.status == .ok) switch receipt.status { @@ -655,13 +666,13 @@ class TransactionsTests: XCTestCase { } let details = try await web3.eth.transactionDetails(txHash) - + // FIXME: Re-enable this test. // XCTAssertEqual(details.transaction.gasLimit, BigUInt(78423)) } catch Web3Error.nodeError(let descr) { guard descr == "insufficient funds for gas * price + value" else {return XCTFail()} } catch { - + XCTFail() } } diff --git a/Tests/web3swiftTests/localTests/UncategorizedTests.swift b/Tests/web3swiftTests/localTests/UncategorizedTests.swift index ccd1056b1..f47ccdeec 100755 --- a/Tests/web3swiftTests/localTests/UncategorizedTests.swift +++ b/Tests/web3swiftTests/localTests/UncategorizedTests.swift @@ -69,7 +69,7 @@ class UncategorizedTests: XCTestCase { bloom.add(BigUInt(data)) let newBytes = bloom.bytes if newBytes != oldBytes { - + } } for str in positive { @@ -118,16 +118,15 @@ class UncategorizedTests: XCTestCase { let userDeviceCount = try await contract! .createReadOperation("userDeviceCount", parameters: [addr])? .callContractMethod() - + let totalUsers = try await contract! .createReadOperation("totalUsers")? .callContractMethod() - + let user = try await contract! .createReadOperation("users", parameters: [0])? .callContractMethod() - - + } func testBloomFilterPerformance() throws { diff --git a/Tests/web3swiftTests/localTests/UserCases.swift b/Tests/web3swiftTests/localTests/UserCases.swift index c6377dda9..faa903d4d 100755 --- a/Tests/web3swiftTests/localTests/UserCases.swift +++ b/Tests/web3swiftTests/localTests/UserCases.swift @@ -13,8 +13,8 @@ class UserCases: XCTestCase { func getKeystoreData() -> Data? { let bundle = Bundle(for: type(of: self)) - guard let path = bundle.path(forResource: "key", ofType: "json") else {return nil} - guard let data = NSData(contentsOfFile: path) else {return nil} + guard let path = bundle.path(forResource: "key", ofType: "json") else { return nil } + guard let data = NSData(contentsOfFile: path) else { return nil } return data as Data } @@ -26,7 +26,7 @@ class UserCases: XCTestCase { readTransaction.transaction.from = account let response = try await readTransaction.callContractMethod() let balance = response["0"] as? BigUInt - + } func testUserCase2() async { @@ -86,7 +86,7 @@ class UserCases: XCTestCase { Thread.sleep(forTimeInterval: 1.0) let receipt = try await web3.eth.transactionReceipt(txHash) - + XCTAssert(receipt.contractAddress != nil) switch receipt.status { @@ -97,7 +97,7 @@ class UserCases: XCTestCase { } let details = try await web3.eth.transactionDetails(txHash) - + XCTAssert(details.transaction.to == .contractDeploymentAddress()) } @@ -105,6 +105,6 @@ class UserCases: XCTestCase { let web3 = try await Web3.new(LocalTestCase.url) let address = EthereumAddress("0xe22b8979739D724343bd002F9f432F5990879901")! let balanceResult = try await web3.eth.getBalance(for: address) - + } } diff --git a/Tests/web3swiftTests/localTests/UtilitiesTests.swift b/Tests/web3swiftTests/localTests/UtilitiesTests.swift index 5751afde0..4780805b0 100644 --- a/Tests/web3swiftTests/localTests/UtilitiesTests.swift +++ b/Tests/web3swiftTests/localTests/UtilitiesTests.swift @@ -10,14 +10,14 @@ import Web3Core @testable import web3swift -class UtilitiesTests: XCTestCase { +class UtilitiesTests: XCTestCase { // MARK: - units - + struct Test { let input: Utilities.Units let output: Int } - + func testUnitsDecimals() throws { let units: [Test] = [.init(input: .wei, output: 0), .init(input: .kwei, output: 3), @@ -41,7 +41,7 @@ class UtilitiesTests: XCTestCase { .init(input: .grand, output: 21), .init(input: .mether, output: 24), .init(input: .gether, output: 27), - .init(input: .tether, output: 30), + .init(input: .tether, output: 30) ] units.forEach { test in XCTAssertEqual(test.input.decimals, test.output) diff --git a/Tests/web3swiftTests/localTests/Web3ErrorTests.swift b/Tests/web3swiftTests/localTests/Web3ErrorTests.swift index c66ff9012..7eba7b8eb 100644 --- a/Tests/web3swiftTests/localTests/Web3ErrorTests.swift +++ b/Tests/web3swiftTests/localTests/Web3ErrorTests.swift @@ -22,4 +22,3 @@ class Web3ErrorTests: XCTestCase { } } - diff --git a/Tests/web3swiftTests/remoteTests/EIP1559Tests.swift b/Tests/web3swiftTests/remoteTests/EIP1559Tests.swift index 7f2848429..92d323b57 100644 --- a/Tests/web3swiftTests/remoteTests/EIP1559Tests.swift +++ b/Tests/web3swiftTests/remoteTests/EIP1559Tests.swift @@ -1,6 +1,6 @@ // // EIP1559Tests.swift -// +// // // Created by Jann Driessen on 01.11.22. // @@ -10,10 +10,11 @@ import Web3Core @testable import web3swift +// swiftlint:disable force_unwrapping final class EIP1559Tests: XCTestCase { func testEIP1159MainnetTransaction() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) var tx = CodableTransaction( type: .eip1559, to: EthereumAddress("0xb47292B7bBedA4447564B8336E4eD1f93735e7C7")!, @@ -29,7 +30,7 @@ final class EIP1559Tests: XCTestCase { } func testEIP1159GoerliTransaction() async throws { - let web3 = await Web3.InfuraGoerliWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraGoerliWeb3(accessToken: Constants.infuraToken) var tx = CodableTransaction( type: .eip1559, to: EthereumAddress("0xeBec795c9c8bBD61FFc14A6662944748F299cAcf")!, diff --git a/Tests/web3swiftTests/remoteTests/ENSTests.swift b/Tests/web3swiftTests/remoteTests/ENSTests.swift index 052142bd9..a21c5f848 100755 --- a/Tests/web3swiftTests/remoteTests/ENSTests.swift +++ b/Tests/web3swiftTests/remoteTests/ENSTests.swift @@ -23,16 +23,16 @@ class ENSTests: XCTestCase { } func testResolverAddress() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let address = try await ens?.registry.getResolver(forDomain: domain).resolverContractAddress - + XCTAssertEqual(address?.address.lowercased(), "0x4976fb03c32e5b8cfe2b6ccb31c09ba78ebaba41") } func testResolver() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let address = try await ens?.getAddress(forNode: domain) @@ -40,7 +40,7 @@ class ENSTests: XCTestCase { } func testSupportsInterface() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let resolver = try await ens?.registry.getResolver(forDomain: domain) @@ -55,7 +55,7 @@ class ENSTests: XCTestCase { } func testABI() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let resolver = try await ens?.registry.getResolver(forDomain: domain) @@ -70,7 +70,7 @@ class ENSTests: XCTestCase { } func testOwner() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let owner = try await ens?.registry.getOwner(node: domain) @@ -78,7 +78,7 @@ class ENSTests: XCTestCase { } func testTTL() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = try XCTUnwrap(ENS(web3: web3)) let domain = "somename.eth" let ttl = try await ens.registry.getTTL(node: domain) @@ -86,7 +86,7 @@ class ENSTests: XCTestCase { } func testGetAddress() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let resolver = try await ens?.registry.getResolver(forDomain: domain) @@ -95,7 +95,7 @@ class ENSTests: XCTestCase { } func testGetPubkey() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let ens = ENS(web3: web3) let domain = "somename.eth" let resolver = try await ens?.registry.getResolver(forDomain: domain) diff --git a/Tests/web3swiftTests/remoteTests/EtherscanTransactionCheckerTests.swift b/Tests/web3swiftTests/remoteTests/EtherscanTransactionCheckerTests.swift index c58d2fa44..88de5f92b 100644 --- a/Tests/web3swiftTests/remoteTests/EtherscanTransactionCheckerTests.swift +++ b/Tests/web3swiftTests/remoteTests/EtherscanTransactionCheckerTests.swift @@ -13,7 +13,7 @@ final class EtherscanTransactionCheckerTests: XCTestCase { func testHasTransactions() async throws { let sut = EtherscanTransactionChecker(urlSession: URLSession.shared, apiKey: testApiKey) - + let result = try await sut.hasTransactions(ethereumAddress: try XCTUnwrap(EthereumAddress(vitaliksAddress))) XCTAssertTrue(result) diff --git a/Tests/web3swiftTests/remoteTests/GasOracleTests.swift b/Tests/web3swiftTests/remoteTests/GasOracleTests.swift index e2c51ec75..b5b3ac195 100644 --- a/Tests/web3swiftTests/remoteTests/GasOracleTests.swift +++ b/Tests/web3swiftTests/remoteTests/GasOracleTests.swift @@ -16,7 +16,7 @@ class GasOracleTests: XCTestCase { let blockNumber: BigUInt = 14571792 func testPretictBaseFee() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) lazy var oracle: Oracle = .init(web3.provider, block: .exact(blockNumber), blockCount: 20, percentiles: [10, 40, 60, 90]) let etalonPercentiles: [BigUInt] = [ 94217344703, // 10 percentile @@ -30,7 +30,7 @@ class GasOracleTests: XCTestCase { } func testPredictTip() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) lazy var oracle: Oracle = .init(web3.provider, block: .exact(blockNumber), blockCount: 20, percentiles: [10, 40, 60, 90]) let etalonPercentiles: [BigUInt] = [ 1217066957, // 10 percentile @@ -44,7 +44,7 @@ class GasOracleTests: XCTestCase { } func testPredictBothFee() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) lazy var oracle: Oracle = .init(web3.provider, block: .exact(blockNumber), blockCount: 20, percentiles: [10, 40, 60, 90]) let etalonPercentiles: ([BigUInt], [BigUInt]) = ( baseFee: [ @@ -67,7 +67,7 @@ class GasOracleTests: XCTestCase { } // func testPredictLegacyGasPrice() async throws { -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // lazy var oracle: Web3.Oracle = .init(web3, block: .exact(blockNumber), blockCount: 20, percentiles: [10, 40, 60, 90]) // let etalonPercentiles: [BigUInt] = [ // 93253857566, // 10 percentile @@ -75,13 +75,13 @@ class GasOracleTests: XCTestCase { // 111000000000, // 60 percentile // 127210686305 // 90 percentile // ] -// +// // let gasPriceLegacyPercentiles = await oracle.gasPriceLegacyPercentiles() // XCTAssertEqual(gasPriceLegacyPercentiles, etalonPercentiles, "Arrays should be equal") // } // // func testAllTransactionInBlockDecodesWell() async throws { -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // lazy var oracle: Web3.Oracle = .init(web3, block: .exact(blockNumber), blockCount: 20, percentiles: [10, 40, 60, 90]) // let blockWithTransaction = try await web3.eth.getBlockByNumber(blockNumber, fullTransactions: true) // @@ -95,14 +95,14 @@ class GasOracleTests: XCTestCase { // FIXME: Move it to external test suit. // func testBlockNumber() async throws { -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // let latestBlockNumber = try await web3.eth.getBlockNumber() -// +// // } // // func testgetAccounts() async throws { -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // let accounts = try await web3.eth.getAccounts() -// +// // } } diff --git a/Tests/web3swiftTests/remoteTests/InfuraTests.swift b/Tests/web3swiftTests/remoteTests/InfuraTests.swift index c53020293..fec9289ef 100755 --- a/Tests/web3swiftTests/remoteTests/InfuraTests.swift +++ b/Tests/web3swiftTests/remoteTests/InfuraTests.swift @@ -12,7 +12,7 @@ import Web3Core class InfuraTests: XCTestCase { func testGetBalance() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let address = EthereumAddress("0xd61b5ca425F8C8775882d4defefC68A6979DBbce")! let balance = try await web3.eth.getBalance(for: address) let balString = Utilities.formatToPrecision(balance, units: .ether, formattingDecimals: 3) @@ -20,30 +20,30 @@ class InfuraTests: XCTestCase { } func testGetBlockByHash() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let result = try await web3.eth.block(by: "0x6d05ba24da6b7a1af22dc6cc2a1fe42f58b2a5ea4c406b19c8cf672ed8ec0695", fullTransactions: false) XCTAssertEqual(result.number, 5184323) } func testGetBlockByHash_hashAsData() async throws { let blockHash = Data.fromHex("6d05ba24da6b7a1af22dc6cc2a1fe42f58b2a5ea4c406b19c8cf672ed8ec0695")! - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let result = try await web3.eth.block(by: blockHash, fullTransactions: false) XCTAssertEqual(result.number, 5184323) } func testGetBlockByNumber1() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) _ = try await web3.eth.block(by: .latest, fullTransactions: false) } func testGetBlockByNumber2() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) _ = try await web3.eth.block(by: .exact(5184323), fullTransactions: true) } - func testGetBlockByNumber3() async { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + func testGetBlockByNumber3() async throws { + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) do { _ = try await web3.eth.block(by: .exact(10000000000000), fullTransactions: true) XCTFail("The expression above must throw DecodingError.") @@ -54,13 +54,13 @@ class InfuraTests: XCTestCase { } func testGasPrice() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) _ = try await web3.eth.gasPrice() } // func testGetIndexedEventsPromise() async throws { // let jsonString = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_initialAmount\",\"type\":\"uint256\"},{\"name\":\"_tokenName\",\"type\":\"string\"},{\"name\":\"_decimalUnits\",\"type\":\"uint8\"},{\"name\":\"_tokenSymbol\",\"type\":\"string\"}],\"type\":\"constructor\"},{\"payable\":false,\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},]" -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // let contract = web3.contract(jsonString, at: nil, abiVersion: 2) // var filter = EventFilterParameters() // filter.fromBlock = .exact(5200120) @@ -69,7 +69,7 @@ class InfuraTests: XCTestCase { // filter.topics = [EventFilterParameters.Topic.strings([EventFilterParameters.Topic.string("0xefdcf2c36f3756ce7247628afdb632fa4ee12ec5"), EventFilterParameters.Topic.string(nil)])] // // need // let eventParserResult = try await contract!.getIndexedEvents(eventName: "Transfer", filter: filter, joinWithReceipts: true) -// +// // XCTAssert(eventParserResult.count == 2) // XCTAssert(eventParserResult.first?.transactionReceipt != nil) // XCTAssert(eventParserResult.first?.eventLog != nil) @@ -84,10 +84,10 @@ class InfuraTests: XCTestCase { // filter.parameterFilters = [([EthereumAddress("0xefdcf2c36f3756ce7247628afdb632fa4ee12ec5")!] as [EventFilterable]), ([EthereumAddress("0xd5395c132c791a7f46fa8fc27f0ab6bacd824484")!] as [EventFilterable])] // guard let eventParser = contract?.createEventParser("Transfer", filter: filter) else {return XCTFail()} // let present = try eventParser.parseBlockByNumberPromise(UInt64(5200120)).wait() -// +// // XCTAssert(present.count == 1) // } -// +// // func testUserCaseEventParsing() throws { // let contractAddress = EthereumAddress("0x7ff546aaccd379d2d1f241e1d29cdd61d4d50778") // let jsonString = "[{\"constant\":false,\"inputs\":[{\"name\":\"_id\",\"type\":\"string\"}],\"name\":\"deposit\",\"outputs\":[],\"payable\":true,\"stateMutability\":\"payable\",\"type\":\"function\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_id\",\"type\":\"string\"},{\"indexed\":true,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Deposit\",\"type\":\"event\"}]" diff --git a/Tests/web3swiftTests/remoteTests/PolicyResolverTests.swift b/Tests/web3swiftTests/remoteTests/PolicyResolverTests.swift index 7e10946a5..a21aa6273 100644 --- a/Tests/web3swiftTests/remoteTests/PolicyResolverTests.swift +++ b/Tests/web3swiftTests/remoteTests/PolicyResolverTests.swift @@ -1,6 +1,6 @@ // // PolicyResolverTests.swift -// +// // // Created by Jann Driessen on 01.11.22. // @@ -11,10 +11,11 @@ import Web3Core @testable import web3swift +// swiftlint:disable force_unwrapping final class PolicyResolverTests: XCTestCase { func testResolveAllForEIP1159Transaction() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let resolver = PolicyResolver(provider: web3.provider) var tx = CodableTransaction( type: .eip1559, @@ -27,8 +28,7 @@ final class PolicyResolverTests: XCTestCase { tx.from = EthereumAddress("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B")! let policies = Policies(gasLimitPolicy: .manual(21_000)) try await resolver.resolveAll(for: &tx, with: policies) - - + XCTAssertGreaterThan(tx.gasLimit, 0) XCTAssertGreaterThan(tx.maxFeePerGas ?? 0, 0) XCTAssertGreaterThan(tx.maxPriorityFeePerGas ?? 0, 0) @@ -36,7 +36,7 @@ final class PolicyResolverTests: XCTestCase { } func testResolveAllForLegacyTransaction() async throws { - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let resolver = PolicyResolver(provider: web3.provider) var tx = CodableTransaction( type: .legacy, @@ -49,8 +49,7 @@ final class PolicyResolverTests: XCTestCase { tx.from = EthereumAddress("0xAb5801a7D398351b8bE11C439e05C5B3259aeC9B")! let policies = Policies(gasLimitPolicy: .manual(21_000)) try await resolver.resolveAll(for: &tx, with: policies) - - + XCTAssertGreaterThan(tx.gasLimit, 0) XCTAssertGreaterThan(tx.gasPrice ?? 0, 0) XCTAssertGreaterThan(tx.nonce, 0) @@ -61,7 +60,7 @@ final class PolicyResolverTests: XCTestCase { let expectedGasLimit = BigUInt(22_000) let expectedBaseFee = BigUInt(20) let expectedPriorityFee = BigUInt(9) - let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) + let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) let resolver = PolicyResolver(provider: web3.provider) var tx = CodableTransaction( type: .eip1559, diff --git a/Tests/web3swiftTests/remoteTests/RemoteParsingTests.swift b/Tests/web3swiftTests/remoteTests/RemoteParsingTests.swift index b4b272b20..80acf0622 100755 --- a/Tests/web3swiftTests/remoteTests/RemoteParsingTests.swift +++ b/Tests/web3swiftTests/remoteTests/RemoteParsingTests.swift @@ -14,23 +14,23 @@ import Web3Core class RemoteParsingTests: XCTestCase { // func testEventParsing1usingABIv2() throws { -// +// // let jsonString = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_initialAmount\",\"type\":\"uint256\"},{\"name\":\"_tokenName\",\"type\":\"string\"},{\"name\":\"_decimalUnits\",\"type\":\"uint8\"},{\"name\":\"_tokenSymbol\",\"type\":\"string\"}],\"type\":\"constructor\"},{\"payable\":false,\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},]" -// +// // let contractAddress = EthereumAddress("0x45245bc59219eeaaf6cd3f382e078a461ff9de7b") -// +// // let web3 = Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) -// +// // let contract = web3.contract(jsonString, at: contractAddress, abiVersion: 2) -// +// // guard let eventParser = contract?.createEventParser("Transfer", filter: nil) else {return XCTFail()} -// +// // let present = try eventParser.parseBlockByNumber(UInt64(5200088)) -// +// // XCTAssert(present.count == 1) -// +// // let decoded = present[0].decodedResult -// +// // XCTAssert(decoded["name"] as! String == "Transfer") // XCTAssert(decoded["_to"] as! EthereumAddress == EthereumAddress("0xa5dcf6e0fee38f635c4a8d50d90e24400ed547d2")!) // XCTAssert(decoded["_from"] as! EthereumAddress == EthereumAddress("0xdbf493e8d7db835192c02b992bd1ab72e96fd2e3")!) @@ -65,7 +65,7 @@ class RemoteParsingTests: XCTestCase { // let present = try eventParser.parseBlockByNumber(i) // for p in present { // + "\n") -// +// // .addHexPrefix() + "\n") // .address + "\n") // .address + "\n") @@ -91,7 +91,7 @@ class RemoteParsingTests: XCTestCase { // func testEventParsing5usingABIv2() async throws { // let jsonString = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_initialAmount\",\"type\":\"uint256\"},{\"name\":\"_tokenName\",\"type\":\"string\"},{\"name\":\"_decimalUnits\",\"type\":\"uint8\"},{\"name\":\"_tokenSymbol\",\"type\":\"string\"}],\"type\":\"constructor\"},{\"payable\":false,\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},]" -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // let contract = web3.contract(jsonString, at: nil, abiVersion: 2) // var filter = EventFilter() // filter.fromBlock = .exact(5200120) @@ -104,7 +104,7 @@ class RemoteParsingTests: XCTestCase { // func testEventParsing6usingABIv2() async throws { // let jsonString = "[{\"constant\":true,\"inputs\":[],\"name\":\"name\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"approve\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"totalSupply\",\"outputs\":[{\"name\":\"\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_from\",\"type\":\"address\"},{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transferFrom\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"decimals\",\"outputs\":[{\"name\":\"\",\"type\":\"uint8\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"version\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"}],\"name\":\"balanceOf\",\"outputs\":[{\"name\":\"balance\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[],\"name\":\"symbol\",\"outputs\":[{\"name\":\"\",\"type\":\"string\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_to\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"transfer\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":false,\"inputs\":[{\"name\":\"_spender\",\"type\":\"address\"},{\"name\":\"_value\",\"type\":\"uint256\"},{\"name\":\"_extraData\",\"type\":\"bytes\"}],\"name\":\"approveAndCall\",\"outputs\":[{\"name\":\"success\",\"type\":\"bool\"}],\"payable\":false,\"type\":\"function\"},{\"constant\":true,\"inputs\":[{\"name\":\"_owner\",\"type\":\"address\"},{\"name\":\"_spender\",\"type\":\"address\"}],\"name\":\"allowance\",\"outputs\":[{\"name\":\"remaining\",\"type\":\"uint256\"}],\"payable\":false,\"type\":\"function\"},{\"inputs\":[{\"name\":\"_initialAmount\",\"type\":\"uint256\"},{\"name\":\"_tokenName\",\"type\":\"string\"},{\"name\":\"_decimalUnits\",\"type\":\"uint8\"},{\"name\":\"_tokenSymbol\",\"type\":\"string\"}],\"type\":\"constructor\"},{\"payable\":false,\"type\":\"fallback\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_from\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_to\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Transfer\",\"type\":\"event\"},{\"anonymous\":false,\"inputs\":[{\"indexed\":true,\"name\":\"_owner\",\"type\":\"address\"},{\"indexed\":true,\"name\":\"_spender\",\"type\":\"address\"},{\"indexed\":false,\"name\":\"_value\",\"type\":\"uint256\"}],\"name\":\"Approval\",\"type\":\"event\"},]" -// let web3 = await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) +// let web3 = try await Web3.InfuraMainnetWeb3(accessToken: Constants.infuraToken) // let contract = web3.contract(jsonString, at: nil, abiVersion: 2) // var filter = EventFilter() // filter.fromBlock = .exact(5200120)